import { printIdentifier, formatTypeSpec, paramMessage, createTypeSpecLibrary, serializeValueAsJson, getEncode, isTemplateDeclaration, getOpExamples, ignoreDiagnostics, getDiscriminator, getDiscriminatedUnion, getNamespaceFullName, isNeverType, resolveEncodedName, isArrayModelType, explainStringTemplateNotSerializable, compilerAssert, isSecret, getKnownValues, getTypeName, getSummary, getMinLength, getMaxLength, getMinValue, getMaxValue, getPattern, getMinItems, getMaxItems, getFormat, getDoc, getDeprecated, getExamples, getMinValueExclusive, getMaxValueExclusive, isNullType, navigateTypesInNamespace, resolvePath, emitFile, listServices, getService, interpolatePath, isDeprecated, getAllTags, isVoidType, isGlobalNamespace, getAnyExtensionFromPath, createDiagnosticCollector } from '@typespec/compiler';
import { ObjectBuilder, TypeEmitter, Placeholder, ArrayBuilder, createAssetEmitter } from '@typespec/compiler/emitter-framework';
import { unsafe_mutateSubgraphWithNamespace } from '@typespec/compiler/experimental';
import { Visibility, getVisibilitySuffix, getHttpOperation, resolveRequestVisibility, getHttpService, resolveAuthentication, reportIfNoRoutes, getStatusCodeDescription, isContentTypeHeader, createMetadataInfo, getServers, isOverloadSameEndpoint, isOrExtendsHttpFile } from '@typespec/http';
import { isDefaultResponse, getExtensions as getExtensions$1, getOpenAPITypeName, getExternalDocs, isReadonlyProperty, shouldInline, checkDuplicateTypeName, resolveInfo, resolveOperationId, getParameterKey, getTagsMetadata } from '@typespec/openapi';
import { getVersioningMutators } from '@typespec/versioning';
import { TwoLevelMap } from '@typespec/compiler/utils';

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 (n.__esModule) return n;
  var f = n.default;
	if (typeof f == "function") {
		var a = function a () {
			if (this instanceof a) {
        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 util$2 = {};

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

// shim for using process in browser
var process = browser$1.exports = {};

// cached from whatever global is present so that test runners that stub it
// don't break things.  But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals.  It's inside a
// function because try/catches deoptimize in certain engines.

var cachedSetTimeout;
var cachedClearTimeout;

function defaultSetTimout() {
    throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
    throw new Error('clearTimeout has not been defined');
}
(function () {
    try {
        if (typeof setTimeout === 'function') {
            cachedSetTimeout = setTimeout;
        } else {
            cachedSetTimeout = defaultSetTimout;
        }
    } catch (e) {
        cachedSetTimeout = defaultSetTimout;
    }
    try {
        if (typeof clearTimeout === 'function') {
            cachedClearTimeout = clearTimeout;
        } else {
            cachedClearTimeout = defaultClearTimeout;
        }
    } catch (e) {
        cachedClearTimeout = defaultClearTimeout;
    }
} ());
function runTimeout(fun) {
    if (cachedSetTimeout === setTimeout) {
        //normal enviroments in sane situations
        return setTimeout(fun, 0);
    }
    // if setTimeout wasn't available but was latter defined
    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
        cachedSetTimeout = setTimeout;
        return setTimeout(fun, 0);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedSetTimeout(fun, 0);
    } catch(e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
            return cachedSetTimeout.call(null, fun, 0);
        } catch(e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
            return cachedSetTimeout.call(this, fun, 0);
        }
    }


}
function runClearTimeout(marker) {
    if (cachedClearTimeout === clearTimeout) {
        //normal enviroments in sane situations
        return clearTimeout(marker);
    }
    // if clearTimeout wasn't available but was latter defined
    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
        cachedClearTimeout = clearTimeout;
        return clearTimeout(marker);
    }
    try {
        // when when somebody has screwed with setTimeout but no I.E. maddness
        return cachedClearTimeout(marker);
    } catch (e){
        try {
            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
            return cachedClearTimeout.call(null, marker);
        } catch (e){
            // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
            return cachedClearTimeout.call(this, marker);
        }
    }



}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;

function cleanUpNextTick() {
    if (!draining || !currentQueue) {
        return;
    }
    draining = false;
    if (currentQueue.length) {
        queue = currentQueue.concat(queue);
    } else {
        queueIndex = -1;
    }
    if (queue.length) {
        drainQueue();
    }
}

function drainQueue() {
    if (draining) {
        return;
    }
    var timeout = runTimeout(cleanUpNextTick);
    draining = true;

    var len = queue.length;
    while(len) {
        currentQueue = queue;
        queue = [];
        while (++queueIndex < len) {
            if (currentQueue) {
                currentQueue[queueIndex].run();
            }
        }
        queueIndex = -1;
        len = queue.length;
    }
    currentQueue = null;
    draining = false;
    runClearTimeout(timeout);
}

process.nextTick = function (fun) {
    var args = new Array(arguments.length - 1);
    if (arguments.length > 1) {
        for (var i = 1; i < arguments.length; i++) {
            args[i - 1] = arguments[i];
        }
    }
    queue.push(new Item(fun, args));
    if (queue.length === 1 && !draining) {
        runTimeout(drainQueue);
    }
};

// v8 likes predictible objects
function Item(fun, array) {
    this.fun = fun;
    this.array = array;
}
Item.prototype.run = function () {
    this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};

function noop$1() {}

process.on = noop$1;
process.addListener = noop$1;
process.once = noop$1;
process.off = noop$1;
process.removeListener = noop$1;
process.removeAllListeners = noop$1;
process.emit = noop$1;
process.prependListener = noop$1;
process.prependOnceListener = noop$1;

process.listeners = function (name) { return [] };

process.binding = function (name) {
    throw new Error('process.binding is not supported');
};

process.cwd = function () { return '/' };
process.chdir = function (dir) {
    throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };

function noop() {}
var browser = /** @type {boolean} */browser$1.exports.browser;
var emitWarning = noop;
var binding = /** @type {Function} */browser$1.exports.binding;
var exit = noop;
var pid = 1;
var features = {};
var kill = noop;
var dlopen = noop;
var uptime = noop;
var memoryUsage = noop;
var uvCounters = noop;
var platform = 'browser';
var arch = 'browser';
var execPath = 'browser';
var execArgv = /** @type {string[]} */[];
var api = {
  nextTick: browser$1.exports.nextTick,
  title: browser$1.exports.title,
  browser: browser,
  env: browser$1.exports.env,
  argv: browser$1.exports.argv,
  version: browser$1.exports.version,
  versions: browser$1.exports.versions,
  on: browser$1.exports.on,
  addListener: browser$1.exports.addListener,
  once: browser$1.exports.once,
  off: browser$1.exports.off,
  removeListener: browser$1.exports.removeListener,
  removeAllListeners: browser$1.exports.removeAllListeners,
  emit: browser$1.exports.emit,
  emitWarning: emitWarning,
  prependListener: browser$1.exports.prependListener,
  prependOnceListener: browser$1.exports.prependOnceListener,
  listeners: browser$1.exports.listeners,
  binding: binding,
  cwd: browser$1.exports.cwd,
  chdir: browser$1.exports.chdir,
  umask: browser$1.exports.umask,
  exit: exit,
  pid: pid,
  features: features,
  kill: kill,
  dlopen: dlopen,
  uptime: uptime,
  memoryUsage: memoryUsage,
  uvCounters: uvCounters,
  platform: platform,
  arch: arch,
  execPath: execPath,
  execArgv: execArgv
};

browser$1.exports.addListener;
browser$1.exports.argv;
browser$1.exports.chdir;
browser$1.exports.cwd;
browser$1.exports.emit;
browser$1.exports.env;
browser$1.exports.listeners;
browser$1.exports.nextTick;
browser$1.exports.off;
browser$1.exports.on;
browser$1.exports.once;
browser$1.exports.prependListener;
browser$1.exports.prependOnceListener;
browser$1.exports.removeAllListeners;
browser$1.exports.removeListener;
browser$1.exports.title;
browser$1.exports.umask;
browser$1.exports.version;
browser$1.exports.versions;

var util$1 = {};

var types$1 = {};

var shams$1;
var hasRequiredShams$1;

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

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

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

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

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

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

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

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

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

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

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

		return true;
	};
	return shams$1;
}

var shams;
var hasRequiredShams;

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

	var hasSymbols = requireShams$1();

	/** @type {import('.')} */
	shams = function hasToStringTagShams() {
		return hasSymbols() && !!Symbol.toStringTag;
	};
	return shams;
}

var esObjectAtoms;
var hasRequiredEsObjectAtoms;

function requireEsObjectAtoms () {
	if (hasRequiredEsObjectAtoms) return esObjectAtoms;
	hasRequiredEsObjectAtoms = 1;

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

var esErrors;
var hasRequiredEsErrors;

function requireEsErrors () {
	if (hasRequiredEsErrors) return esErrors;
	hasRequiredEsErrors = 1;

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

var _eval;
var hasRequired_eval;

function require_eval () {
	if (hasRequired_eval) return _eval;
	hasRequired_eval = 1;

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

var range;
var hasRequiredRange;

function requireRange () {
	if (hasRequiredRange) return range;
	hasRequiredRange = 1;

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

var ref$2;
var hasRequiredRef$2;

function requireRef$2 () {
	if (hasRequiredRef$2) return ref$2;
	hasRequiredRef$2 = 1;

	/** @type {import('./ref')} */
	ref$2 = ReferenceError;
	return ref$2;
}

var syntax;
var hasRequiredSyntax;

function requireSyntax () {
	if (hasRequiredSyntax) return syntax;
	hasRequiredSyntax = 1;

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

var type$f;
var hasRequiredType$1;

function requireType$1 () {
	if (hasRequiredType$1) return type$f;
	hasRequiredType$1 = 1;

	/** @type {import('./type')} */
	type$f = TypeError;
	return type$f;
}

var uri$1;
var hasRequiredUri$1;

function requireUri$1 () {
	if (hasRequiredUri$1) return uri$1;
	hasRequiredUri$1 = 1;

	/** @type {import('./uri')} */
	uri$1 = URIError;
	return uri$1;
}

var abs;
var hasRequiredAbs;

function requireAbs () {
	if (hasRequiredAbs) return abs;
	hasRequiredAbs = 1;

	/** @type {import('./abs')} */
	abs = Math.abs;
	return abs;
}

var floor;
var hasRequiredFloor;

function requireFloor () {
	if (hasRequiredFloor) return floor;
	hasRequiredFloor = 1;

	/** @type {import('./floor')} */
	floor = Math.floor;
	return floor;
}

var max;
var hasRequiredMax;

function requireMax () {
	if (hasRequiredMax) return max;
	hasRequiredMax = 1;

	/** @type {import('./max')} */
	max = Math.max;
	return max;
}

var min;
var hasRequiredMin;

function requireMin () {
	if (hasRequiredMin) return min;
	hasRequiredMin = 1;

	/** @type {import('./min')} */
	min = Math.min;
	return min;
}

var pow;
var hasRequiredPow;

function requirePow () {
	if (hasRequiredPow) return pow;
	hasRequiredPow = 1;

	/** @type {import('./pow')} */
	pow = Math.pow;
	return pow;
}

var round;
var hasRequiredRound;

function requireRound () {
	if (hasRequiredRound) return round;
	hasRequiredRound = 1;

	/** @type {import('./round')} */
	round = Math.round;
	return round;
}

var _isNaN;
var hasRequired_isNaN;

function require_isNaN () {
	if (hasRequired_isNaN) return _isNaN;
	hasRequired_isNaN = 1;

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

var sign;
var hasRequiredSign;

function requireSign () {
	if (hasRequiredSign) return sign;
	hasRequiredSign = 1;

	var $isNaN = /*@__PURE__*/ require_isNaN();

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

var gOPD;
var hasRequiredGOPD;

function requireGOPD () {
	if (hasRequiredGOPD) return gOPD;
	hasRequiredGOPD = 1;

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

var gopd;
var hasRequiredGopd;

function requireGopd () {
	if (hasRequiredGopd) return gopd;
	hasRequiredGopd = 1;

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

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

	gopd = $gOPD;
	return gopd;
}

var esDefineProperty;
var hasRequiredEsDefineProperty;

function requireEsDefineProperty () {
	if (hasRequiredEsDefineProperty) return esDefineProperty;
	hasRequiredEsDefineProperty = 1;

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

	esDefineProperty = $defineProperty;
	return esDefineProperty;
}

var hasSymbols;
var hasRequiredHasSymbols;

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

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

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

		return hasSymbolSham();
	};
	return hasSymbols;
}

var Reflect_getPrototypeOf;
var hasRequiredReflect_getPrototypeOf;

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

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

var Object_getPrototypeOf;
var hasRequiredObject_getPrototypeOf;

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

	var $Object = /*@__PURE__*/ requireEsObjectAtoms();

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

var implementation;
var hasRequiredImplementation;

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

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

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

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

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

	    return arr;
	};

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

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

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

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

	    };

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

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

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

	    return bound;
	};
	return implementation;
}

var functionBind;
var hasRequiredFunctionBind;

function requireFunctionBind () {
	if (hasRequiredFunctionBind) return functionBind;
	hasRequiredFunctionBind = 1;

	var implementation = requireImplementation();

	functionBind = Function.prototype.bind || implementation;
	return functionBind;
}

var functionCall;
var hasRequiredFunctionCall;

function requireFunctionCall () {
	if (hasRequiredFunctionCall) return functionCall;
	hasRequiredFunctionCall = 1;

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

var functionApply;
var hasRequiredFunctionApply;

function requireFunctionApply () {
	if (hasRequiredFunctionApply) return functionApply;
	hasRequiredFunctionApply = 1;

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

var reflectApply;
var hasRequiredReflectApply;

function requireReflectApply () {
	if (hasRequiredReflectApply) return reflectApply;
	hasRequiredReflectApply = 1;

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

var actualApply;
var hasRequiredActualApply;

function requireActualApply () {
	if (hasRequiredActualApply) return actualApply;
	hasRequiredActualApply = 1;

	var bind = requireFunctionBind();

	var $apply = requireFunctionApply();
	var $call = requireFunctionCall();
	var $reflectApply = requireReflectApply();

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

var callBindApplyHelpers;
var hasRequiredCallBindApplyHelpers;

function requireCallBindApplyHelpers () {
	if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers;
	hasRequiredCallBindApplyHelpers = 1;

	var bind = requireFunctionBind();
	var $TypeError = /*@__PURE__*/ requireType$1();

	var $call = requireFunctionCall();
	var $actualApply = requireActualApply();

	/** @type {import('.')} */
	callBindApplyHelpers = function callBindBasic(args) {
		if (args.length < 1 || typeof args[0] !== 'function') {
			throw new $TypeError('a function is required');
		}
		return $actualApply(bind, $call, args);
	};
	return callBindApplyHelpers;
}

var get;
var hasRequiredGet;

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

	var callBind = requireCallBindApplyHelpers();
	var gOPD = /*@__PURE__*/ requireGopd();

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

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

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

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

var getProto;
var hasRequiredGetProto;

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

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

	var getDunderProto = /*@__PURE__*/ requireGet();

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

var hasown;
var hasRequiredHasown;

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

	var call = Function.prototype.call;
	var $hasOwn = Object.prototype.hasOwnProperty;
	var bind = requireFunctionBind();

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

var getIntrinsic;
var hasRequiredGetIntrinsic;

function requireGetIntrinsic () {
	if (hasRequiredGetIntrinsic) return getIntrinsic;
	hasRequiredGetIntrinsic = 1;

	var undefined$1;

	var $Object = /*@__PURE__*/ requireEsObjectAtoms();

	var $Error = /*@__PURE__*/ requireEsErrors();
	var $EvalError = /*@__PURE__*/ require_eval();
	var $RangeError = /*@__PURE__*/ requireRange();
	var $ReferenceError = /*@__PURE__*/ requireRef$2();
	var $SyntaxError = /*@__PURE__*/ requireSyntax();
	var $TypeError = /*@__PURE__*/ requireType$1();
	var $URIError = /*@__PURE__*/ requireUri$1();

	var abs = /*@__PURE__*/ requireAbs();
	var floor = /*@__PURE__*/ requireFloor();
	var max = /*@__PURE__*/ requireMax();
	var min = /*@__PURE__*/ requireMin();
	var pow = /*@__PURE__*/ requirePow();
	var round = /*@__PURE__*/ requireRound();
	var sign = /*@__PURE__*/ requireSign();

	var $Function = Function;

	// eslint-disable-next-line consistent-return
	var getEvalledConstructor = function (expressionSyntax) {
		try {
			return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
		} catch (e) {}
	};

	var $gOPD = /*@__PURE__*/ requireGopd();
	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

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

	var hasSymbols = requireHasSymbols()();

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

	var $apply = requireFunctionApply();
	var $call = requireFunctionCall();

	var needsEval = {};

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

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

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

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

	var doEval = function doEval(name) {
		var value;
		if (name === '%AsyncFunction%') {
			value = getEvalledConstructor('async function () {}');
		} else if (name === '%GeneratorFunction%') {
			value = getEvalledConstructor('function* () {}');
		} else if (name === '%AsyncGeneratorFunction%') {
			value = getEvalledConstructor('async function* () {}');
		} else if (name === '%AsyncGenerator%') {
			var fn = doEval('%AsyncGeneratorFunction%');
			if (fn) {
				value = fn.prototype;
			}
		} else if (name === '%AsyncIteratorPrototype%') {
			var gen = doEval('%AsyncGenerator%');
			if (gen && getProto) {
				value = getProto(gen.prototype);
			}
		}

		INTRINSICS[name] = value;

		return value;
	};

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

	var bind = requireFunctionBind();
	var hasOwn = /*@__PURE__*/ requireHasown();
	var $concat = bind.call($call, Array.prototype.concat);
	var $spliceApply = bind.call($apply, Array.prototype.splice);
	var $replace = bind.call($call, String.prototype.replace);
	var $strSlice = bind.call($call, String.prototype.slice);
	var $exec = bind.call($call, RegExp.prototype.exec);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

var callBound;
var hasRequiredCallBound;

function requireCallBound () {
	if (hasRequiredCallBound) return callBound;
	hasRequiredCallBound = 1;

	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();

	var callBindBasic = requireCallBindApplyHelpers();

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

	/** @type {import('.')} */
	callBound = function callBoundIntrinsic(name, allowMissing) {
		// eslint-disable-next-line no-extra-parens
		var intrinsic = /** @type {Parameters<typeof callBindBasic>[0][0]} */ (GetIntrinsic(name, !!allowMissing));
		if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) {
			return callBindBasic([intrinsic]);
		}
		return intrinsic;
	};
	return callBound;
}

var isArguments;
var hasRequiredIsArguments;

function requireIsArguments () {
	if (hasRequiredIsArguments) return isArguments;
	hasRequiredIsArguments = 1;

	var hasToStringTag = requireShams()();
	var callBound = /*@__PURE__*/ requireCallBound();

	var $toString = callBound('Object.prototype.toString');

	/** @type {import('.')} */
	var isStandardArguments = function isArguments(value) {
		if (
			hasToStringTag
			&& value
			&& typeof value === 'object'
			&& Symbol.toStringTag in value
		) {
			return false;
		}
		return $toString(value) === '[object Arguments]';
	};

	/** @type {import('.')} */
	var isLegacyArguments = function isArguments(value) {
		if (isStandardArguments(value)) {
			return true;
		}
		return value !== null
			&& typeof value === 'object'
			&& 'length' in value
			&& typeof value.length === 'number'
			&& value.length >= 0
			&& $toString(value) !== '[object Array]'
			&& 'callee' in value
			&& $toString(value.callee) === '[object Function]';
	};

	var supportsStandardArguments = (function () {
		return isStandardArguments(arguments);
	}());

	// @ts-expect-error TODO make this not error
	isStandardArguments.isLegacyArguments = isLegacyArguments; // for tests

	/** @type {import('.')} */
	isArguments = supportsStandardArguments ? isStandardArguments : isLegacyArguments;
	return isArguments;
}

var isRegex;
var hasRequiredIsRegex;

function requireIsRegex () {
	if (hasRequiredIsRegex) return isRegex;
	hasRequiredIsRegex = 1;

	var callBound = /*@__PURE__*/ requireCallBound();
	var hasToStringTag = requireShams()();
	var hasOwn = /*@__PURE__*/ requireHasown();
	var gOPD = /*@__PURE__*/ requireGopd();

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

	if (hasToStringTag) {
		/** @type {(receiver: ThisParameterType<typeof RegExp.prototype.exec>, ...args: Parameters<typeof RegExp.prototype.exec>) => ReturnType<typeof RegExp.prototype.exec>} */
		var $exec = callBound('RegExp.prototype.exec');
		/** @type {object} */
		var isRegexMarker = {};

		var throwRegexMarker = function () {
			throw isRegexMarker;
		};
		/** @type {{ toString(): never, valueOf(): never, [Symbol.toPrimitive]?(): never }} */
		var badStringifier = {
			toString: throwRegexMarker,
			valueOf: throwRegexMarker
		};

		if (typeof Symbol.toPrimitive === 'symbol') {
			badStringifier[Symbol.toPrimitive] = throwRegexMarker;
		}

		/** @type {import('.')} */
		// @ts-expect-error TS can't figure out that the $exec call always throws
		// eslint-disable-next-line consistent-return
		fn = function isRegex(value) {
			if (!value || typeof value !== 'object') {
				return false;
			}

			// eslint-disable-next-line no-extra-parens
			var descriptor = /** @type {NonNullable<typeof gOPD>} */ (gOPD)(/** @type {{ lastIndex?: unknown }} */ (value), 'lastIndex');
			var hasLastIndexDataProperty = descriptor && hasOwn(descriptor, 'value');
			if (!hasLastIndexDataProperty) {
				return false;
			}

			try {
				// eslint-disable-next-line no-extra-parens
				$exec(value, /** @type {string} */ (/** @type {unknown} */ (badStringifier)));
			} catch (e) {
				return e === isRegexMarker;
			}
		};
	} else {
		/** @type {(receiver: ThisParameterType<typeof Object.prototype.toString>, ...args: Parameters<typeof Object.prototype.toString>) => ReturnType<typeof Object.prototype.toString>} */
		var $toString = callBound('Object.prototype.toString');
		/** @const @type {'[object RegExp]'} */
		var regexClass = '[object RegExp]';

		/** @type {import('.')} */
		fn = function isRegex(value) {
			// In older browsers, typeof regex incorrectly returns 'function'
			if (!value || (typeof value !== 'object' && typeof value !== 'function')) {
				return false;
			}

			return $toString(value) === regexClass;
		};
	}

	isRegex = fn;
	return isRegex;
}

var safeRegexTest;
var hasRequiredSafeRegexTest;

function requireSafeRegexTest () {
	if (hasRequiredSafeRegexTest) return safeRegexTest;
	hasRequiredSafeRegexTest = 1;

	var callBound = /*@__PURE__*/ requireCallBound();
	var isRegex = requireIsRegex();

	var $exec = callBound('RegExp.prototype.exec');
	var $TypeError = /*@__PURE__*/ requireType$1();

	/** @type {import('.')} */
	safeRegexTest = function regexTester(regex) {
		if (!isRegex(regex)) {
			throw new $TypeError('`regex` must be a RegExp');
		}
		return function test(s) {
			return $exec(regex, s) !== null;
		};
	};
	return safeRegexTest;
}

var isGeneratorFunction;
var hasRequiredIsGeneratorFunction;

function requireIsGeneratorFunction () {
	if (hasRequiredIsGeneratorFunction) return isGeneratorFunction;
	hasRequiredIsGeneratorFunction = 1;

	var callBound = /*@__PURE__*/ requireCallBound();
	var safeRegexTest = /*@__PURE__*/ requireSafeRegexTest();
	var isFnRegex = safeRegexTest(/^\s*(?:function)?\*/);
	var hasToStringTag = requireShams()();
	var getProto = requireGetProto();

	var toStr = callBound('Object.prototype.toString');
	var fnToStr = callBound('Function.prototype.toString');

	var getGeneratorFunc = function () { // eslint-disable-line consistent-return
		if (!hasToStringTag) {
			return false;
		}
		try {
			return Function('return function*() {}')();
		} catch (e) {
		}
	};
	/** @type {undefined | false | null | GeneratorFunctionConstructor} */
	var GeneratorFunction;

	/** @type {import('.')} */
	isGeneratorFunction = function isGeneratorFunction(fn) {
		if (typeof fn !== 'function') {
			return false;
		}
		if (isFnRegex(fnToStr(fn))) {
			return true;
		}
		if (!hasToStringTag) {
			var str = toStr(fn);
			return str === '[object GeneratorFunction]';
		}
		if (!getProto) {
			return false;
		}
		if (typeof GeneratorFunction === 'undefined') {
			var generatorFunc = getGeneratorFunc();
			GeneratorFunction = generatorFunc
				// eslint-disable-next-line no-extra-parens
				? /** @type {GeneratorFunctionConstructor} */ (getProto(generatorFunc))
				: false;
		}
		return getProto(fn) === GeneratorFunction;
	};
	return isGeneratorFunction;
}

var isCallable;
var hasRequiredIsCallable;

function requireIsCallable () {
	if (hasRequiredIsCallable) return isCallable;
	hasRequiredIsCallable = 1;

	var fnToStr = Function.prototype.toString;
	var reflectApply = typeof Reflect === 'object' && Reflect !== null && Reflect.apply;
	var badArrayLike;
	var isCallableMarker;
	if (typeof reflectApply === 'function' && typeof Object.defineProperty === 'function') {
		try {
			badArrayLike = Object.defineProperty({}, 'length', {
				get: function () {
					throw isCallableMarker;
				}
			});
			isCallableMarker = {};
			// eslint-disable-next-line no-throw-literal
			reflectApply(function () { throw 42; }, null, badArrayLike);
		} catch (_) {
			if (_ !== isCallableMarker) {
				reflectApply = null;
			}
		}
	} else {
		reflectApply = null;
	}

	var constructorRegex = /^\s*class\b/;
	var isES6ClassFn = function isES6ClassFunction(value) {
		try {
			var fnStr = fnToStr.call(value);
			return constructorRegex.test(fnStr);
		} catch (e) {
			return false; // not a function
		}
	};

	var tryFunctionObject = function tryFunctionToStr(value) {
		try {
			if (isES6ClassFn(value)) { return false; }
			fnToStr.call(value);
			return true;
		} catch (e) {
			return false;
		}
	};
	var toStr = Object.prototype.toString;
	var objectClass = '[object Object]';
	var fnClass = '[object Function]';
	var genClass = '[object GeneratorFunction]';
	var ddaClass = '[object HTMLAllCollection]'; // IE 11
	var ddaClass2 = '[object HTML document.all class]';
	var ddaClass3 = '[object HTMLCollection]'; // IE 9-10
	var hasToStringTag = typeof Symbol === 'function' && !!Symbol.toStringTag; // better: use `has-tostringtag`

	var isIE68 = !(0 in [,]); // eslint-disable-line no-sparse-arrays, comma-spacing

	var isDDA = function isDocumentDotAll() { return false; };
	if (typeof document === 'object') {
		// Firefox 3 canonicalizes DDA to undefined when it's not accessed directly
		var all = document.all;
		if (toStr.call(all) === toStr.call(document.all)) {
			isDDA = function isDocumentDotAll(value) {
				/* globals document: false */
				// in IE 6-8, typeof document.all is "object" and it's truthy
				if ((isIE68 || !value) && (typeof value === 'undefined' || typeof value === 'object')) {
					try {
						var str = toStr.call(value);
						return (
							str === ddaClass
							|| str === ddaClass2
							|| str === ddaClass3 // opera 12.16
							|| str === objectClass // IE 6-8
						) && value('') == null; // eslint-disable-line eqeqeq
					} catch (e) { /**/ }
				}
				return false;
			};
		}
	}

	isCallable = reflectApply
		? function isCallable(value) {
			if (isDDA(value)) { return true; }
			if (!value) { return false; }
			if (typeof value !== 'function' && typeof value !== 'object') { return false; }
			try {
				reflectApply(value, null, badArrayLike);
			} catch (e) {
				if (e !== isCallableMarker) { return false; }
			}
			return !isES6ClassFn(value) && tryFunctionObject(value);
		}
		: function isCallable(value) {
			if (isDDA(value)) { return true; }
			if (!value) { return false; }
			if (typeof value !== 'function' && typeof value !== 'object') { return false; }
			if (hasToStringTag) { return tryFunctionObject(value); }
			if (isES6ClassFn(value)) { return false; }
			var strClass = toStr.call(value);
			if (strClass !== fnClass && strClass !== genClass && !(/^\[object HTML/).test(strClass)) { return false; }
			return tryFunctionObject(value);
		};
	return isCallable;
}

var forEach_1;
var hasRequiredForEach;

function requireForEach () {
	if (hasRequiredForEach) return forEach_1;
	hasRequiredForEach = 1;

	var isCallable = requireIsCallable();

	var toStr = Object.prototype.toString;
	var hasOwnProperty = Object.prototype.hasOwnProperty;

	var forEachArray = function forEachArray(array, iterator, receiver) {
	    for (var i = 0, len = array.length; i < len; i++) {
	        if (hasOwnProperty.call(array, i)) {
	            if (receiver == null) {
	                iterator(array[i], i, array);
	            } else {
	                iterator.call(receiver, array[i], i, array);
	            }
	        }
	    }
	};

	var forEachString = function forEachString(string, iterator, receiver) {
	    for (var i = 0, len = string.length; i < len; i++) {
	        // no such thing as a sparse string.
	        if (receiver == null) {
	            iterator(string.charAt(i), i, string);
	        } else {
	            iterator.call(receiver, string.charAt(i), i, string);
	        }
	    }
	};

	var forEachObject = function forEachObject(object, iterator, receiver) {
	    for (var k in object) {
	        if (hasOwnProperty.call(object, k)) {
	            if (receiver == null) {
	                iterator(object[k], k, object);
	            } else {
	                iterator.call(receiver, object[k], k, object);
	            }
	        }
	    }
	};

	var forEach = function forEach(list, iterator, thisArg) {
	    if (!isCallable(iterator)) {
	        throw new TypeError('iterator must be a function');
	    }

	    var receiver;
	    if (arguments.length >= 3) {
	        receiver = thisArg;
	    }

	    if (toStr.call(list) === '[object Array]') {
	        forEachArray(list, iterator, receiver);
	    } else if (typeof list === 'string') {
	        forEachString(list, iterator, receiver);
	    } else {
	        forEachObject(list, iterator, receiver);
	    }
	};

	forEach_1 = forEach;
	return forEach_1;
}

var possibleTypedArrayNames;
var hasRequiredPossibleTypedArrayNames;

function requirePossibleTypedArrayNames () {
	if (hasRequiredPossibleTypedArrayNames) return possibleTypedArrayNames;
	hasRequiredPossibleTypedArrayNames = 1;

	/** @type {import('.')} */
	possibleTypedArrayNames = [
		'Float32Array',
		'Float64Array',
		'Int8Array',
		'Int16Array',
		'Int32Array',
		'Uint8Array',
		'Uint8ClampedArray',
		'Uint16Array',
		'Uint32Array',
		'BigInt64Array',
		'BigUint64Array'
	];
	return possibleTypedArrayNames;
}

var availableTypedArrays;
var hasRequiredAvailableTypedArrays;

function requireAvailableTypedArrays () {
	if (hasRequiredAvailableTypedArrays) return availableTypedArrays;
	hasRequiredAvailableTypedArrays = 1;

	var possibleNames = /*@__PURE__*/ requirePossibleTypedArrayNames();

	var g = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;

	/** @type {import('.')} */
	availableTypedArrays = function availableTypedArrays() {
		var /** @type {ReturnType<typeof availableTypedArrays>} */ out = [];
		for (var i = 0; i < possibleNames.length; i++) {
			if (typeof g[possibleNames[i]] === 'function') {
				// @ts-expect-error
				out[out.length] = possibleNames[i];
			}
		}
		return out;
	};
	return availableTypedArrays;
}

var callBind = {exports: {}};

var defineDataProperty;
var hasRequiredDefineDataProperty;

function requireDefineDataProperty () {
	if (hasRequiredDefineDataProperty) return defineDataProperty;
	hasRequiredDefineDataProperty = 1;

	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

	var $SyntaxError = /*@__PURE__*/ requireSyntax();
	var $TypeError = /*@__PURE__*/ requireType$1();

	var gopd = /*@__PURE__*/ requireGopd();

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

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

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

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

var hasPropertyDescriptors_1;
var hasRequiredHasPropertyDescriptors;

function requireHasPropertyDescriptors () {
	if (hasRequiredHasPropertyDescriptors) return hasPropertyDescriptors_1;
	hasRequiredHasPropertyDescriptors = 1;

	var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

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

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

	hasPropertyDescriptors_1 = hasPropertyDescriptors;
	return hasPropertyDescriptors_1;
}

var setFunctionLength;
var hasRequiredSetFunctionLength;

function requireSetFunctionLength () {
	if (hasRequiredSetFunctionLength) return setFunctionLength;
	hasRequiredSetFunctionLength = 1;

	var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic();
	var define = /*@__PURE__*/ requireDefineDataProperty();
	var hasDescriptors = /*@__PURE__*/ requireHasPropertyDescriptors()();
	var gOPD = /*@__PURE__*/ requireGopd();

	var $TypeError = /*@__PURE__*/ requireType$1();
	var $floor = GetIntrinsic('%Math.floor%');

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

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

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

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

var applyBind;
var hasRequiredApplyBind;

function requireApplyBind () {
	if (hasRequiredApplyBind) return applyBind;
	hasRequiredApplyBind = 1;

	var bind = requireFunctionBind();
	var $apply = requireFunctionApply();
	var actualApply = requireActualApply();

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

var hasRequiredCallBind;

function requireCallBind () {
	if (hasRequiredCallBind) return callBind.exports;
	hasRequiredCallBind = 1;
	(function (module) {

		var setFunctionLength = /*@__PURE__*/ requireSetFunctionLength();

		var $defineProperty = /*@__PURE__*/ requireEsDefineProperty();

		var callBindBasic = requireCallBindApplyHelpers();
		var applyBind = requireApplyBind();

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

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

var whichTypedArray;
var hasRequiredWhichTypedArray;

function requireWhichTypedArray () {
	if (hasRequiredWhichTypedArray) return whichTypedArray;
	hasRequiredWhichTypedArray = 1;

	var forEach = requireForEach();
	var availableTypedArrays = /*@__PURE__*/ requireAvailableTypedArrays();
	var callBind = requireCallBind();
	var callBound = /*@__PURE__*/ requireCallBound();
	var gOPD = /*@__PURE__*/ requireGopd();

	/** @type {(O: object) => string} */
	var $toString = callBound('Object.prototype.toString');
	var hasToStringTag = requireShams()();

	var g = typeof globalThis === 'undefined' ? commonjsGlobal : globalThis;
	var typedArrays = availableTypedArrays();

	var $slice = callBound('String.prototype.slice');
	var getPrototypeOf = Object.getPrototypeOf; // require('getprototypeof');

	/** @type {<T = unknown>(array: readonly T[], value: unknown) => number} */
	var $indexOf = callBound('Array.prototype.indexOf', true) || function indexOf(array, value) {
		for (var i = 0; i < array.length; i += 1) {
			if (array[i] === value) {
				return i;
			}
		}
		return -1;
	};

	/** @typedef {(receiver: import('.').TypedArray) => string | typeof Uint8Array.prototype.slice.call | typeof Uint8Array.prototype.set.call} Getter */
	/** @type {{ [k in `\$${import('.').TypedArrayName}`]?: Getter } & { __proto__: null }} */
	var cache = { __proto__: null };
	if (hasToStringTag && gOPD && getPrototypeOf) {
		forEach(typedArrays, function (typedArray) {
			var arr = new g[typedArray]();
			if (Symbol.toStringTag in arr) {
				var proto = getPrototypeOf(arr);
				// @ts-expect-error TS won't narrow inside a closure
				var descriptor = gOPD(proto, Symbol.toStringTag);
				if (!descriptor) {
					var superProto = getPrototypeOf(proto);
					// @ts-expect-error TS won't narrow inside a closure
					descriptor = gOPD(superProto, Symbol.toStringTag);
				}
				// @ts-expect-error TODO: fix
				cache['$' + typedArray] = callBind(descriptor.get);
			}
		});
	} else {
		forEach(typedArrays, function (typedArray) {
			var arr = new g[typedArray]();
			var fn = arr.slice || arr.set;
			if (fn) {
				// @ts-expect-error TODO: fix
				cache['$' + typedArray] = callBind(fn);
			}
		});
	}

	/** @type {(value: object) => false | import('.').TypedArrayName} */
	var tryTypedArrays = function tryAllTypedArrays(value) {
		/** @type {ReturnType<typeof tryAllTypedArrays>} */ var found = false;
		forEach(
			// eslint-disable-next-line no-extra-parens
			/** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache),
			/** @type {(getter: Getter, name: `\$${import('.').TypedArrayName}`) => void} */
			function (getter, typedArray) {
				if (!found) {
					try {
					// @ts-expect-error TODO: fix
						if ('$' + getter(value) === typedArray) {
							found = $slice(typedArray, 1);
						}
					} catch (e) { /**/ }
				}
			}
		);
		return found;
	};

	/** @type {(value: object) => false | import('.').TypedArrayName} */
	var trySlices = function tryAllSlices(value) {
		/** @type {ReturnType<typeof tryAllSlices>} */ var found = false;
		forEach(
			// eslint-disable-next-line no-extra-parens
			/** @type {Record<`\$${TypedArrayName}`, Getter>} */ /** @type {any} */ (cache),
			/** @type {(getter: typeof cache, name: `\$${import('.').TypedArrayName}`) => void} */ function (getter, name) {
				if (!found) {
					try {
						// @ts-expect-error TODO: fix
						getter(value);
						found = $slice(name, 1);
					} catch (e) { /**/ }
				}
			}
		);
		return found;
	};

	/** @type {import('.')} */
	whichTypedArray = function whichTypedArray(value) {
		if (!value || typeof value !== 'object') { return false; }
		if (!hasToStringTag) {
			/** @type {string} */
			var tag = $slice($toString(value), 8, -1);
			if ($indexOf(typedArrays, tag) > -1) {
				return tag;
			}
			if (tag !== 'Object') {
				return false;
			}
			// node < 0.6 hits here on real Typed Arrays
			return trySlices(value);
		}
		if (!gOPD) { return null; } // unknown engine
		return tryTypedArrays(value);
	};
	return whichTypedArray;
}

var isTypedArray;
var hasRequiredIsTypedArray;

function requireIsTypedArray () {
	if (hasRequiredIsTypedArray) return isTypedArray;
	hasRequiredIsTypedArray = 1;

	var whichTypedArray = /*@__PURE__*/ requireWhichTypedArray();

	/** @type {import('.')} */
	isTypedArray = function isTypedArray(value) {
		return !!whichTypedArray(value);
	};
	return isTypedArray;
}

var hasRequiredTypes$1;

function requireTypes$1 () {
	if (hasRequiredTypes$1) return types$1;
	hasRequiredTypes$1 = 1;
	(function (exports) {

		var isArgumentsObject = /*@__PURE__*/ requireIsArguments();
		var isGeneratorFunction = requireIsGeneratorFunction();
		var whichTypedArray = /*@__PURE__*/ requireWhichTypedArray();
		var isTypedArray = /*@__PURE__*/ requireIsTypedArray();

		function uncurryThis(f) {
		  return f.call.bind(f);
		}

		var BigIntSupported = typeof BigInt !== 'undefined';
		var SymbolSupported = typeof Symbol !== 'undefined';

		var ObjectToString = uncurryThis(Object.prototype.toString);

		var numberValue = uncurryThis(Number.prototype.valueOf);
		var stringValue = uncurryThis(String.prototype.valueOf);
		var booleanValue = uncurryThis(Boolean.prototype.valueOf);

		if (BigIntSupported) {
		  var bigIntValue = uncurryThis(BigInt.prototype.valueOf);
		}

		if (SymbolSupported) {
		  var symbolValue = uncurryThis(Symbol.prototype.valueOf);
		}

		function checkBoxedPrimitive(value, prototypeValueOf) {
		  if (typeof value !== 'object') {
		    return false;
		  }
		  try {
		    prototypeValueOf(value);
		    return true;
		  } catch(e) {
		    return false;
		  }
		}

		exports.isArgumentsObject = isArgumentsObject;
		exports.isGeneratorFunction = isGeneratorFunction;
		exports.isTypedArray = isTypedArray;

		// Taken from here and modified for better browser support
		// https://github.com/sindresorhus/p-is-promise/blob/cda35a513bda03f977ad5cde3a079d237e82d7ef/index.js
		function isPromise(input) {
			return (
				(
					typeof Promise !== 'undefined' &&
					input instanceof Promise
				) ||
				(
					input !== null &&
					typeof input === 'object' &&
					typeof input.then === 'function' &&
					typeof input.catch === 'function'
				)
			);
		}
		exports.isPromise = isPromise;

		function isArrayBufferView(value) {
		  if (typeof ArrayBuffer !== 'undefined' && ArrayBuffer.isView) {
		    return ArrayBuffer.isView(value);
		  }

		  return (
		    isTypedArray(value) ||
		    isDataView(value)
		  );
		}
		exports.isArrayBufferView = isArrayBufferView;


		function isUint8Array(value) {
		  return whichTypedArray(value) === 'Uint8Array';
		}
		exports.isUint8Array = isUint8Array;

		function isUint8ClampedArray(value) {
		  return whichTypedArray(value) === 'Uint8ClampedArray';
		}
		exports.isUint8ClampedArray = isUint8ClampedArray;

		function isUint16Array(value) {
		  return whichTypedArray(value) === 'Uint16Array';
		}
		exports.isUint16Array = isUint16Array;

		function isUint32Array(value) {
		  return whichTypedArray(value) === 'Uint32Array';
		}
		exports.isUint32Array = isUint32Array;

		function isInt8Array(value) {
		  return whichTypedArray(value) === 'Int8Array';
		}
		exports.isInt8Array = isInt8Array;

		function isInt16Array(value) {
		  return whichTypedArray(value) === 'Int16Array';
		}
		exports.isInt16Array = isInt16Array;

		function isInt32Array(value) {
		  return whichTypedArray(value) === 'Int32Array';
		}
		exports.isInt32Array = isInt32Array;

		function isFloat32Array(value) {
		  return whichTypedArray(value) === 'Float32Array';
		}
		exports.isFloat32Array = isFloat32Array;

		function isFloat64Array(value) {
		  return whichTypedArray(value) === 'Float64Array';
		}
		exports.isFloat64Array = isFloat64Array;

		function isBigInt64Array(value) {
		  return whichTypedArray(value) === 'BigInt64Array';
		}
		exports.isBigInt64Array = isBigInt64Array;

		function isBigUint64Array(value) {
		  return whichTypedArray(value) === 'BigUint64Array';
		}
		exports.isBigUint64Array = isBigUint64Array;

		function isMapToString(value) {
		  return ObjectToString(value) === '[object Map]';
		}
		isMapToString.working = (
		  typeof Map !== 'undefined' &&
		  isMapToString(new Map())
		);

		function isMap(value) {
		  if (typeof Map === 'undefined') {
		    return false;
		  }

		  return isMapToString.working
		    ? isMapToString(value)
		    : value instanceof Map;
		}
		exports.isMap = isMap;

		function isSetToString(value) {
		  return ObjectToString(value) === '[object Set]';
		}
		isSetToString.working = (
		  typeof Set !== 'undefined' &&
		  isSetToString(new Set())
		);
		function isSet(value) {
		  if (typeof Set === 'undefined') {
		    return false;
		  }

		  return isSetToString.working
		    ? isSetToString(value)
		    : value instanceof Set;
		}
		exports.isSet = isSet;

		function isWeakMapToString(value) {
		  return ObjectToString(value) === '[object WeakMap]';
		}
		isWeakMapToString.working = (
		  typeof WeakMap !== 'undefined' &&
		  isWeakMapToString(new WeakMap())
		);
		function isWeakMap(value) {
		  if (typeof WeakMap === 'undefined') {
		    return false;
		  }

		  return isWeakMapToString.working
		    ? isWeakMapToString(value)
		    : value instanceof WeakMap;
		}
		exports.isWeakMap = isWeakMap;

		function isWeakSetToString(value) {
		  return ObjectToString(value) === '[object WeakSet]';
		}
		isWeakSetToString.working = (
		  typeof WeakSet !== 'undefined' &&
		  isWeakSetToString(new WeakSet())
		);
		function isWeakSet(value) {
		  return isWeakSetToString(value);
		}
		exports.isWeakSet = isWeakSet;

		function isArrayBufferToString(value) {
		  return ObjectToString(value) === '[object ArrayBuffer]';
		}
		isArrayBufferToString.working = (
		  typeof ArrayBuffer !== 'undefined' &&
		  isArrayBufferToString(new ArrayBuffer())
		);
		function isArrayBuffer(value) {
		  if (typeof ArrayBuffer === 'undefined') {
		    return false;
		  }

		  return isArrayBufferToString.working
		    ? isArrayBufferToString(value)
		    : value instanceof ArrayBuffer;
		}
		exports.isArrayBuffer = isArrayBuffer;

		function isDataViewToString(value) {
		  return ObjectToString(value) === '[object DataView]';
		}
		isDataViewToString.working = (
		  typeof ArrayBuffer !== 'undefined' &&
		  typeof DataView !== 'undefined' &&
		  isDataViewToString(new DataView(new ArrayBuffer(1), 0, 1))
		);
		function isDataView(value) {
		  if (typeof DataView === 'undefined') {
		    return false;
		  }

		  return isDataViewToString.working
		    ? isDataViewToString(value)
		    : value instanceof DataView;
		}
		exports.isDataView = isDataView;

		// Store a copy of SharedArrayBuffer in case it's deleted elsewhere
		var SharedArrayBufferCopy = typeof SharedArrayBuffer !== 'undefined' ? SharedArrayBuffer : undefined;
		function isSharedArrayBufferToString(value) {
		  return ObjectToString(value) === '[object SharedArrayBuffer]';
		}
		function isSharedArrayBuffer(value) {
		  if (typeof SharedArrayBufferCopy === 'undefined') {
		    return false;
		  }

		  if (typeof isSharedArrayBufferToString.working === 'undefined') {
		    isSharedArrayBufferToString.working = isSharedArrayBufferToString(new SharedArrayBufferCopy());
		  }

		  return isSharedArrayBufferToString.working
		    ? isSharedArrayBufferToString(value)
		    : value instanceof SharedArrayBufferCopy;
		}
		exports.isSharedArrayBuffer = isSharedArrayBuffer;

		function isAsyncFunction(value) {
		  return ObjectToString(value) === '[object AsyncFunction]';
		}
		exports.isAsyncFunction = isAsyncFunction;

		function isMapIterator(value) {
		  return ObjectToString(value) === '[object Map Iterator]';
		}
		exports.isMapIterator = isMapIterator;

		function isSetIterator(value) {
		  return ObjectToString(value) === '[object Set Iterator]';
		}
		exports.isSetIterator = isSetIterator;

		function isGeneratorObject(value) {
		  return ObjectToString(value) === '[object Generator]';
		}
		exports.isGeneratorObject = isGeneratorObject;

		function isWebAssemblyCompiledModule(value) {
		  return ObjectToString(value) === '[object WebAssembly.Module]';
		}
		exports.isWebAssemblyCompiledModule = isWebAssemblyCompiledModule;

		function isNumberObject(value) {
		  return checkBoxedPrimitive(value, numberValue);
		}
		exports.isNumberObject = isNumberObject;

		function isStringObject(value) {
		  return checkBoxedPrimitive(value, stringValue);
		}
		exports.isStringObject = isStringObject;

		function isBooleanObject(value) {
		  return checkBoxedPrimitive(value, booleanValue);
		}
		exports.isBooleanObject = isBooleanObject;

		function isBigIntObject(value) {
		  return BigIntSupported && checkBoxedPrimitive(value, bigIntValue);
		}
		exports.isBigIntObject = isBigIntObject;

		function isSymbolObject(value) {
		  return SymbolSupported && checkBoxedPrimitive(value, symbolValue);
		}
		exports.isSymbolObject = isSymbolObject;

		function isBoxedPrimitive(value) {
		  return (
		    isNumberObject(value) ||
		    isStringObject(value) ||
		    isBooleanObject(value) ||
		    isBigIntObject(value) ||
		    isSymbolObject(value)
		  );
		}
		exports.isBoxedPrimitive = isBoxedPrimitive;

		function isAnyArrayBuffer(value) {
		  return typeof Uint8Array !== 'undefined' && (
		    isArrayBuffer(value) ||
		    isSharedArrayBuffer(value)
		  );
		}
		exports.isAnyArrayBuffer = isAnyArrayBuffer;

		['isProxy', 'isExternal', 'isModuleNamespaceObject'].forEach(function(method) {
		  Object.defineProperty(exports, method, {
		    enumerable: false,
		    value: function() {
		      throw new Error(method + ' is not supported in userland');
		    }
		  });
		}); 
	} (types$1));
	return types$1;
}

var isBufferBrowser;
var hasRequiredIsBufferBrowser;

function requireIsBufferBrowser () {
	if (hasRequiredIsBufferBrowser) return isBufferBrowser;
	hasRequiredIsBufferBrowser = 1;
	isBufferBrowser = function isBuffer(arg) {
	  return arg && typeof arg === 'object'
	    && typeof arg.copy === 'function'
	    && typeof arg.fill === 'function'
	    && typeof arg.readUInt8 === 'function';
	};
	return isBufferBrowser;
}

var inherits_browser = {exports: {}};

var hasRequiredInherits_browser;

function requireInherits_browser () {
	if (hasRequiredInherits_browser) return inherits_browser.exports;
	hasRequiredInherits_browser = 1;
	if (typeof Object.create === 'function') {
	  // implementation from standard node.js 'util' module
	  inherits_browser.exports = function inherits(ctor, superCtor) {
	    if (superCtor) {
	      ctor.super_ = superCtor;
	      ctor.prototype = Object.create(superCtor.prototype, {
	        constructor: {
	          value: ctor,
	          enumerable: false,
	          writable: true,
	          configurable: true
	        }
	      });
	    }
	  };
	} else {
	  // old school shim for old browsers
	  inherits_browser.exports = function inherits(ctor, superCtor) {
	    if (superCtor) {
	      ctor.super_ = superCtor;
	      var TempCtor = function () {};
	      TempCtor.prototype = superCtor.prototype;
	      ctor.prototype = new TempCtor();
	      ctor.prototype.constructor = ctor;
	    }
	  };
	}
	return inherits_browser.exports;
}

var hasRequiredUtil$2;

function requireUtil$2 () {
	if (hasRequiredUtil$2) return util$1;
	hasRequiredUtil$2 = 1;
	(function (exports) {
		// Copyright Joyent, Inc. and other Node contributors.
		//
		// 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 getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors ||
		  function getOwnPropertyDescriptors(obj) {
		    var keys = Object.keys(obj);
		    var descriptors = {};
		    for (var i = 0; i < keys.length; i++) {
		      descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]);
		    }
		    return descriptors;
		  };

		var formatRegExp = /%[sdj%]/g;
		exports.format = function(f) {
		  if (!isString(f)) {
		    var objects = [];
		    for (var i = 0; i < arguments.length; i++) {
		      objects.push(inspect(arguments[i]));
		    }
		    return objects.join(' ');
		  }

		  var i = 1;
		  var args = arguments;
		  var len = args.length;
		  var str = String(f).replace(formatRegExp, function(x) {
		    if (x === '%%') return '%';
		    if (i >= len) return x;
		    switch (x) {
		      case '%s': return String(args[i++]);
		      case '%d': return Number(args[i++]);
		      case '%j':
		        try {
		          return JSON.stringify(args[i++]);
		        } catch (_) {
		          return '[Circular]';
		        }
		      default:
		        return x;
		    }
		  });
		  for (var x = args[i]; i < len; x = args[++i]) {
		    if (isNull(x) || !isObject(x)) {
		      str += ' ' + x;
		    } else {
		      str += ' ' + inspect(x);
		    }
		  }
		  return str;
		};


		// Mark that a method should not be used.
		// Returns a modified function which warns once by default.
		// If --no-deprecation is set, then it is a no-op.
		exports.deprecate = function(fn, msg) {
		  if (typeof api !== 'undefined' && api.noDeprecation === true) {
		    return fn;
		  }

		  // Allow for deprecating things in the process of starting up.
		  if (typeof api === 'undefined') {
		    return function() {
		      return exports.deprecate(fn, msg).apply(this, arguments);
		    };
		  }

		  var warned = false;
		  function deprecated() {
		    if (!warned) {
		      if (api.throwDeprecation) {
		        throw new Error(msg);
		      } else if (api.traceDeprecation) {
		        console.trace(msg);
		      } else {
		        console.error(msg);
		      }
		      warned = true;
		    }
		    return fn.apply(this, arguments);
		  }

		  return deprecated;
		};


		var debugs = {};
		var debugEnvRegex = /^$/;

		if (api.env.NODE_DEBUG) {
		  var debugEnv = api.env.NODE_DEBUG;
		  debugEnv = debugEnv.replace(/[|\\{}()[\]^$+?.]/g, '\\$&')
		    .replace(/\*/g, '.*')
		    .replace(/,/g, '$|^')
		    .toUpperCase();
		  debugEnvRegex = new RegExp('^' + debugEnv + '$', 'i');
		}
		exports.debuglog = function(set) {
		  set = set.toUpperCase();
		  if (!debugs[set]) {
		    if (debugEnvRegex.test(set)) {
		      var pid = api.pid;
		      debugs[set] = function() {
		        var msg = exports.format.apply(exports, arguments);
		        console.error('%s %d: %s', set, pid, msg);
		      };
		    } else {
		      debugs[set] = function() {};
		    }
		  }
		  return debugs[set];
		};


		/**
		 * Echos the value of a value. Trys to print the value out
		 * in the best way possible given the different types.
		 *
		 * @param {Object} obj The object to print out.
		 * @param {Object} opts Optional options object that alters the output.
		 */
		/* legacy: obj, showHidden, depth, colors*/
		function inspect(obj, opts) {
		  // default options
		  var ctx = {
		    seen: [],
		    stylize: stylizeNoColor
		  };
		  // legacy...
		  if (arguments.length >= 3) ctx.depth = arguments[2];
		  if (arguments.length >= 4) ctx.colors = arguments[3];
		  if (isBoolean(opts)) {
		    // legacy...
		    ctx.showHidden = opts;
		  } else if (opts) {
		    // got an "options" object
		    exports._extend(ctx, opts);
		  }
		  // set default options
		  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
		  if (isUndefined(ctx.depth)) ctx.depth = 2;
		  if (isUndefined(ctx.colors)) ctx.colors = false;
		  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
		  if (ctx.colors) ctx.stylize = stylizeWithColor;
		  return formatValue(ctx, obj, ctx.depth);
		}
		exports.inspect = inspect;


		// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
		inspect.colors = {
		  'bold' : [1, 22],
		  'italic' : [3, 23],
		  'underline' : [4, 24],
		  'inverse' : [7, 27],
		  'white' : [37, 39],
		  'grey' : [90, 39],
		  'black' : [30, 39],
		  'blue' : [34, 39],
		  'cyan' : [36, 39],
		  'green' : [32, 39],
		  'magenta' : [35, 39],
		  'red' : [31, 39],
		  'yellow' : [33, 39]
		};

		// Don't use 'blue' not visible on cmd.exe
		inspect.styles = {
		  'special': 'cyan',
		  'number': 'yellow',
		  'boolean': 'yellow',
		  'undefined': 'grey',
		  'null': 'bold',
		  'string': 'green',
		  'date': 'magenta',
		  // "name": intentionally not styling
		  'regexp': 'red'
		};


		function stylizeWithColor(str, styleType) {
		  var style = inspect.styles[styleType];

		  if (style) {
		    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
		           '\u001b[' + inspect.colors[style][1] + 'm';
		  } else {
		    return str;
		  }
		}


		function stylizeNoColor(str, styleType) {
		  return str;
		}


		function arrayToHash(array) {
		  var hash = {};

		  array.forEach(function(val, idx) {
		    hash[val] = true;
		  });

		  return hash;
		}


		function formatValue(ctx, value, recurseTimes) {
		  // Provide a hook for user-specified inspect functions.
		  // Check that value is an object with an inspect function on it
		  if (ctx.customInspect &&
		      value &&
		      isFunction(value.inspect) &&
		      // Filter out the util module, it's inspect function is special
		      value.inspect !== exports.inspect &&
		      // Also filter out any prototype objects using the circular check.
		      !(value.constructor && value.constructor.prototype === value)) {
		    var ret = value.inspect(recurseTimes, ctx);
		    if (!isString(ret)) {
		      ret = formatValue(ctx, ret, recurseTimes);
		    }
		    return ret;
		  }

		  // Primitive types cannot have properties
		  var primitive = formatPrimitive(ctx, value);
		  if (primitive) {
		    return primitive;
		  }

		  // Look up the keys of the object.
		  var keys = Object.keys(value);
		  var visibleKeys = arrayToHash(keys);

		  if (ctx.showHidden) {
		    keys = Object.getOwnPropertyNames(value);
		  }

		  // IE doesn't make error fields non-enumerable
		  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
		  if (isError(value)
		      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
		    return formatError(value);
		  }

		  // Some type of object without properties can be shortcutted.
		  if (keys.length === 0) {
		    if (isFunction(value)) {
		      var name = value.name ? ': ' + value.name : '';
		      return ctx.stylize('[Function' + name + ']', 'special');
		    }
		    if (isRegExp(value)) {
		      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
		    }
		    if (isDate(value)) {
		      return ctx.stylize(Date.prototype.toString.call(value), 'date');
		    }
		    if (isError(value)) {
		      return formatError(value);
		    }
		  }

		  var base = '', array = false, braces = ['{', '}'];

		  // Make Array say that they are Array
		  if (isArray(value)) {
		    array = true;
		    braces = ['[', ']'];
		  }

		  // Make functions say that they are functions
		  if (isFunction(value)) {
		    var n = value.name ? ': ' + value.name : '';
		    base = ' [Function' + n + ']';
		  }

		  // Make RegExps say that they are RegExps
		  if (isRegExp(value)) {
		    base = ' ' + RegExp.prototype.toString.call(value);
		  }

		  // Make dates with properties first say the date
		  if (isDate(value)) {
		    base = ' ' + Date.prototype.toUTCString.call(value);
		  }

		  // Make error with message first say the error
		  if (isError(value)) {
		    base = ' ' + formatError(value);
		  }

		  if (keys.length === 0 && (!array || value.length == 0)) {
		    return braces[0] + base + braces[1];
		  }

		  if (recurseTimes < 0) {
		    if (isRegExp(value)) {
		      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
		    } else {
		      return ctx.stylize('[Object]', 'special');
		    }
		  }

		  ctx.seen.push(value);

		  var output;
		  if (array) {
		    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
		  } else {
		    output = keys.map(function(key) {
		      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
		    });
		  }

		  ctx.seen.pop();

		  return reduceToSingleString(output, base, braces);
		}


		function formatPrimitive(ctx, value) {
		  if (isUndefined(value))
		    return ctx.stylize('undefined', 'undefined');
		  if (isString(value)) {
		    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
		                                             .replace(/'/g, "\\'")
		                                             .replace(/\\"/g, '"') + '\'';
		    return ctx.stylize(simple, 'string');
		  }
		  if (isNumber(value))
		    return ctx.stylize('' + value, 'number');
		  if (isBoolean(value))
		    return ctx.stylize('' + value, 'boolean');
		  // For some reason typeof null is "object", so special case here.
		  if (isNull(value))
		    return ctx.stylize('null', 'null');
		}


		function formatError(value) {
		  return '[' + Error.prototype.toString.call(value) + ']';
		}


		function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
		  var output = [];
		  for (var i = 0, l = value.length; i < l; ++i) {
		    if (hasOwnProperty(value, String(i))) {
		      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
		          String(i), true));
		    } else {
		      output.push('');
		    }
		  }
		  keys.forEach(function(key) {
		    if (!key.match(/^\d+$/)) {
		      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
		          key, true));
		    }
		  });
		  return output;
		}


		function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
		  var name, str, desc;
		  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
		  if (desc.get) {
		    if (desc.set) {
		      str = ctx.stylize('[Getter/Setter]', 'special');
		    } else {
		      str = ctx.stylize('[Getter]', 'special');
		    }
		  } else {
		    if (desc.set) {
		      str = ctx.stylize('[Setter]', 'special');
		    }
		  }
		  if (!hasOwnProperty(visibleKeys, key)) {
		    name = '[' + key + ']';
		  }
		  if (!str) {
		    if (ctx.seen.indexOf(desc.value) < 0) {
		      if (isNull(recurseTimes)) {
		        str = formatValue(ctx, desc.value, null);
		      } else {
		        str = formatValue(ctx, desc.value, recurseTimes - 1);
		      }
		      if (str.indexOf('\n') > -1) {
		        if (array) {
		          str = str.split('\n').map(function(line) {
		            return '  ' + line;
		          }).join('\n').slice(2);
		        } else {
		          str = '\n' + str.split('\n').map(function(line) {
		            return '   ' + line;
		          }).join('\n');
		        }
		      }
		    } else {
		      str = ctx.stylize('[Circular]', 'special');
		    }
		  }
		  if (isUndefined(name)) {
		    if (array && key.match(/^\d+$/)) {
		      return str;
		    }
		    name = JSON.stringify('' + key);
		    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
		      name = name.slice(1, -1);
		      name = ctx.stylize(name, 'name');
		    } else {
		      name = name.replace(/'/g, "\\'")
		                 .replace(/\\"/g, '"')
		                 .replace(/(^"|"$)/g, "'");
		      name = ctx.stylize(name, 'string');
		    }
		  }

		  return name + ': ' + str;
		}


		function reduceToSingleString(output, base, braces) {
		  var length = output.reduce(function(prev, cur) {
		    if (cur.indexOf('\n') >= 0) ;
		    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
		  }, 0);

		  if (length > 60) {
		    return braces[0] +
		           (base === '' ? '' : base + '\n ') +
		           ' ' +
		           output.join(',\n  ') +
		           ' ' +
		           braces[1];
		  }

		  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
		}


		// NOTE: These type checking functions intentionally don't use `instanceof`
		// because it is fragile and can be easily faked with `Object.create()`.
		exports.types = requireTypes$1();

		function isArray(ar) {
		  return Array.isArray(ar);
		}
		exports.isArray = isArray;

		function isBoolean(arg) {
		  return typeof arg === 'boolean';
		}
		exports.isBoolean = isBoolean;

		function isNull(arg) {
		  return arg === null;
		}
		exports.isNull = isNull;

		function isNullOrUndefined(arg) {
		  return arg == null;
		}
		exports.isNullOrUndefined = isNullOrUndefined;

		function isNumber(arg) {
		  return typeof arg === 'number';
		}
		exports.isNumber = isNumber;

		function isString(arg) {
		  return typeof arg === 'string';
		}
		exports.isString = isString;

		function isSymbol(arg) {
		  return typeof arg === 'symbol';
		}
		exports.isSymbol = isSymbol;

		function isUndefined(arg) {
		  return arg === undefined;
		}
		exports.isUndefined = isUndefined;

		function isRegExp(re) {
		  return isObject(re) && objectToString(re) === '[object RegExp]';
		}
		exports.isRegExp = isRegExp;
		exports.types.isRegExp = isRegExp;

		function isObject(arg) {
		  return typeof arg === 'object' && arg !== null;
		}
		exports.isObject = isObject;

		function isDate(d) {
		  return isObject(d) && objectToString(d) === '[object Date]';
		}
		exports.isDate = isDate;
		exports.types.isDate = isDate;

		function isError(e) {
		  return isObject(e) &&
		      (objectToString(e) === '[object Error]' || e instanceof Error);
		}
		exports.isError = isError;
		exports.types.isNativeError = isError;

		function isFunction(arg) {
		  return typeof arg === 'function';
		}
		exports.isFunction = isFunction;

		function isPrimitive(arg) {
		  return arg === null ||
		         typeof arg === 'boolean' ||
		         typeof arg === 'number' ||
		         typeof arg === 'string' ||
		         typeof arg === 'symbol' ||  // ES6 symbol
		         typeof arg === 'undefined';
		}
		exports.isPrimitive = isPrimitive;

		exports.isBuffer = requireIsBufferBrowser();

		function objectToString(o) {
		  return Object.prototype.toString.call(o);
		}


		function pad(n) {
		  return n < 10 ? '0' + n.toString(10) : n.toString(10);
		}


		var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
		              'Oct', 'Nov', 'Dec'];

		// 26 Feb 16:19:34
		function timestamp() {
		  var d = new Date();
		  var time = [pad(d.getHours()),
		              pad(d.getMinutes()),
		              pad(d.getSeconds())].join(':');
		  return [d.getDate(), months[d.getMonth()], time].join(' ');
		}


		// log is just a thin wrapper to console.log that prepends a timestamp
		exports.log = function() {
		  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
		};


		/**
		 * Inherit the prototype methods from one constructor into another.
		 *
		 * The Function.prototype.inherits from lang.js rewritten as a standalone
		 * function (not on Function.prototype). NOTE: If this file is to be loaded
		 * during bootstrapping this function needs to be rewritten using some native
		 * functions as prototype setup using normal JavaScript does not work as
		 * expected during bootstrapping (see mirror.js in r114903).
		 *
		 * @param {function} ctor Constructor function which needs to inherit the
		 *     prototype.
		 * @param {function} superCtor Constructor function to inherit prototype from.
		 */
		exports.inherits = requireInherits_browser();

		exports._extend = function(origin, add) {
		  // Don't do anything if add isn't an object
		  if (!add || !isObject(add)) return origin;

		  var keys = Object.keys(add);
		  var i = keys.length;
		  while (i--) {
		    origin[keys[i]] = add[keys[i]];
		  }
		  return origin;
		};

		function hasOwnProperty(obj, prop) {
		  return Object.prototype.hasOwnProperty.call(obj, prop);
		}

		var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined;

		exports.promisify = function promisify(original) {
		  if (typeof original !== 'function')
		    throw new TypeError('The "original" argument must be of type Function');

		  if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) {
		    var fn = original[kCustomPromisifiedSymbol];
		    if (typeof fn !== 'function') {
		      throw new TypeError('The "util.promisify.custom" argument must be of type Function');
		    }
		    Object.defineProperty(fn, kCustomPromisifiedSymbol, {
		      value: fn, enumerable: false, writable: false, configurable: true
		    });
		    return fn;
		  }

		  function fn() {
		    var promiseResolve, promiseReject;
		    var promise = new Promise(function (resolve, reject) {
		      promiseResolve = resolve;
		      promiseReject = reject;
		    });

		    var args = [];
		    for (var i = 0; i < arguments.length; i++) {
		      args.push(arguments[i]);
		    }
		    args.push(function (err, value) {
		      if (err) {
		        promiseReject(err);
		      } else {
		        promiseResolve(value);
		      }
		    });

		    try {
		      original.apply(this, args);
		    } catch (err) {
		      promiseReject(err);
		    }

		    return promise;
		  }

		  Object.setPrototypeOf(fn, Object.getPrototypeOf(original));

		  if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, {
		    value: fn, enumerable: false, writable: false, configurable: true
		  });
		  return Object.defineProperties(
		    fn,
		    getOwnPropertyDescriptors(original)
		  );
		};

		exports.promisify.custom = kCustomPromisifiedSymbol;

		function callbackifyOnRejected(reason, cb) {
		  // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M).
		  // Because `null` is a special error value in callbacks which means "no error
		  // occurred", we error-wrap so the callback consumer can distinguish between
		  // "the promise rejected with null" or "the promise fulfilled with undefined".
		  if (!reason) {
		    var newReason = new Error('Promise was rejected with a falsy value');
		    newReason.reason = reason;
		    reason = newReason;
		  }
		  return cb(reason);
		}

		function callbackify(original) {
		  if (typeof original !== 'function') {
		    throw new TypeError('The "original" argument must be of type Function');
		  }

		  // We DO NOT return the promise as it gives the user a false sense that
		  // the promise is actually somehow related to the callback's execution
		  // and that the callback throwing will reject the promise.
		  function callbackified() {
		    var args = [];
		    for (var i = 0; i < arguments.length; i++) {
		      args.push(arguments[i]);
		    }

		    var maybeCb = args.pop();
		    if (typeof maybeCb !== 'function') {
		      throw new TypeError('The last argument must be of type Function');
		    }
		    var self = this;
		    var cb = function() {
		      return maybeCb.apply(self, arguments);
		    };
		    // In true node style we process the callback on `nextTick` with all the
		    // implications (stack, `uncaughtException`, `async_hooks`)
		    original.apply(this, args)
		      .then(function(ret) { api.nextTick(cb.bind(null, null, ret)); },
		            function(rej) { api.nextTick(callbackifyOnRejected.bind(null, rej, cb)); });
		  }

		  Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original));
		  Object.defineProperties(callbackified,
		                          getOwnPropertyDescriptors(original));
		  return callbackified;
		}
		exports.callbackify = callbackify; 
	} (util$1));
	return util$1;
}

var hasRequiredUtil$1;

function requireUtil$1 () {
	if (hasRequiredUtil$1) return util$2;
	hasRequiredUtil$1 = 1;

	const util = requireUtil$2();

	util$2.format = util.format;
	util$2.inherits = util.inherits;
	const parse = (u) => new URL(u);

	/**
	 * Regular Expression that matches Swagger path params.
	 */
	util$2.swaggerParamRegExp = /\{([^/}]+)}/g;

	/**
	 * List of HTTP verbs used for OperationItem as per the Swagger specification
	 */
	const operationsList = ["get", "post", "put", "delete", "patch", "options", "head", "trace"];

	/**
	 * This function takes in a Server object, checks if it has relative path
	 * and then fixes it as per the path url
	 *
	 * @param {object} server - The server object to be fixed
	 * @param {string} path - The path (an http/https url) from where the file was downloaded
	 * @returns {object} - The fixed server object
	 */
	function fixServers (server, path) {
	  // Server url starting with "/" tells that it is not an http(s) url
	  if (server.url && server.url.startsWith("/")) {
	    const inUrl = parse(path);
	    const finalUrl = inUrl.protocol + "//" + inUrl.hostname + server.url;
	    server.url = finalUrl;
	    return server;
	  }
	}

	/**
	 * This function helps fix the relative servers in the API definition file
	 * be at root, path or operation's level
	 */
	function fixOasRelativeServers (schema, filePath) {
	  if (schema.openapi && (filePath && (filePath.startsWith("http:") || filePath.startsWith("https:")))) {
	    /**
	     * From OpenAPI v3 spec for Server object's url property: "REQUIRED. A URL to the target host.
	     * This URL supports Server Variables and MAY be relative, to indicate that the host location is relative to the location where
	     * the OpenAPI document is being served."
	     * Further, the spec says that "servers" property can show up at root level, in 'Path Item' object or in 'Operation' object.
	     * However, interpretation of the spec says that relative paths for servers should take into account the hostname that
	     * serves the OpenAPI file.
	     */
	    if (schema.servers) {
	      schema.servers.map(server => fixServers(server, filePath)); // Root level servers array's fixup
	    }

	    // Path, Operation, or Webhook level servers array's fixup
	    ["paths", "webhooks"].forEach(component => {
	      Object.keys(schema[component] || []).forEach(path => {
	        const pathItem = schema[component][path];
	        Object.keys(pathItem).forEach(opItem => {
	          if (opItem === "servers") {
	            // servers at pathitem level
	            pathItem[opItem].map(server => fixServers(server, filePath));
	          }
	          else if (operationsList.includes(opItem)) {
	            // servers at operation level
	            if (pathItem[opItem].servers) {
	              pathItem[opItem].servers.map(server => fixServers(server, filePath));
	            }
	          }
	        });
	      });
	    });
	  }
	}

	util$2.fixOasRelativeServers = fixOasRelativeServers;
	return util$2;
}

/**
 * Ono supports custom formatters for error messages.  In Node.js, it defaults
 * to the `util.format()` function.  In browsers, it defaults to `Array.join()`.
 *
 * The Node.js functionality can be used in a web browser via a polyfill,
 * such as "format-util".
 *
 * @see https://github.com/tmpfs/format-util
 */
const format$2 = false;

const newline = /\r?\n/;
const onoCall = /\bono[ @]/;
/**
 * Is the property lazily computed?
 */
function isLazyStack(stackProp) {
    return Boolean(stackProp &&
        stackProp.configurable &&
        typeof stackProp.get === "function");
}
/**
 * Is the stack property writable?
 */
function isWritableStack(stackProp) {
    return Boolean(
    // If there is no stack property, then it's writable, since assigning it will create it
    !stackProp ||
        stackProp.writable ||
        typeof stackProp.set === "function");
}
/**
 * Appends the original `Error.stack` property to the new Error's stack.
 */
function joinStacks(newError, originalError) {
    let newStack = popStack(newError.stack);
    let originalStack = originalError ? originalError.stack : undefined;
    if (newStack && originalStack) {
        return newStack + "\n\n" + originalStack;
    }
    else {
        return newStack || originalStack;
    }
}
/**
 * Calls `joinStacks` lazily, when the `Error.stack` property is accessed.
 */
function lazyJoinStacks(lazyStack, newError, originalError) {
    if (originalError) {
        Object.defineProperty(newError, "stack", {
            get: () => {
                let newStack = lazyStack.get.apply(newError);
                return joinStacks({ stack: newStack }, originalError);
            },
            enumerable: false,
            configurable: true
        });
    }
    else {
        lazyPopStack(newError, lazyStack);
    }
}
/**
 * Removes Ono from the stack, so that the stack starts at the original error location
 */
function popStack(stack) {
    if (stack) {
        let lines = stack.split(newline);
        // Find the Ono call(s) in the stack, and remove them
        let onoStart;
        for (let i = 0; i < lines.length; i++) {
            let line = lines[i];
            if (onoCall.test(line)) {
                if (onoStart === undefined) {
                    // We found the first Ono call in the stack trace.
                    // There may be other subsequent Ono calls as well.
                    onoStart = i;
                }
            }
            else if (onoStart !== undefined) {
                // We found the first non-Ono call after one or more Ono calls.
                // So remove the Ono call lines from the stack trace
                lines.splice(onoStart, i - onoStart);
                break;
            }
        }
        if (lines.length > 0) {
            return lines.join("\n");
        }
    }
    // If we get here, then the stack doesn't contain a call to `ono`.
    // This may be due to minification or some optimization of the JS engine.
    // So just return the stack as-is.
    return stack;
}
/**
 * Calls `popStack` lazily, when the `Error.stack` property is accessed.
 */
function lazyPopStack(error, lazyStack) {
    Object.defineProperty(error, "stack", {
        get: () => popStack(lazyStack.get.apply(error)),
        enumerable: false,
        configurable: true
    });
}

const nonJsonTypes = ["function", "symbol", "undefined"];
const protectedProps$1 = ["constructor", "prototype", "__proto__"];
const objectPrototype = Object.getPrototypeOf({});
/**
 * Custom JSON serializer for Error objects.
 * Returns all built-in error properties, as well as extended properties.
 */
function toJSON() {
    // HACK: We have to cast the objects to `any` so we can use symbol indexers.
    // see https://github.com/Microsoft/TypeScript/issues/1863
    let pojo = {};
    let error = this;
    for (let key of getDeepKeys(error)) {
        if (typeof key === "string") {
            let value = error[key];
            let type = typeof value;
            if (!nonJsonTypes.includes(type)) {
                pojo[key] = value;
            }
        }
    }
    return pojo;
}
/**
 * Returns own, inherited, enumerable, non-enumerable, string, and symbol keys of `obj`.
 * Does NOT return members of the base Object prototype, or the specified omitted keys.
 */
function getDeepKeys(obj, omit = []) {
    let keys = [];
    // Crawl the prototype chain, finding all the string and symbol keys
    while (obj && obj !== objectPrototype) {
        keys = keys.concat(Object.getOwnPropertyNames(obj), Object.getOwnPropertySymbols(obj));
        obj = Object.getPrototypeOf(obj);
    }
    // De-duplicate the list of keys
    let uniqueKeys = new Set(keys);
    // Remove any omitted keys
    for (let key of omit.concat(protectedProps$1)) {
        uniqueKeys.delete(key);
    }
    return uniqueKeys;
}

const protectedProps = ["name", "message", "stack"];
/**
 * Extends the new error with the properties of the original error and the `props` object.
 *
 * @param newError - The error object to extend
 * @param originalError - The original error object, if any
 * @param props - Additional properties to add, if any
 */
function extendError(error, originalError, props) {
    let onoError = error;
    extendStack(onoError, originalError);
    // Copy properties from the original error
    if (originalError && typeof originalError === "object") {
        mergeErrors(onoError, originalError);
    }
    // The default `toJSON` method doesn't output props like `name`, `message`, `stack`, etc.
    // So replace it with one that outputs every property of the error.
    onoError.toJSON = toJSON;
    // Finally, copy custom properties that were specified by the user.
    // These props OVERWRITE any previous props
    if (props && typeof props === "object") {
        Object.assign(onoError, props);
    }
    return onoError;
}
/**
 * Extend the error stack to include its cause
 */
function extendStack(newError, originalError) {
    let stackProp = Object.getOwnPropertyDescriptor(newError, "stack");
    if (isLazyStack(stackProp)) {
        lazyJoinStacks(stackProp, newError, originalError);
    }
    else if (isWritableStack(stackProp)) {
        newError.stack = joinStacks(newError, originalError);
    }
}
/**
 * Merges properties of the original error with the new error.
 *
 * @param newError - The error object to extend
 * @param originalError - The original error object, if any
 */
function mergeErrors(newError, originalError) {
    // Get the original error's keys
    // NOTE: We specifically exclude properties that we have already set on the new error.
    // This is _especially_ important for the `stack` property, because this property has
    // a lazy getter in some environments
    let keys = getDeepKeys(originalError, protectedProps);
    // HACK: We have to cast the errors to `any` so we can use symbol indexers.
    // see https://github.com/Microsoft/TypeScript/issues/1863
    let _newError = newError;
    let _originalError = originalError;
    for (let key of keys) {
        if (_newError[key] === undefined) {
            try {
                _newError[key] = _originalError[key];
            }
            catch (e) {
                // This property is read-only, so it can't be copied
            }
        }
    }
}

/**
 * Normalizes Ono options, accounting for defaults and optional options.
 */
function normalizeOptions(options) {
    options = options || {};
    return {
        concatMessages: options.concatMessages === undefined ? true : Boolean(options.concatMessages),
        format: options.format === undefined ? format$2
            : (typeof options.format === "function" ? options.format : false),
    };
}
/**
 * Normalizes the Ono arguments, accounting for defaults, options, and optional arguments.
 */
function normalizeArgs$1(args, options) {
    let originalError;
    let props;
    let formatArgs;
    let message = "";
    // Determine which arguments were actually specified
    if (typeof args[0] === "string") {
        formatArgs = args;
    }
    else if (typeof args[1] === "string") {
        if (args[0] instanceof Error) {
            originalError = args[0];
        }
        else {
            props = args[0];
        }
        formatArgs = args.slice(1);
    }
    else {
        originalError = args[0];
        props = args[1];
        formatArgs = args.slice(2);
    }
    // If there are any format arguments, then format the error message
    if (formatArgs.length > 0) {
        if (options.format) {
            message = options.format.apply(undefined, formatArgs);
        }
        else {
            message = formatArgs.join(" ");
        }
    }
    if (options.concatMessages && originalError && originalError.message) {
        // The inner-error's message will be added to the new message
        message += (message ? " \n" : "") + originalError.message;
    }
    return { originalError, props, message };
}

const constructor = Ono;
/**
 * Creates an `Ono` instance for a specifc error type.
 */
// eslint-disable-next-line @typescript-eslint/naming-convention
function Ono(ErrorConstructor, options) {
    options = normalizeOptions(options);
    function ono(...args) {
        let { originalError, props, message } = normalizeArgs$1(args, options);
        // Create a new error of the specified type
        let newError = new ErrorConstructor(message);
        // Extend the error with the properties of the original error and the `props` object
        return extendError(newError, originalError, props);
    }
    ono[Symbol.species] = ErrorConstructor;
    return ono;
}
/**
 * Returns an object containing all properties of the given Error object,
 * which can be used with `JSON.stringify()`.
 */
Ono.toJSON = function toJSON$1(error) {
    return toJSON.call(error);
};
/**
 * Extends the given Error object with enhanced Ono functionality, such as nested stack traces,
 * additional properties, and improved support for `JSON.stringify()`.
 */
Ono.extend = function extend(error, originalError, props) {
    if (props || originalError instanceof Error) {
        return extendError(error, originalError, props);
    }
    else if (originalError) {
        return extendError(error, undefined, originalError);
    }
    else {
        return extendError(error);
    }
};

const singleton = ono;
ono.error = new constructor(Error);
ono.eval = new constructor(EvalError);
ono.range = new constructor(RangeError);
ono.reference = new constructor(ReferenceError);
ono.syntax = new constructor(SyntaxError);
ono.type = new constructor(TypeError);
ono.uri = new constructor(URIError);
const onoMap = ono;
/**
 * Creates a new error with the specified message, properties, and/or inner error.
 * If an inner error is provided, then the new error will match its type, if possible.
 */
function ono(...args) {
    let originalError = args[0];
    // Is the first argument an Error-like object?
    if (typeof originalError === "object" && typeof originalError.name === "string") {
        // Try to find an Ono singleton method that matches this error type
        for (let typedOno of Object.values(onoMap)) {
            if (typeof typedOno === "function" && typedOno.name === "ono") {
                let species = typedOno[Symbol.species];
                if (species && species !== Error && (originalError instanceof species || originalError.name === species.name)) {
                    // Create an error of the same type
                    return typedOno.apply(undefined, args);
                }
            }
        }
    }
    // By default, create a base Error object
    return ono.error.apply(undefined, args);
}

requireUtil$2();

/* eslint-env commonjs */
// CommonJS default export hack
if (typeof module === "object" && typeof module.exports === "object") {
    module.exports = Object.assign(module.exports.default, module.exports);
}

var esm = /*#__PURE__*/Object.freeze({
	__proto__: null,
	Ono: constructor,
	default: singleton,
	ono: singleton
});

var require$$6$1 = /*@__PURE__*/getAugmentedNamespace(esm);

var dist = {exports: {}};

var core$3 = {};

var validate = {};

var boolSchema = {};

var errors$1 = {};

var codegen = {};

var code$1 = {};

var hasRequiredCode$1;

function requireCode$1 () {
	if (hasRequiredCode$1) return code$1;
	hasRequiredCode$1 = 1;
	(function (exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = undefined;
		// eslint-disable-next-line @typescript-eslint/no-extraneous-class
		class _CodeOrName {
		}
		exports._CodeOrName = _CodeOrName;
		exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
		class Name extends _CodeOrName {
		    constructor(s) {
		        super();
		        if (!exports.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.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 !== undefined ? _a : (this._str = this._items.reduce((s, c) => `${s}${c}`, "")));
		    }
		    get names() {
		        var _a;
		        return ((_a = this._names) !== null && _a !== undefined ? _a : (this._names = this._items.reduce((names, c) => {
		            if (c instanceof Name)
		                names[c.str] = (names[c.str] || 0) + 1;
		            return names;
		        }, {})));
		    }
		}
		exports._Code = _Code;
		exports.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._ = _;
		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.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.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.strConcat = strConcat;
		// TODO do not allow arrays here
		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.stringify = stringify;
		function safeStringify(x) {
		    return JSON.stringify(x)
		        .replace(/\u2028/g, "\\u2028")
		        .replace(/\u2029/g, "\\u2029");
		}
		exports.safeStringify = safeStringify;
		function getProperty(key) {
		    return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _ `[${key}]`;
		}
		exports.getProperty = getProperty;
		//Does best effort to format the name properly
		function getEsmExportName(key) {
		    if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
		        return new _Code(`${key}`);
		    }
		    throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
		}
		exports.getEsmExportName = getEsmExportName;
		function regexpCode(rx) {
		    return new _Code(rx.toString());
		}
		exports.regexpCode = regexpCode;
		
	} (code$1));
	return code$1;
}

var scope = {};

var hasRequiredScope;

function requireScope () {
	if (hasRequiredScope) return scope;
	hasRequiredScope = 1;
	(function (exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = undefined;
		const code_1 = requireCode$1();
		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.UsedValueState = UsedValueState = {}));
		exports.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 === undefined ? undefined : _a._prefixes) === null || _b === undefined ? undefined : _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.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.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 !== undefined ? _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.varKinds.var : exports.varKinds.const;
		                    code = (0, code_1._) `${code}${def} ${name} = ${c};${this.opts._n}`;
		                }
		                else if ((c = getCode === null || getCode === undefined ? undefined : getCode(name))) {
		                    code = (0, code_1._) `${code}${c}${this.opts._n}`;
		                }
		                else {
		                    throw new ValueError(name);
		                }
		                nameSet.set(name, UsedValueState.Completed);
		            });
		        }
		        return code;
		    }
		}
		exports.ValueScope = ValueScope;
		
	} (scope));
	return scope;
}

var hasRequiredCodegen;

function requireCodegen () {
	if (hasRequiredCodegen) return codegen;
	hasRequiredCodegen = 1;
	(function (exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = undefined;
		const code_1 = requireCode$1();
		const scope_1 = requireScope();
		var code_2 = requireCode$1();
		Object.defineProperty(exports, "_", { enumerable: true, get: function () { return code_2._; } });
		Object.defineProperty(exports, "str", { enumerable: true, get: function () { return code_2.str; } });
		Object.defineProperty(exports, "strConcat", { enumerable: true, get: function () { return code_2.strConcat; } });
		Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return code_2.nil; } });
		Object.defineProperty(exports, "getProperty", { enumerable: true, get: function () { return code_2.getProperty; } });
		Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return code_2.stringify; } });
		Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function () { return code_2.regexpCode; } });
		Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return code_2.Name; } });
		var scope_2 = requireScope();
		Object.defineProperty(exports, "Scope", { enumerable: true, get: function () { return scope_2.Scope; } });
		Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function () { return scope_2.ValueScope; } });
		Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function () { return scope_2.ValueScopeName; } });
		Object.defineProperty(exports, "varKinds", { enumerable: true, get: function () { return scope_2.varKinds; } });
		exports.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--) {
		            // iterating backwards improves 1-pass optimization
		            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; // else is ignored here
		        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 === undefined ? undefined : _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 === undefined ? undefined : _a.optimizeNodes();
		        (_b = this.finally) === null || _b === undefined ? undefined : _b.optimizeNodes();
		        return this;
		    }
		    optimizeNames(names, constants) {
		        var _a, _b;
		        super.optimizeNames(names, constants);
		        (_a = this.catch) === null || _a === undefined ? undefined : _a.optimizeNames(names, constants);
		        (_b = this.finally) === null || _b === undefined ? undefined : _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);
		    }
		    // returns unique name in the internal scope
		    name(prefix) {
		        return this._scope.name(prefix);
		    }
		    // reserves unique name in the external scope
		    scopeName(prefix) {
		        return this._extScope.name(prefix);
		    }
		    // reserves unique name in the external scope and assigns value to it
		    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);
		    }
		    // return code that assigns values in the external scope to the names that are used internally
		    // (same names that were returned by gen.scopeName or gen.scopeValue)
		    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` declaration (`var` in es5 mode)
		    const(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
		    }
		    // `let` declaration with optional assignment (`var` in es5 mode)
		    let(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
		    }
		    // `var` declaration with optional assignment
		    var(nameOrPrefix, rhs, _constant) {
		        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
		    }
		    // assignment code
		    assign(lhs, rhs, sideEffects) {
		        return this._leafNode(new Assign(lhs, rhs, sideEffects));
		    }
		    // `+=` code
		    add(lhs, rhs) {
		        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
		    }
		    // appends passed SafeExpr to code or executes Block
		    code(c) {
		        if (typeof c == "function")
		            c();
		        else if (c !== code_1.nil)
		            this._leafNode(new AnyCode(c));
		        return this;
		    }
		    // returns code for object literal for the passed argument list of key-value pairs
		    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` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
		    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;
		    }
		    // `else if` clause - invalid without `if` or after `else` clauses
		    elseIf(condition) {
		        return this._elseNode(new If(condition));
		    }
		    // `else` clause - only valid after `if` or `else if` clauses
		    else() {
		        return this._elseNode(new Else());
		    }
		    // end `if` statement (needed if gen.if was used only with condition)
		    endIf() {
		        return this._endBlockNode(If, Else);
		    }
		    _for(node, forBody) {
		        this._blockNode(node);
		        if (forBody)
		            this.code(forBody).endFor();
		        return this;
		    }
		    // a generic `for` clause (or statement if `forBody` is passed)
		    for(iteration, forBody) {
		        return this._for(new ForLoop(iteration), forBody);
		    }
		    // `for` statement for a range of values
		    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));
		    }
		    // `for-of` statement (in es5 mode replace with a normal for loop)
		    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));
		    }
		    // `for-in` statement.
		    // With option `ownProperties` replaced with a `for-of` loop for object keys
		    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));
		    }
		    // end `for` loop
		    endFor() {
		        return this._endBlockNode(For);
		    }
		    // `label` statement
		    label(label) {
		        return this._leafNode(new Label(label));
		    }
		    // `break` statement
		    break(label) {
		        return this._leafNode(new Break(label));
		    }
		    // `return` statement
		    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` statement
		    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` statement
		    throw(error) {
		        return this._leafNode(new Throw(error));
		    }
		    // start self-balancing block
		    block(body, nodeCount) {
		        this._blockStarts.push(this._nodes.length);
		        if (body)
		            this.code(body).endBlock(nodeCount);
		        return this;
		    }
		    // end the current self-balancing block
		    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;
		    }
		    // `function` heading (or definition if funcBody is passed)
		    func(name, args = code_1.nil, async, funcBody) {
		        this._blockNode(new Func(name, args, async));
		        if (funcBody)
		            this.code(funcBody).endFunc();
		        return this;
		    }
		    // end function definition
		    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.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.not = not;
		const andCode = mappend(exports.operators.AND);
		// boolean AND (&&) expression with the passed arguments
		function and(...args) {
		    return args.reduce(andCode);
		}
		exports.and = and;
		const orCode = mappend(exports.operators.OR);
		// boolean OR (||) expression with the passed arguments
		function or(...args) {
		    return args.reduce(orCode);
		}
		exports.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 = {};

var hasRequiredUtil;

function requireUtil () {
	if (hasRequiredUtil) return util;
	hasRequiredUtil = 1;
	Object.defineProperty(util, "__esModule", { value: true });
	util.checkStrictMode = util.getErrorPath = util.Type = util.useFunc = util.setEvaluated = util.evaluatedPropsToName = util.mergeEvaluated = util.eachItem = util.unescapeJsonPointer = util.escapeJsonPointer = util.escapeFragment = util.unescapeFragment = util.schemaRefOrVal = util.schemaHasRulesButRef = util.schemaHasRules = util.checkUnknownRules = util.alwaysValidSchema = util.toHash = undefined;
	const codegen_1 = requireCodegen();
	const code_1 = requireCode$1();
	// TODO refactor to use Set
	function toHash(arr) {
	    const hash = {};
	    for (const item of arr)
	        hash[item] = true;
	    return hash;
	}
	util.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.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.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.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.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.schemaRefOrVal = schemaRefOrVal;
	function unescapeFragment(str) {
	    return unescapeJsonPointer(decodeURIComponent(str));
	}
	util.unescapeFragment = unescapeFragment;
	function escapeFragment(str) {
	    return encodeURIComponent(escapeJsonPointer(str));
	}
	util.escapeFragment = escapeFragment;
	function escapeJsonPointer(str) {
	    if (typeof str == "number")
	        return `${str}`;
	    return str.replace(/~/g, "~0").replace(/\//g, "~1");
	}
	util.escapeJsonPointer = escapeJsonPointer;
	function unescapeJsonPointer(str) {
	    return str.replace(/~1/g, "/").replace(/~0/g, "~");
	}
	util.unescapeJsonPointer = unescapeJsonPointer;
	function eachItem(xs, f) {
	    if (Array.isArray(xs)) {
	        for (const x of xs)
	            f(x);
	    }
	    else {
	        f(xs);
	    }
	}
	util.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.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.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.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.useFunc = useFunc;
	var Type;
	(function (Type) {
	    Type[Type["Num"] = 0] = "Num";
	    Type[Type["Str"] = 1] = "Str";
	})(Type || (util.Type = Type = {}));
	function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
	    // let path
	    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")`; // TODO maybe use global escapePointer
	    }
	    return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
	}
	util.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.checkStrictMode = checkStrictMode;
	
	return util;
}

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 = {
	    // validation function arguments
	    data: new codegen_1.Name("data"), // data passed to validation function
	    // args passed from referencing schema
	    valCxt: new codegen_1.Name("valCxt"), // validation/data context - should not be used directly, it is destructured to the names below
	    instancePath: new codegen_1.Name("instancePath"),
	    parentData: new codegen_1.Name("parentData"),
	    parentDataProperty: new codegen_1.Name("parentDataProperty"),
	    rootData: new codegen_1.Name("rootData"), // root data - same as the data passed to the first/top validation function
	    dynamicAnchors: new codegen_1.Name("dynamicAnchors"), // used to support recursiveRef and dynamicRef
	    // function scoped variables
	    vErrors: new codegen_1.Name("vErrors"), // null or array of validation errors
	    errors: new codegen_1.Name("errors"), // counter of validation errors
	    this: new codegen_1.Name("this"),
	    // "globals"
	    self: new codegen_1.Name("self"),
	    scope: new codegen_1.Name("scope"),
	    // JTD serialize/parse name for JSON string and position
	    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) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = undefined;
		const codegen_1 = requireCodegen();
		const util_1 = requireUtil();
		const names_1 = requireNames();
		exports.keywordError = {
		    message: ({ keyword }) => (0, codegen_1.str) `must pass "${keyword}" keyword validation`,
		};
		exports.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.keywordError, errorPaths, overrideAllErrors) {
		    const { it } = cxt;
		    const { gen, compositeRule, allErrors } = it;
		    const errObj = errorObjectCode(cxt, error, errorPaths);
		    if (overrideAllErrors !== null && overrideAllErrors !== undefined ? overrideAllErrors : (compositeRule || allErrors)) {
		        addError(gen, errObj);
		    }
		    else {
		        returnErrors(it, (0, codegen_1._) `[${errObj}]`);
		    }
		}
		exports.reportError = reportError;
		function reportExtraError(cxt, error = exports.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.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.resetErrorsCount = resetErrorsCount;
		function extendErrors({ gen, keyword, schemaValue, data, errsCount, it, }) {
		    /* istanbul ignore if */
		    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.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"), // also used in JTD errors
		    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 = undefined;
	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); // TODO var
	        falseSchemaError(it);
	    }
	    else {
	        gen.var(valid, true); // TODO var
	    }
	}
	boolSchema.boolOrEmptySchema = boolOrEmptySchema;
	function falseSchemaError(it, overrideAllErrors) {
	    const { gen, data } = it;
	    // TODO maybe some other interface should be used for non-keyword validation errors...
	    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 = undefined;
	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 = undefined;
	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 === undefined ? undefined : _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 = undefined;
	const rules_1 = requireRules();
	const applicability_1 = requireApplicability();
	const errors_1 = requireErrors$1();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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;
	// eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
	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) {
	    // TODO use gen.property
	    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 = {};

var hasRequiredDefaults;

function requireDefaults () {
	if (hasRequiredDefaults) return defaults;
	hasRequiredDefaults = 1;
	Object.defineProperty(defaults, "__esModule", { value: true });
	defaults.assignDefaults = undefined;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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.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} === ""`;
	    }
	    // `${childData} === undefined` +
	    // (opts.useDefaults === "empty" ? ` || ${childData} === null || ${childData} === ""` : "")
	    gen.if(condition, (0, codegen_1._) `${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
	}
	
	return defaults;
}

var keyword = {};

var code = {};

var hasRequiredCode;

function requireCode () {
	if (hasRequiredCode) return code;
	hasRequiredCode = 1;
	Object.defineProperty(code, "__esModule", { value: true });
	code.validateUnion = code.validateArray = code.usePattern = code.callValidateCode = code.schemaProperties = code.allSchemaProperties = code.noPropertyInData = code.propertyInData = code.isOwnProperty = code.hasPropFunc = code.reportMissingProp = code.checkMissingProp = code.checkReportMissingProp = undefined;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	const names_1 = requireNames();
	const util_2 = requireUtil();
	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.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.checkMissingProp = checkMissingProp;
	function reportMissingProp(cxt, missing) {
	    cxt.setParams({ missingProperty: missing }, true);
	    cxt.error();
	}
	code.reportMissingProp = reportMissingProp;
	function hasPropFunc(gen) {
	    return gen.scopeValue("func", {
	        // eslint-disable-next-line @typescript-eslint/unbound-method
	        ref: Object.prototype.hasOwnProperty,
	        code: (0, codegen_1._) `Object.prototype.hasOwnProperty`,
	    });
	}
	code.hasPropFunc = hasPropFunc;
	function isOwnProperty(gen, data, property) {
	    return (0, codegen_1._) `${hasPropFunc(gen)}.call(${data}, ${property})`;
	}
	code.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.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.noPropertyInData = noPropertyInData;
	function allSchemaProperties(schemaMap) {
	    return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
	}
	code.allSchemaProperties = allSchemaProperties;
	function schemaProperties(it, schemaMap) {
	    return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
	}
	code.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.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.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.validateArray = validateArray;
	function validateUnion(cxt) {
	    const { gen, schema, keyword, it } = cxt;
	    /* istanbul ignore if */
	    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);
	        // can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
	        // or if all properties and items were evaluated (it.props === true && it.items === true)
	        if (!merged)
	            gen.if((0, codegen_1.not)(valid));
	    }));
	    cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
	}
	code.validateUnion = validateUnion;
	
	return code;
}

var hasRequiredKeyword;

function requireKeyword () {
	if (hasRequiredKeyword) return keyword;
	hasRequiredKeyword = 1;
	Object.defineProperty(keyword, "__esModule", { value: true });
	keyword.validateKeywordUsage = keyword.validSchemaType = keyword.funcKeywordCode = keyword.macroKeywordCode = undefined;
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const code_1 = requireCode();
	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.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 !== undefined ? _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 !== undefined ? _a : valid), errors);
	    }
	}
	keyword.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) {
	    // TODO add tests
	    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.validSchemaType = validSchemaType;
	function validateKeywordUsage({ schema, opts, self, errSchemaPath }, def, keyword) {
	    /* istanbul ignore if */
	    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 === undefined ? undefined : 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.validateKeywordUsage = validateKeywordUsage;
	
	return keyword;
}

var subschema = {};

var hasRequiredSubschema;

function requireSubschema () {
	if (hasRequiredSubschema) return subschema;
	hasRequiredSubschema = 1;
	Object.defineProperty(subschema, "__esModule", { value: true });
	subschema.extendSubschemaMode = subschema.extendSubschemaData = subschema.getSubschema = undefined;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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); // replaceable if used once?
	        dataContextProps(nextData);
	        if (propertyName !== undefined)
	            subschema.propertyName = propertyName;
	        // TODO something is possibly wrong here with not changing parentDataProperty and not appending dataPathArr
	    }
	    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; // not inherited
	    subschema.jtdMetadata = jtdMetadata; // not inherited
	}
	subschema.extendSubschemaMode = extendSubschemaMode;
	
	return subschema;
}

var resolve = {};

var fastDeepEqual;
var hasRequiredFastDeepEqual;

function requireFastDeepEqual () {
	if (hasRequiredFastDeepEqual) return fastDeepEqual;
	hasRequiredFastDeepEqual = 1;

	// do not edit .js files directly - edit src/index.jst



	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;
	  }

	  // true if both NaN, false otherwise
	  return a!==a && b!==b;
	};
	return fastDeepEqual;
}

var jsonSchemaTraverse = {exports: {}};

var hasRequiredJsonSchemaTraverse;

function requireJsonSchemaTraverse () {
	if (hasRequiredJsonSchemaTraverse) return jsonSchemaTraverse.exports;
	hasRequiredJsonSchemaTraverse = 1;

	var traverse = jsonSchemaTraverse.exports = function (schema, opts, cb) {
	  // Legacy support for v0.3.1 and earlier.
	  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 = undefined;
	const util_1 = requireUtil();
	const equal = requireFastDeepEqual();
	const traverse = requireJsonSchemaTraverse();
	// TODO refactor to use keyword definitions
	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) {
	            // eslint-disable-next-line @typescript-eslint/unbound-method
	            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 = undefined;
	const boolSchema_1 = requireBoolSchema();
	const dataType_1 = requireDataType();
	const applicability_1 = requireApplicability();
	const dataType_2 = requireDataType();
	const defaults_1 = requireDefaults();
	const keyword_1 = requireKeyword();
	const subschema_1 = requireSubschema();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const resolve_1 = requireResolve();
	const util_1 = requireUtil();
	const errors_1 = requireErrors$1();
	// schema compilation - generates validation function, subschemaCode (below) is used for subschemas
	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) {
	    // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
	    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;
	}
	// schema compilation - this function is used recursively to generate code for sub-schemas
	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);
	    // TODO var
	    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) {
	        // TODO assign unevaluated
	        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)); // TODO typecast
	        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);
	        }
	        // TODO make it "ok" call?
	        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); // this branch will be removed by gen.optimize
	            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) {
	                /* istanbul ignore if */
	                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 }); // TODO value.code for standalone
	                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 = {};

var hasRequiredCompile;

function requireCompile () {
	if (hasRequiredCompile) return compile;
	hasRequiredCompile = 1;
	Object.defineProperty(compile, "__esModule", { value: true });
	compile.resolveSchema = compile.getCompilingSchema = compile.resolveRef = compile.compileSchema = compile.SchemaEnv = undefined;
	const codegen_1 = requireCodegen();
	const validation_error_1 = requireValidation_error();
	const names_1 = requireNames();
	const resolve_1 = requireResolve();
	const util_1 = requireUtil();
	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 !== undefined ? _a : (0, resolve_1.normalizeId)(schema === null || schema === undefined ? undefined : schema[env.schemaId || "$id"]);
	        this.schemaPath = env.schemaPath;
	        this.localRefs = env.localRefs;
	        this.meta = env.meta;
	        this.$async = schema === null || schema === undefined ? undefined : schema.$async;
	        this.refs = {};
	    }
	}
	compile.SchemaEnv = SchemaEnv;
	// let codeSize = 0
	// let nodeCount = 0
	// Compiles schema in SchemaEnv
	function compileSchema(sch) {
	    // TODO refactor - remove compilations
	    const _sch = getCompilingSchema.call(this, sch);
	    if (_sch)
	        return _sch;
	    const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId); // TODO if getFullPath removed 1 tests fails
	    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], // TODO can its length be used as dataLevel if nil is removed?
	        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);
	        // gen.optimize(1)
	        const validateCode = gen.toString();
	        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
	        // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
	        if (this.opts.code.process)
	            sourceCode = this.opts.code.process(sourceCode, sch);
	        // console.log("\n\n\n *** \n", sourceCode)
	        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);
	        // console.log("\n\n\n *** \n", sourceCode, this.opts)
	        throw e;
	    }
	    finally {
	        this._compilations.delete(sch);
	    }
	}
	compile.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 === undefined ? undefined : _a[ref]; // TODO maybe localRefs should hold SchemaEnv
	        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.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);
	}
	// Index of schema compilation in the currently compiled list
	function getCompilingSchema(schEnv) {
	    for (const sch of this._compilations) {
	        if (sameSchemaEnv(sch, schEnv))
	            return sch;
	    }
	}
	compile.getCompilingSchema = getCompilingSchema;
	function sameSchemaEnv(s1, s2) {
	    return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
	}
	// resolve and compile the references ($ref)
	// TODO returns AnySchemaObject (if the schema can be inlined) or validation function
	function resolve(root, // information about the root schema for the current schema
	ref // reference to resolve
	) {
	    let sch;
	    while (typeof (sch = this.refs[ref]) == "string")
	        ref = sch;
	    return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
	}
	// Resolve schema, its root and baseId
	function resolveSchema(root, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
	ref // reference to resolve
	) {
	    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);
	    // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
	    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 === undefined ? undefined : sch.schema) !== "object")
	            return;
	        return getJsonPointer.call(this, p, sch);
	    }
	    if (typeof (schOrRef === null || schOrRef === undefined ? undefined : 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.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 === undefined ? undefined : _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;
	        // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
	        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);
	    }
	    // even though resolution failed we need to return SchemaEnv to throw exception
	    // so that compileAsync loads missing schema.
	    const { schemaId } = this.opts;
	    env = env || new SchemaEnv({ schema, schemaId, root, baseId });
	    if (env.schema !== env.root.schema)
	        return env;
	    return undefined;
	}
	
	return compile;
}

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

var uri = {};

var fastUri = {exports: {}};

var scopedChars;
var hasRequiredScopedChars;

function requireScopedChars () {
	if (hasRequiredScopedChars) return scopedChars;
	hasRequiredScopedChars = 1;

	const HEX = {
	  0: 0,
	  1: 1,
	  2: 2,
	  3: 3,
	  4: 4,
	  5: 5,
	  6: 6,
	  7: 7,
	  8: 8,
	  9: 9,
	  a: 10,
	  A: 10,
	  b: 11,
	  B: 11,
	  c: 12,
	  C: 12,
	  d: 13,
	  D: 13,
	  e: 14,
	  E: 14,
	  f: 15,
	  F: 15
	};

	scopedChars = {
	  HEX
	};
	return scopedChars;
}

var utils;
var hasRequiredUtils;

function requireUtils () {
	if (hasRequiredUtils) return utils;
	hasRequiredUtils = 1;

	const { HEX } = requireScopedChars();

	const IPV4_REG = /^(?:(?: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 normalizeIPv4 (host) {
	  if (findToken(host, '.') < 3) { return { host, isIPV4: false } }
	  const matches = host.match(IPV4_REG) || [];
	  const [address] = matches;
	  if (address) {
	    return { host: stripLeadingZeros(address, '.'), isIPV4: true }
	  } else {
	    return { host, isIPV4: false }
	  }
	}

	/**
	 * @param {string[]} input
	 * @param {boolean} [keepZero=false]
	 * @returns {string|undefined}
	 */
	function stringArrayToHexStripped (input, keepZero = false) {
	  let acc = '';
	  let strip = true;
	  for (const c of input) {
	    if (HEX[c] === undefined) return undefined
	    if (c !== '0' && strip === true) strip = false;
	    if (!strip) acc += c;
	  }
	  if (keepZero && acc.length === 0) acc = '0';
	  return acc
	}

	function getIPV6 (input) {
	  let tokenCount = 0;
	  const output = { error: false, address: '', zone: '' };
	  const address = [];
	  const buffer = [];
	  let isZone = false;
	  let endipv6Encountered = false;
	  let endIpv6 = false;

	  function consume () {
	    if (buffer.length) {
	      if (isZone === false) {
	        const hex = stringArrayToHexStripped(buffer);
	        if (hex !== undefined) {
	          address.push(hex);
	        } else {
	          output.error = true;
	          return false
	        }
	      }
	      buffer.length = 0;
	    }
	    return true
	  }

	  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()) { break }
	      tokenCount++;
	      address.push(':');
	      if (tokenCount > 7) {
	        // not valid
	        output.error = true;
	        break
	      }
	      if (i - 1 >= 0 && input[i - 1] === ':') {
	        endipv6Encountered = true;
	      }
	      continue
	    } else if (cursor === '%') {
	      if (!consume()) { break }
	      // switch to zone detection
	      isZone = true;
	    } else {
	      buffer.push(cursor);
	      continue
	    }
	  }
	  if (buffer.length) {
	    if (isZone) {
	      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, escapedHost, isIPV6: true }
	  } else {
	    return { host, isIPV6: false }
	  }
	}

	function stripLeadingZeros (str, token) {
	  let out = '';
	  let skip = true;
	  const l = str.length;
	  for (let i = 0; i < l; i++) {
	    const c = str[i];
	    if (c === '0' && skip) {
	      if ((i + 1 <= l && str[i + 1] === token) || i + 1 === l) {
	        out += c;
	        skip = false;
	      }
	    } else {
	      if (c === token) {
	        skip = true;
	      } else {
	        skip = false;
	      }
	      out += c;
	    }
	  }
	  return out
	}

	function findToken (str, token) {
	  let ind = 0;
	  for (let i = 0; i < str.length; i++) {
	    if (str[i] === token) ind++;
	  }
	  return ind
	}

	const RDS1 = /^\.\.?\//u;
	const RDS2 = /^\/\.(?:\/|$)/u;
	const RDS3 = /^\/\.\.(?:\/|$)/u;
	const RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/u;

	function removeDotSegments (input) {
	  const output = [];

	  while (input.length) {
	    if (input.match(RDS1)) {
	      input = input.replace(RDS1, '');
	    } else if (input.match(RDS2)) {
	      input = input.replace(RDS2, '/');
	    } else if (input.match(RDS3)) {
	      input = input.replace(RDS3, '/');
	      output.pop();
	    } else if (input === '.' || input === '..') {
	      input = '';
	    } else {
	      const im = input.match(RDS5);
	      if (im) {
	        const s = im[0];
	        input = input.slice(s.length);
	        output.push(s);
	      } else {
	        throw new Error('Unexpected dot segment condition')
	      }
	    }
	  }
	  return output.join('')
	}

	function normalizeComponentEncoding (components, esc) {
	  const func = esc !== true ? escape : unescape;
	  if (components.scheme !== undefined) {
	    components.scheme = func(components.scheme);
	  }
	  if (components.userinfo !== undefined) {
	    components.userinfo = func(components.userinfo);
	  }
	  if (components.host !== undefined) {
	    components.host = func(components.host);
	  }
	  if (components.path !== undefined) {
	    components.path = func(components.path);
	  }
	  if (components.query !== undefined) {
	    components.query = func(components.query);
	  }
	  if (components.fragment !== undefined) {
	    components.fragment = func(components.fragment);
	  }
	  return components
	}

	function recomposeAuthority (components) {
	  const uriTokens = [];

	  if (components.userinfo !== undefined) {
	    uriTokens.push(components.userinfo);
	    uriTokens.push('@');
	  }

	  if (components.host !== undefined) {
	    let host = unescape(components.host);
	    const ipV4res = normalizeIPv4(host);

	    if (ipV4res.isIPV4) {
	      host = ipV4res.host;
	    } else {
	      const ipV6res = normalizeIPv6(ipV4res.host);
	      if (ipV6res.isIPV6 === true) {
	        host = `[${ipV6res.escapedHost}]`;
	      } else {
	        host = components.host;
	      }
	    }
	    uriTokens.push(host);
	  }

	  if (typeof components.port === 'number' || typeof components.port === 'string') {
	    uriTokens.push(':');
	    uriTokens.push(String(components.port));
	  }

	  return uriTokens.length ? uriTokens.join('') : undefined
	}
	utils = {
	  recomposeAuthority,
	  normalizeComponentEncoding,
	  removeDotSegments,
	  normalizeIPv4,
	  normalizeIPv6,
	  stringArrayToHexStripped
	};
	return utils;
}

var schemes;
var hasRequiredSchemes;

function requireSchemes () {
	if (hasRequiredSchemes) return schemes;
	hasRequiredSchemes = 1;

	const UUID_REG = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu;
	const URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;

	function isSecure (wsComponents) {
	  return typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === 'wss'
	}

	function httpParse (components) {
	  if (!components.host) {
	    components.error = components.error || 'HTTP URIs must have a host.';
	  }

	  return components
	}

	function httpSerialize (components) {
	  const secure = String(components.scheme).toLowerCase() === 'https';

	  // normalize the default port
	  if (components.port === (secure ? 443 : 80) || components.port === '') {
	    components.port = undefined;
	  }

	  // normalize the empty path
	  if (!components.path) {
	    components.path = '/';
	  }

	  // NOTE: We do not parse query strings for HTTP URIs
	  // as WWW Form Url Encoded query strings are part of the HTML4+ spec,
	  // and not the HTTP spec.

	  return components
	}

	function wsParse (wsComponents) {
	// indicate if the secure flag is set
	  wsComponents.secure = isSecure(wsComponents);

	  // construct resouce name
	  wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');
	  wsComponents.path = undefined;
	  wsComponents.query = undefined;

	  return wsComponents
	}

	function wsSerialize (wsComponents) {
	// normalize the default port
	  if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === '') {
	    wsComponents.port = undefined;
	  }

	  // ensure scheme matches secure flag
	  if (typeof wsComponents.secure === 'boolean') {
	    wsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');
	    wsComponents.secure = undefined;
	  }

	  // reconstruct path from resource name
	  if (wsComponents.resourceName) {
	    const [path, query] = wsComponents.resourceName.split('?');
	    wsComponents.path = (path && path !== '/' ? path : undefined);
	    wsComponents.query = query;
	    wsComponents.resourceName = undefined;
	  }

	  // forbid fragment component
	  wsComponents.fragment = undefined;

	  return wsComponents
	}

	function urnParse (urnComponents, options) {
	  if (!urnComponents.path) {
	    urnComponents.error = 'URN can not be parsed';
	    return urnComponents
	  }
	  const matches = urnComponents.path.match(URN_REG);
	  if (matches) {
	    const scheme = options.scheme || urnComponents.scheme || 'urn';
	    urnComponents.nid = matches[1].toLowerCase();
	    urnComponents.nss = matches[2];
	    const urnScheme = `${scheme}:${options.nid || urnComponents.nid}`;
	    const schemeHandler = SCHEMES[urnScheme];
	    urnComponents.path = undefined;

	    if (schemeHandler) {
	      urnComponents = schemeHandler.parse(urnComponents, options);
	    }
	  } else {
	    urnComponents.error = urnComponents.error || 'URN can not be parsed.';
	  }

	  return urnComponents
	}

	function urnSerialize (urnComponents, options) {
	  const scheme = options.scheme || urnComponents.scheme || 'urn';
	  const nid = urnComponents.nid.toLowerCase();
	  const urnScheme = `${scheme}:${options.nid || nid}`;
	  const schemeHandler = SCHEMES[urnScheme];

	  if (schemeHandler) {
	    urnComponents = schemeHandler.serialize(urnComponents, options);
	  }

	  const uriComponents = urnComponents;
	  const nss = urnComponents.nss;
	  uriComponents.path = `${nid || options.nid}:${nss}`;

	  options.skipEscape = true;
	  return uriComponents
	}

	function urnuuidParse (urnComponents, options) {
	  const uuidComponents = urnComponents;
	  uuidComponents.uuid = uuidComponents.nss;
	  uuidComponents.nss = undefined;

	  if (!options.tolerant && (!uuidComponents.uuid || !UUID_REG.test(uuidComponents.uuid))) {
	    uuidComponents.error = uuidComponents.error || 'UUID is not valid.';
	  }

	  return uuidComponents
	}

	function urnuuidSerialize (uuidComponents) {
	  const urnComponents = uuidComponents;
	  // normalize UUID
	  urnComponents.nss = (uuidComponents.uuid || '').toLowerCase();
	  return urnComponents
	}

	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
	};

	schemes = SCHEMES;
	return schemes;
}

var hasRequiredFastUri;

function requireFastUri () {
	if (hasRequiredFastUri) return fastUri.exports;
	hasRequiredFastUri = 1;

	const { normalizeIPv6, normalizeIPv4, removeDotSegments, recomposeAuthority, normalizeComponentEncoding } = requireUtils();
	const SCHEMES = 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 = Object.assign({ scheme: 'null' }, options);
	  const resolved = resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true);
	  return serialize(resolved, { ...schemelessOptions, skipEscape: true })
	}

	function resolveComponents (base, relative, options, skipNormalization) {
	  const target = {};
	  if (!skipNormalization) {
	    base = parse(serialize(base, options), options); // normalize base components
	    relative = parse(serialize(relative, options), options); // normalize relative components
	  }
	  options = options || {};

	  if (!options.tolerant && relative.scheme) {
	    target.scheme = relative.scheme;
	    // target.authority = relative.authority;
	    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.authority = relative.authority;
	      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.charAt(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.authority = base.authority;
	      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 components = {
	    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 = [];

	  // find scheme handler
	  const schemeHandler = SCHEMES[(options.scheme || components.scheme || '').toLowerCase()];

	  // perform scheme specific serialization
	  if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);

	  if (components.path !== undefined) {
	    if (!options.skipEscape) {
	      components.path = escape(components.path);

	      if (components.scheme !== undefined) {
	        components.path = components.path.split('%3A').join(':');
	      }
	    } else {
	      components.path = unescape(components.path);
	    }
	  }

	  if (options.reference !== 'suffix' && components.scheme) {
	    uriTokens.push(components.scheme, ':');
	  }

	  const authority = recomposeAuthority(components);
	  if (authority !== undefined) {
	    if (options.reference !== 'suffix') {
	      uriTokens.push('//');
	    }

	    uriTokens.push(authority);

	    if (components.path && components.path.charAt(0) !== '/') {
	      uriTokens.push('/');
	    }
	  }
	  if (components.path !== undefined) {
	    let s = components.path;

	    if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
	      s = removeDotSegments(s);
	    }

	    if (authority === undefined) {
	      s = s.replace(/^\/\//u, '/%2F'); // don't allow the path to start with "//"
	    }

	    uriTokens.push(s);
	  }

	  if (components.query !== undefined) {
	    uriTokens.push('?', components.query);
	  }

	  if (components.fragment !== undefined) {
	    uriTokens.push('#', components.fragment);
	  }
	  return uriTokens.join('')
	}

	const hexLookUp = Array.from({ length: 127 }, (_v, k) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(k)));

	function nonSimpleDomain (value) {
	  let code = 0;
	  for (let i = 0, len = value.length; i < len; ++i) {
	    code = value.charCodeAt(i);
	    if (code > 126 || hexLookUp[code]) {
	      return true
	    }
	  }
	  return false
	}

	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
	  };
	  const gotEncoding = uri.indexOf('%') !== -1;
	  let isIP = false;
	  if (options.reference === 'suffix') uri = (options.scheme ? options.scheme + ':' : '') + '//' + uri;

	  const matches = uri.match(URI_PARSE);

	  if (matches) {
	    // store each component
	    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];

	    // fix port number
	    if (isNaN(parsed.port)) {
	      parsed.port = matches[5];
	    }
	    if (parsed.host) {
	      const ipv4result = normalizeIPv4(parsed.host);
	      if (ipv4result.isIPV4 === false) {
	        const ipv6result = normalizeIPv6(ipv4result.host);
	        parsed.host = ipv6result.host.toLowerCase();
	        isIP = ipv6result.isIPV6;
	      } else {
	        parsed.host = ipv4result.host;
	        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';
	    }

	    // check for reference errors
	    if (options.reference && options.reference !== 'suffix' && options.reference !== parsed.reference) {
	      parsed.error = parsed.error || 'URI is not a ' + options.reference + ' reference.';
	    }

	    // find scheme handler
	    const schemeHandler = SCHEMES[(options.scheme || parsed.scheme || '').toLowerCase()];

	    // check if scheme can't handle IRIs
	    if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
	      // if host component is a domain name
	      if (parsed.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost)) && isIP === false && nonSimpleDomain(parsed.host)) {
	        // convert Unicode IDN -> ASCII IDN
	        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;
	        }
	      }
	      // convert IRI -> URI
	    }

	    if (!schemeHandler || (schemeHandler && !schemeHandler.skipNormalize)) {
	      if (gotEncoding && parsed.scheme !== undefined) {
	        parsed.scheme = unescape(parsed.scheme);
	      }
	      if (gotEncoding && 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));
	      }
	    }

	    // perform scheme specific parsing
	    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,
	  resolveComponents,
	  equal,
	  serialize,
	  parse
	};

	fastUri.exports = fastUri$1;
	fastUri.exports.default = fastUri$1;
	fastUri.exports.fastUri = fastUri$1;
	return fastUri.exports;
}

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$3;

function requireCore$3 () {
	if (hasRequiredCore$3) return core$3;
	hasRequiredCore$3 = 1;
	(function (exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = undefined;
		var validate_1 = requireValidate();
		Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen();
		Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports, "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();
		const codegen_2 = requireCodegen();
		const resolve_1 = requireResolve();
		const dataType_1 = requireDataType();
		const util_1 = requireUtil();
		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;
		// eslint-disable-next-line complexity
		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 === undefined ? undefined : _a.optimize;
		    const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0;
		    const regExp = (_c = (_b = o.code) === null || _b === undefined ? undefined : _b.regExp) !== null && _c !== undefined ? _c : defaultRegExp;
		    const uriResolver = (_d = o.uriResolver) !== null && _d !== undefined ? _d : uri_1.default;
		    return {
		        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== undefined ? _e : s) !== null && _f !== undefined ? _f : true,
		        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== undefined ? _g : s) !== null && _h !== undefined ? _h : true,
		        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== undefined ? _j : s) !== null && _k !== undefined ? _k : "log",
		        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== undefined ? _l : s) !== null && _m !== undefined ? _m : "log",
		        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== undefined ? _o : s) !== null && _p !== undefined ? _p : false,
		        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
		        loopRequired: (_q = o.loopRequired) !== null && _q !== undefined ? _q : MAX_EXPRESSION,
		        loopEnum: (_r = o.loopEnum) !== null && _r !== undefined ? _r : MAX_EXPRESSION,
		        meta: (_s = o.meta) !== null && _s !== undefined ? _s : true,
		        messages: (_t = o.messages) !== null && _t !== undefined ? _t : true,
		        inlineRefs: (_u = o.inlineRefs) !== null && _u !== undefined ? _u : true,
		        schemaId: (_v = o.schemaId) !== null && _v !== undefined ? _v : "$id",
		        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== undefined ? _w : true,
		        validateSchema: (_x = o.validateSchema) !== null && _x !== undefined ? _x : true,
		        validateFormats: (_y = o.validateFormats) !== null && _y !== undefined ? _y : true,
		        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== undefined ? _z : true,
		        int32range: (_0 = o.int32range) !== null && _0 !== undefined ? _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, // key, ref or schema object
		    // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
		    data // to be validated
		    ) {
		        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];
		            }
		        }
		    }
		    // Adds schema to the instance
		    addSchema(schema, // If array is passed, `key` will be ignored
		    key, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
		    _meta, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
		    _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
		    ) {
		        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;
		    }
		    // Add schema that will be used to validate other schemas
		    // options in META_IGNORE_OPTIONS are alway set to false
		    addMetaSchema(schema, key, // schema key
		    _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
		    ) {
		        this.addSchema(schema, key, true, _validateSchema);
		        return this;
		    }
		    //  Validate schema against its meta-schema
		    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;
		    }
		    // Get compiled schema by `key` or `ref`.
		    // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
		    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));
		    }
		    // Remove cached schema(s).
		    // If no parameter is passed all schemas but meta-schemas are removed.
		    // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
		    // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
		    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");
		        }
		    }
		    // add "vocabulary" - a collection of keywords
		    addVocabulary(definitions) {
		        for (const def of definitions)
		            this.addKeyword(def);
		        return this;
		    }
		    addKeyword(kwdOrDef, def // deprecated
		    ) {
		        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;
		    }
		    // Remove keyword
		    removeKeyword(keyword) {
		        // TODO return type should be Ajv
		        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;
		    }
		    // Add format
		    addFormat(name, format) {
		        if (typeof format == "string")
		            format = new RegExp(format);
		        this.formats[name] = format;
		        return this;
		    }
		    errorsText(errors = this.errors, // optional array of validation errors
		    { separator = ", ", dataVar = "data" } = {} // optional options with properties `separator` and `dataVar`
		    ) {
		        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); // first segment is an empty string
		            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("#")) {
		            // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
		            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);
		        /* istanbul ignore if */
		        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.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); // TODO tests fail without this line
		    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 === undefined ? undefined : 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 === undefined ? undefined : _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 draft4 = {};

var core$2 = {};

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 = undefined;
	const ref_error_1 = requireRef_error();
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const compile_1 = requireCompile();
	const util_1 = requireUtil();
	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); // TODO will not work with async, it has to be returned with the result
	            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})`); // TODO tagged
	        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 === undefined ? undefined : sch.validate) === null || _a === undefined ? undefined : _a.evaluated;
	        // TODO refactor
	        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$2;

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

var validation$1 = {};

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 core_1 = requireCore$3();
	const codegen_1 = requireCodegen();
	const ops = codegen_1.operators;
	const KWDs = {
	    maximum: {
	        exclusive: "exclusiveMaximum",
	        ops: [
	            { okStr: "<=", ok: ops.LTE, fail: ops.GT },
	            { okStr: "<", ok: ops.LT, fail: ops.GTE },
	        ],
	    },
	    minimum: {
	        exclusive: "exclusiveMinimum",
	        ops: [
	            { okStr: ">=", ok: ops.GTE, fail: ops.LT },
	            { okStr: ">", ok: ops.GT, fail: ops.LTE },
	        ],
	    },
	};
	const error = {
	    message: (cxt) => core_1.str `must be ${kwdOp(cxt).okStr} ${cxt.schemaCode}`,
	    params: (cxt) => core_1._ `{comparison: ${kwdOp(cxt).okStr}, limit: ${cxt.schemaCode}}`,
	};
	const def = {
	    keyword: Object.keys(KWDs),
	    type: "number",
	    schemaType: "number",
	    $data: true,
	    error,
	    code(cxt) {
	        const { data, schemaCode } = cxt;
	        cxt.fail$data(core_1._ `${data} ${kwdOp(cxt).fail} ${schemaCode} || isNaN(${data})`);
	    },
	};
	function kwdOp(cxt) {
	    var _a;
	    const keyword = cxt.keyword;
	    const opsIdx = ((_a = cxt.parentSchema) === null || _a === undefined ? undefined : _a[KWDs[keyword].exclusive]) ? 1 : 0;
	    return KWDs[keyword].ops[opsIdx];
	}
	limitNumber$1.default = def;
	
	return limitNumber$1;
}

var limitNumberExclusive = {};

var hasRequiredLimitNumberExclusive;

function requireLimitNumberExclusive () {
	if (hasRequiredLimitNumberExclusive) return limitNumberExclusive;
	hasRequiredLimitNumberExclusive = 1;
	Object.defineProperty(limitNumberExclusive, "__esModule", { value: true });
	const KWDs = {
	    exclusiveMaximum: "maximum",
	    exclusiveMinimum: "minimum",
	};
	const def = {
	    keyword: Object.keys(KWDs),
	    type: "number",
	    schemaType: "boolean",
	    code({ keyword, parentSchema }) {
	        const limitKwd = KWDs[keyword];
	        if (parentSchema[limitKwd] === undefined) {
	            throw new Error(`${keyword} can only be used with ${limitKwd}`);
	        }
	    },
	};
	limitNumberExclusive.default = def;
	
	return limitNumberExclusive;
}

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 bdt = bad$DataType(schemaCode, <string>def.schemaType, $data)
	        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 });
	// https://mathiasbynens.be/notes/javascript-encoding
	// https://github.com/bestiejs/punycode.js - punycode.ucs2.decode
	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) {
	            // high surrogate, and there is a next character
	            value = str.charCodeAt(pos);
	            if ((value & 0xfc00) === 0xdc00)
	                pos++; // low surrogate
	        }
	    }
	    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();
	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();
	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;
	        // TODO regexp should be wrapped in try/catchs
	        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$4 = {};

var hasRequiredRequired;

function requireRequired () {
	if (hasRequiredRequired) return required$4;
	hasRequiredRequired = 1;
	Object.defineProperty(required$4, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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 === undefined ? undefined : 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$4.default = def;
	
	return required$4;
}

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 });
	// https://github.com/ajv-validator/ajv/issues/889
	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();
	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();
	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();
	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 !== undefined ? 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 {
	            /* istanbul ignore if */
	            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$1();
	const limitNumberExclusive_1 = requireLimitNumberExclusive();
	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 = [
	    // number
	    limitNumber_1.default,
	    limitNumberExclusive_1.default,
	    multipleOf_1.default,
	    // string
	    limitLength_1.default,
	    pattern_1.default,
	    // object
	    limitProperties_1.default,
	    required_1.default,
	    // array
	    limitItems_1.default,
	    uniqueItems_1.default,
	    // any
	    { 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 = undefined;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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}`); // TODO var
	        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 = undefined;
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	const code_1 = requireCode();
	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();
	const code_1 = requireCode();
	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 = {};

var hasRequiredContains;

function requireContains () {
	if (hasRequiredContains) return contains;
	hasRequiredContains = 1;
	Object.defineProperty(contains, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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.default = def;
	
	return contains;
}

var dependencies$1 = {};

var hasRequiredDependencies;

function requireDependencies () {
	if (hasRequiredDependencies) return dependencies$1;
	hasRequiredDependencies = 1;
	(function (exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = undefined;
		const codegen_1 = requireCodegen();
		const util_1 = requireUtil();
		const code_1 = requireCode();
		exports.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}}`, // TODO change to reference
		};
		const def = {
		    keyword: "dependencies",
		    type: "object",
		    schemaType: "object",
		    error: exports.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.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) // TODO var
		        );
		        cxt.ok(valid);
		    }
		}
		exports.validateSchemaDeps = validateSchemaDeps;
		exports.default = def;
		
	} (dependencies$1));
	return dependencies$1;
}

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();
	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$3 = {};

var hasRequiredAdditionalProperties;

function requireAdditionalProperties () {
	if (hasRequiredAdditionalProperties) return additionalProperties$3;
	hasRequiredAdditionalProperties = 1;
	Object.defineProperty(additionalProperties$3, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const util_1 = requireUtil();
	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;
	        /* istanbul ignore if */
	        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) {
	                // TODO maybe an option instead of hard-coded 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$3.default = def;
	
	return additionalProperties$3;
}

var properties$d = {};

var hasRequiredProperties;

function requireProperties () {
	if (hasRequiredProperties) return properties$d;
	hasRequiredProperties = 1;
	Object.defineProperty(properties$d, "__esModule", { value: true });
	const validate_1 = requireValidate();
	const code_1 = requireCode();
	const util_1 = requireUtil();
	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$d.default = def;
	
	return properties$d;
}

var patternProperties$2 = {};

var hasRequiredPatternProperties;

function requirePatternProperties () {
	if (hasRequiredPatternProperties) return patternProperties$2;
	hasRequiredPatternProperties = 1;
	Object.defineProperty(patternProperties$2, "__esModule", { value: true });
	const code_1 = requireCode();
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	const util_2 = requireUtil();
	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); // TODO var
	                    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) {
	                        // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false)
	                        // or if all properties were evaluated (props === true)
	                        gen.if((0, codegen_1.not)(valid), () => gen.break());
	                    }
	                });
	            });
	        }
	    },
	};
	patternProperties$2.default = def;
	
	return patternProperties$2;
}

var not = {};

var hasRequiredNot;

function requireNot () {
	if (hasRequiredNot) return not;
	hasRequiredNot = 1;
	Object.defineProperty(not, "__esModule", { value: true });
	const util_1 = requireUtil();
	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$1 = {};

var hasRequiredAnyOf;

function requireAnyOf () {
	if (hasRequiredAnyOf) return anyOf$1;
	hasRequiredAnyOf = 1;
	Object.defineProperty(anyOf$1, "__esModule", { value: true });
	const code_1 = requireCode();
	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 = {};

var hasRequiredOneOf;

function requireOneOf () {
	if (hasRequiredOneOf) return oneOf;
	hasRequiredOneOf = 1;
	Object.defineProperty(oneOf, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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;
	        /* istanbul ignore if */
	        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 });
	        // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas
	        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$1 = {};

var hasRequiredAllOf;

function requireAllOf () {
	if (hasRequiredAllOf) return allOf$1;
	hasRequiredAllOf = 1;
	Object.defineProperty(allOf$1, "__esModule", { value: true });
	const util_1 = requireUtil();
	const def = {
	    keyword: "allOf",
	    schemaType: "array",
	    code(cxt) {
	        const { gen, schema, it } = cxt;
	        /* istanbul ignore if */
	        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 = {};

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();
	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();
	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 = [
	        // any
	        not_1.default,
	        anyOf_1.default,
	        oneOf_1.default,
	        allOf_1.default,
	        if_1.default,
	        thenElse_1.default,
	        // object
	        propertyNames_1.default,
	        additionalProperties_1.default,
	        dependencies_1.default,
	        properties_1.default,
	        patternProperties_1.default,
	    ];
	    // array
	    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$1 = {};

var format = {};

var hasRequiredFormat$1;

function requireFormat$1 () {
	if (hasRequiredFormat$1) return format;
	hasRequiredFormat$1 = 1;
	Object.defineProperty(format, "__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");
	            // TODO simplify
	            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.default = def;
	
	return format;
}

var hasRequiredFormat;

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

var hasRequiredDraft4;

function requireDraft4 () {
	if (hasRequiredDraft4) return draft4;
	hasRequiredDraft4 = 1;
	Object.defineProperty(draft4, "__esModule", { value: true });
	const core_1 = requireCore$2();
	const validation_1 = requireValidation$1();
	const applicator_1 = requireApplicator();
	const format_1 = requireFormat();
	const metadataVocabulary = ["title", "description", "default"];
	const draft4Vocabularies = [
	    core_1.default,
	    validation_1.default,
	    applicator_1.default(),
	    format_1.default,
	    metadataVocabulary,
	];
	draft4.default = draft4Vocabularies;
	
	return draft4;
}

var discriminator = {};

var types = {};

var hasRequiredTypes;

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

var hasRequiredDiscriminator;

function requireDiscriminator () {
	if (hasRequiredDiscriminator) return discriminator;
	hasRequiredDiscriminator = 1;
	Object.defineProperty(discriminator, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const types_1 = requireTypes();
	const compile_1 = requireCompile();
	const ref_error_1 = requireRef_error();
	const util_1 = requireUtil();
	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 === undefined ? undefined : 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 === undefined ? undefined : sch.properties) === null || _a === undefined ? undefined : _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 id$4 = "http://json-schema.org/draft-04/schema#";
var $schema$c = "http://json-schema.org/draft-04/schema#";
var description$1 = "Core schema meta-schema";
var definitions$3 = {
	schemaArray: {
		type: "array",
		minItems: 1,
		items: {
			$ref: "#"
		}
	},
	positiveInteger: {
		type: "integer",
		minimum: 0
	},
	positiveIntegerDefault0: {
		allOf: [
			{
				$ref: "#/definitions/positiveInteger"
			},
			{
				"default": 0
			}
		]
	},
	simpleTypes: {
		"enum": [
			"array",
			"boolean",
			"integer",
			"null",
			"number",
			"object",
			"string"
		]
	},
	stringArray: {
		type: "array",
		items: {
			type: "string"
		},
		minItems: 1,
		uniqueItems: true
	}
};
var type$d = "object";
var properties$c = {
	id: {
		type: "string",
		format: "uri"
	},
	$schema: {
		type: "string",
		format: "uri"
	},
	title: {
		type: "string"
	},
	description: {
		type: "string"
	},
	"default": {
	},
	multipleOf: {
		type: "number",
		minimum: 0,
		exclusiveMinimum: true
	},
	maximum: {
		type: "number"
	},
	exclusiveMaximum: {
		type: "boolean",
		"default": false
	},
	minimum: {
		type: "number"
	},
	exclusiveMinimum: {
		type: "boolean",
		"default": false
	},
	maxLength: {
		$ref: "#/definitions/positiveInteger"
	},
	minLength: {
		$ref: "#/definitions/positiveIntegerDefault0"
	},
	pattern: {
		type: "string",
		format: "regex"
	},
	additionalItems: {
		anyOf: [
			{
				type: "boolean"
			},
			{
				$ref: "#"
			}
		],
		"default": {
		}
	},
	items: {
		anyOf: [
			{
				$ref: "#"
			},
			{
				$ref: "#/definitions/schemaArray"
			}
		],
		"default": {
		}
	},
	maxItems: {
		$ref: "#/definitions/positiveInteger"
	},
	minItems: {
		$ref: "#/definitions/positiveIntegerDefault0"
	},
	uniqueItems: {
		type: "boolean",
		"default": false
	},
	maxProperties: {
		$ref: "#/definitions/positiveInteger"
	},
	minProperties: {
		$ref: "#/definitions/positiveIntegerDefault0"
	},
	required: {
		$ref: "#/definitions/stringArray"
	},
	additionalProperties: {
		anyOf: [
			{
				type: "boolean"
			},
			{
				$ref: "#"
			}
		],
		"default": {
		}
	},
	definitions: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	properties: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	patternProperties: {
		type: "object",
		additionalProperties: {
			$ref: "#"
		},
		"default": {
		}
	},
	dependencies: {
		type: "object",
		additionalProperties: {
			anyOf: [
				{
					$ref: "#"
				},
				{
					$ref: "#/definitions/stringArray"
				}
			]
		}
	},
	"enum": {
		type: "array",
		minItems: 1,
		uniqueItems: true
	},
	type: {
		anyOf: [
			{
				$ref: "#/definitions/simpleTypes"
			},
			{
				type: "array",
				items: {
					$ref: "#/definitions/simpleTypes"
				},
				minItems: 1,
				uniqueItems: true
			}
		]
	},
	allOf: {
		$ref: "#/definitions/schemaArray"
	},
	anyOf: {
		$ref: "#/definitions/schemaArray"
	},
	oneOf: {
		$ref: "#/definitions/schemaArray"
	},
	not: {
		$ref: "#"
	}
};
var dependencies = {
	exclusiveMaximum: [
		"maximum"
	],
	exclusiveMinimum: [
		"minimum"
	]
};
var require$$3$2 = {
	id: id$4,
	$schema: $schema$c,
	description: description$1,
	definitions: definitions$3,
	type: type$d,
	properties: properties$c,
	dependencies: dependencies,
	"default": {
}
};

var hasRequiredDist;

function requireDist () {
	if (hasRequiredDist) return dist.exports;
	hasRequiredDist = 1;
	(function (module, exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = undefined;
		const core_1 = requireCore$3();
		const draft4_1 = requireDraft4();
		const discriminator_1 = requireDiscriminator();
		const draft4MetaSchema = require$$3$2;
		const META_SUPPORT_DATA = ["/properties"];
		const META_SCHEMA_ID = "http://json-schema.org/draft-04/schema";
		class Ajv extends core_1.default {
		    constructor(opts = {}) {
		        super({
		            ...opts,
		            schemaId: "id",
		        });
		    }
		    _addVocabularies() {
		        super._addVocabularies();
		        draft4_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(draft4MetaSchema, META_SUPPORT_DATA)
		            : draft4MetaSchema;
		        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));
		    }
		}
		module.exports = exports = Ajv;
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.default = Ajv;
		var core_2 = requireCore$3();
		Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return core_2.KeywordCxt; } });
		var core_3 = requireCore$3();
		Object.defineProperty(exports, "_", { enumerable: true, get: function () { return core_3._; } });
		Object.defineProperty(exports, "str", { enumerable: true, get: function () { return core_3.str; } });
		Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return core_3.stringify; } });
		Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return core_3.nil; } });
		Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return core_3.Name; } });
		Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return core_3.CodeGen; } });
		
	} (dist, dist.exports));
	return dist.exports;
}

var _2020 = {exports: {}};

var draft2020 = {};

var core$1 = {};

var id$3 = {};

var hasRequiredId;

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

var hasRequiredCore$1;

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

var validation = {};

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 hasRequiredValidation;

function requireValidation () {
	if (hasRequiredValidation) return validation;
	hasRequiredValidation = 1;
	Object.defineProperty(validation, "__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$1 = [
	    // number
	    limitNumber_1.default,
	    multipleOf_1.default,
	    // string
	    limitLength_1.default,
	    pattern_1.default,
	    // object
	    limitProperties_1.default,
	    required_1.default,
	    // array
	    limitItems_1.default,
	    uniqueItems_1.default,
	    // any
	    { keyword: "type", schemaType: ["string", "array"] },
	    { keyword: "nullable", schemaType: "boolean" },
	    const_1.default,
	    enum_1.default,
	];
	validation.default = validation$1;
	
	return validation;
}

var dynamic = {};

var dynamicAnchor = {};

var hasRequiredDynamicAnchor;

function requireDynamicAnchor () {
	if (hasRequiredDynamicAnchor) return dynamicAnchor;
	hasRequiredDynamicAnchor = 1;
	Object.defineProperty(dynamicAnchor, "__esModule", { value: true });
	dynamicAnchor.dynamicAnchor = undefined;
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const compile_1 = requireCompile();
	const ref_1 = requireRef$1();
	const def = {
	    keyword: "$dynamicAnchor",
	    schemaType: "string",
	    code: (cxt) => dynamicAnchor$1(cxt, cxt.schema),
	};
	function dynamicAnchor$1(cxt, anchor) {
	    const { gen, it } = cxt;
	    it.schemaEnv.root.dynamicAnchors[anchor] = true;
	    const v = (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`;
	    const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt);
	    gen.if((0, codegen_1._) `!${v}`, () => gen.assign(v, validate));
	}
	dynamicAnchor.dynamicAnchor = dynamicAnchor$1;
	function _getValidate(cxt) {
	    const { schemaEnv, schema, self } = cxt.it;
	    const { root, baseId, localRefs, meta } = schemaEnv.root;
	    const { schemaId } = self.opts;
	    const sch = new compile_1.SchemaEnv({ schema, schemaId, root, baseId, localRefs, meta });
	    compile_1.compileSchema.call(self, sch);
	    return (0, ref_1.getValidate)(cxt, sch);
	}
	dynamicAnchor.default = def;
	
	return dynamicAnchor;
}

var dynamicRef = {};

var hasRequiredDynamicRef;

function requireDynamicRef () {
	if (hasRequiredDynamicRef) return dynamicRef;
	hasRequiredDynamicRef = 1;
	Object.defineProperty(dynamicRef, "__esModule", { value: true });
	dynamicRef.dynamicRef = undefined;
	const codegen_1 = requireCodegen();
	const names_1 = requireNames();
	const ref_1 = requireRef$1();
	const def = {
	    keyword: "$dynamicRef",
	    schemaType: "string",
	    code: (cxt) => dynamicRef$1(cxt, cxt.schema),
	};
	function dynamicRef$1(cxt, ref) {
	    const { gen, keyword, it } = cxt;
	    if (ref[0] !== "#")
	        throw new Error(`"${keyword}" only supports hash fragment reference`);
	    const anchor = ref.slice(1);
	    if (it.allErrors) {
	        _dynamicRef();
	    }
	    else {
	        const valid = gen.let("valid", false);
	        _dynamicRef(valid);
	        cxt.ok(valid);
	    }
	    function _dynamicRef(valid) {
	        // TODO the assumption here is that `recursiveRef: #` always points to the root
	        // of the schema object, which is not correct, because there may be $id that
	        // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor.
	        // Because of that 2 tests in recursiveRef.json fail.
	        // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`).
	        // (This problem is not tested in JSON-Schema-Test-Suite)
	        if (it.schemaEnv.root.dynamicAnchors[anchor]) {
	            const v = gen.let("_v", (0, codegen_1._) `${names_1.default.dynamicAnchors}${(0, codegen_1.getProperty)(anchor)}`);
	            gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid));
	        }
	        else {
	            _callRef(it.validateName, valid)();
	        }
	    }
	    function _callRef(validate, valid) {
	        return valid
	            ? () => gen.block(() => {
	                (0, ref_1.callRef)(cxt, validate);
	                gen.let(valid, true);
	            })
	            : () => (0, ref_1.callRef)(cxt, validate);
	    }
	}
	dynamicRef.dynamicRef = dynamicRef$1;
	dynamicRef.default = def;
	
	return dynamicRef;
}

var recursiveAnchor = {};

var hasRequiredRecursiveAnchor;

function requireRecursiveAnchor () {
	if (hasRequiredRecursiveAnchor) return recursiveAnchor;
	hasRequiredRecursiveAnchor = 1;
	Object.defineProperty(recursiveAnchor, "__esModule", { value: true });
	const dynamicAnchor_1 = requireDynamicAnchor();
	const util_1 = requireUtil();
	const def = {
	    keyword: "$recursiveAnchor",
	    schemaType: "boolean",
	    code(cxt) {
	        if (cxt.schema)
	            (0, dynamicAnchor_1.dynamicAnchor)(cxt, "");
	        else
	            (0, util_1.checkStrictMode)(cxt.it, "$recursiveAnchor: false is ignored");
	    },
	};
	recursiveAnchor.default = def;
	
	return recursiveAnchor;
}

var recursiveRef = {};

var hasRequiredRecursiveRef;

function requireRecursiveRef () {
	if (hasRequiredRecursiveRef) return recursiveRef;
	hasRequiredRecursiveRef = 1;
	Object.defineProperty(recursiveRef, "__esModule", { value: true });
	const dynamicRef_1 = requireDynamicRef();
	const def = {
	    keyword: "$recursiveRef",
	    schemaType: "string",
	    code: (cxt) => (0, dynamicRef_1.dynamicRef)(cxt, cxt.schema),
	};
	recursiveRef.default = def;
	
	return recursiveRef;
}

var hasRequiredDynamic;

function requireDynamic () {
	if (hasRequiredDynamic) return dynamic;
	hasRequiredDynamic = 1;
	Object.defineProperty(dynamic, "__esModule", { value: true });
	const dynamicAnchor_1 = requireDynamicAnchor();
	const dynamicRef_1 = requireDynamicRef();
	const recursiveAnchor_1 = requireRecursiveAnchor();
	const recursiveRef_1 = requireRecursiveRef();
	const dynamic$1 = [dynamicAnchor_1.default, dynamicRef_1.default, recursiveAnchor_1.default, recursiveRef_1.default];
	dynamic.default = dynamic$1;
	
	return dynamic;
}

var next$2 = {};

var dependentRequired = {};

var hasRequiredDependentRequired;

function requireDependentRequired () {
	if (hasRequiredDependentRequired) return dependentRequired;
	hasRequiredDependentRequired = 1;
	Object.defineProperty(dependentRequired, "__esModule", { value: true });
	const dependencies_1 = requireDependencies();
	const def = {
	    keyword: "dependentRequired",
	    type: "object",
	    schemaType: "object",
	    error: dependencies_1.error,
	    code: (cxt) => (0, dependencies_1.validatePropertyDeps)(cxt),
	};
	dependentRequired.default = def;
	
	return dependentRequired;
}

var dependentSchemas = {};

var hasRequiredDependentSchemas;

function requireDependentSchemas () {
	if (hasRequiredDependentSchemas) return dependentSchemas;
	hasRequiredDependentSchemas = 1;
	Object.defineProperty(dependentSchemas, "__esModule", { value: true });
	const dependencies_1 = requireDependencies();
	const def = {
	    keyword: "dependentSchemas",
	    type: "object",
	    schemaType: "object",
	    code: (cxt) => (0, dependencies_1.validateSchemaDeps)(cxt),
	};
	dependentSchemas.default = def;
	
	return dependentSchemas;
}

var limitContains = {};

var hasRequiredLimitContains;

function requireLimitContains () {
	if (hasRequiredLimitContains) return limitContains;
	hasRequiredLimitContains = 1;
	Object.defineProperty(limitContains, "__esModule", { value: true });
	const util_1 = requireUtil();
	const def = {
	    keyword: ["maxContains", "minContains"],
	    type: "array",
	    schemaType: "number",
	    code({ keyword, parentSchema, it }) {
	        if (parentSchema.contains === undefined) {
	            (0, util_1.checkStrictMode)(it, `"${keyword}" without "contains" is ignored`);
	        }
	    },
	};
	limitContains.default = def;
	
	return limitContains;
}

var hasRequiredNext$2;

function requireNext$2 () {
	if (hasRequiredNext$2) return next$2;
	hasRequiredNext$2 = 1;
	Object.defineProperty(next$2, "__esModule", { value: true });
	const dependentRequired_1 = requireDependentRequired();
	const dependentSchemas_1 = requireDependentSchemas();
	const limitContains_1 = requireLimitContains();
	const next = [dependentRequired_1.default, dependentSchemas_1.default, limitContains_1.default];
	next$2.default = next;
	
	return next$2;
}

var unevaluated = {};

var unevaluatedProperties$1 = {};

var hasRequiredUnevaluatedProperties;

function requireUnevaluatedProperties () {
	if (hasRequiredUnevaluatedProperties) return unevaluatedProperties$1;
	hasRequiredUnevaluatedProperties = 1;
	Object.defineProperty(unevaluatedProperties$1, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	const names_1 = requireNames();
	const error = {
	    message: "must NOT have unevaluated properties",
	    params: ({ params }) => (0, codegen_1._) `{unevaluatedProperty: ${params.unevaluatedProperty}}`,
	};
	const def = {
	    keyword: "unevaluatedProperties",
	    type: "object",
	    schemaType: ["boolean", "object"],
	    trackErrors: true,
	    error,
	    code(cxt) {
	        const { gen, schema, data, errsCount, it } = cxt;
	        /* istanbul ignore if */
	        if (!errsCount)
	            throw new Error("ajv implementation error");
	        const { allErrors, props } = it;
	        if (props instanceof codegen_1.Name) {
	            gen.if((0, codegen_1._) `${props} !== true`, () => gen.forIn("key", data, (key) => gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(key))));
	        }
	        else if (props !== true) {
	            gen.forIn("key", data, (key) => props === undefined
	                ? unevaluatedPropCode(key)
	                : gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(key)));
	        }
	        it.props = true;
	        cxt.ok((0, codegen_1._) `${errsCount} === ${names_1.default.errors}`);
	        function unevaluatedPropCode(key) {
	            if (schema === false) {
	                cxt.setParams({ unevaluatedProperty: key });
	                cxt.error();
	                if (!allErrors)
	                    gen.break();
	                return;
	            }
	            if (!(0, util_1.alwaysValidSchema)(it, schema)) {
	                const valid = gen.name("valid");
	                cxt.subschema({
	                    keyword: "unevaluatedProperties",
	                    dataProp: key,
	                    dataPropType: util_1.Type.Str,
	                }, valid);
	                if (!allErrors)
	                    gen.if((0, codegen_1.not)(valid), () => gen.break());
	            }
	        }
	        function unevaluatedDynamic(evaluatedProps, key) {
	            return (0, codegen_1._) `!${evaluatedProps} || !${evaluatedProps}[${key}]`;
	        }
	        function unevaluatedStatic(evaluatedProps, key) {
	            const ps = [];
	            for (const p in evaluatedProps) {
	                if (evaluatedProps[p] === true)
	                    ps.push((0, codegen_1._) `${key} !== ${p}`);
	            }
	            return (0, codegen_1.and)(...ps);
	        }
	    },
	};
	unevaluatedProperties$1.default = def;
	
	return unevaluatedProperties$1;
}

var unevaluatedItems = {};

var hasRequiredUnevaluatedItems;

function requireUnevaluatedItems () {
	if (hasRequiredUnevaluatedItems) return unevaluatedItems;
	hasRequiredUnevaluatedItems = 1;
	Object.defineProperty(unevaluatedItems, "__esModule", { value: true });
	const codegen_1 = requireCodegen();
	const util_1 = requireUtil();
	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: "unevaluatedItems",
	    type: "array",
	    schemaType: ["boolean", "object"],
	    error,
	    code(cxt) {
	        const { gen, schema, data, it } = cxt;
	        const items = it.items || 0;
	        if (items === true)
	            return;
	        const len = gen.const("len", (0, codegen_1._) `${data}.length`);
	        if (schema === false) {
	            cxt.setParams({ len: items });
	            cxt.fail((0, codegen_1._) `${len} > ${items}`);
	        }
	        else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
	            const valid = gen.var("valid", (0, codegen_1._) `${len} <= ${items}`);
	            gen.if((0, codegen_1.not)(valid), () => validateItems(valid, items));
	            cxt.ok(valid);
	        }
	        it.items = true;
	        function validateItems(valid, from) {
	            gen.forRange("i", from, len, (i) => {
	                cxt.subschema({ keyword: "unevaluatedItems", dataProp: i, dataPropType: util_1.Type.Num }, valid);
	                if (!it.allErrors)
	                    gen.if((0, codegen_1.not)(valid), () => gen.break());
	            });
	        }
	    },
	};
	unevaluatedItems.default = def;
	
	return unevaluatedItems;
}

var hasRequiredUnevaluated;

function requireUnevaluated () {
	if (hasRequiredUnevaluated) return unevaluated;
	hasRequiredUnevaluated = 1;
	Object.defineProperty(unevaluated, "__esModule", { value: true });
	const unevaluatedProperties_1 = requireUnevaluatedProperties();
	const unevaluatedItems_1 = requireUnevaluatedItems();
	const unevaluated$1 = [unevaluatedProperties_1.default, unevaluatedItems_1.default];
	unevaluated.default = unevaluated$1;
	
	return unevaluated;
}

var metadata = {};

var hasRequiredMetadata;

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

var hasRequiredDraft2020;

function requireDraft2020 () {
	if (hasRequiredDraft2020) return draft2020;
	hasRequiredDraft2020 = 1;
	Object.defineProperty(draft2020, "__esModule", { value: true });
	const core_1 = requireCore$1();
	const validation_1 = requireValidation();
	const applicator_1 = requireApplicator();
	const dynamic_1 = requireDynamic();
	const next_1 = requireNext$2();
	const unevaluated_1 = requireUnevaluated();
	const format_1 = requireFormat();
	const metadata_1 = requireMetadata();
	const draft2020Vocabularies = [
	    dynamic_1.default,
	    core_1.default,
	    validation_1.default,
	    (0, applicator_1.default)(true),
	    format_1.default,
	    metadata_1.metadataVocabulary,
	    metadata_1.contentVocabulary,
	    next_1.default,
	    unevaluated_1.default,
	];
	draft2020.default = draft2020Vocabularies;
	
	return draft2020;
}

var jsonSchema202012 = {};

var $schema$b = "https://json-schema.org/draft/2020-12/schema";
var $id$8 = "https://json-schema.org/draft/2020-12/schema";
var $vocabulary$7 = {
	"https://json-schema.org/draft/2020-12/vocab/core": true,
	"https://json-schema.org/draft/2020-12/vocab/applicator": true,
	"https://json-schema.org/draft/2020-12/vocab/unevaluated": true,
	"https://json-schema.org/draft/2020-12/vocab/validation": true,
	"https://json-schema.org/draft/2020-12/vocab/meta-data": true,
	"https://json-schema.org/draft/2020-12/vocab/format-annotation": true,
	"https://json-schema.org/draft/2020-12/vocab/content": true
};
var $dynamicAnchor$7 = "meta";
var title$8 = "Core and Validation specifications meta-schema";
var allOf = [
	{
		$ref: "meta/core"
	},
	{
		$ref: "meta/applicator"
	},
	{
		$ref: "meta/unevaluated"
	},
	{
		$ref: "meta/validation"
	},
	{
		$ref: "meta/meta-data"
	},
	{
		$ref: "meta/format-annotation"
	},
	{
		$ref: "meta/content"
	}
];
var type$c = [
	"object",
	"boolean"
];
var $comment = "This meta-schema also defines keywords that have appeared in previous drafts in order to prevent incompatible extensions as they remain in common use.";
var properties$b = {
	definitions: {
		$comment: "\"definitions\" has been replaced by \"$defs\".",
		type: "object",
		additionalProperties: {
			$dynamicRef: "#meta"
		},
		deprecated: true,
		"default": {
		}
	},
	dependencies: {
		$comment: "\"dependencies\" has been split and replaced by \"dependentSchemas\" and \"dependentRequired\" in order to serve their differing semantics.",
		type: "object",
		additionalProperties: {
			anyOf: [
				{
					$dynamicRef: "#meta"
				},
				{
					$ref: "meta/validation#/$defs/stringArray"
				}
			]
		},
		deprecated: true,
		"default": {
		}
	},
	$recursiveAnchor: {
		$comment: "\"$recursiveAnchor\" has been replaced by \"$dynamicAnchor\".",
		$ref: "meta/core#/$defs/anchorString",
		deprecated: true
	},
	$recursiveRef: {
		$comment: "\"$recursiveRef\" has been replaced by \"$dynamicRef\".",
		$ref: "meta/core#/$defs/uriReferenceString",
		deprecated: true
	}
};
var require$$0$2 = {
	$schema: $schema$b,
	$id: $id$8,
	$vocabulary: $vocabulary$7,
	$dynamicAnchor: $dynamicAnchor$7,
	title: title$8,
	allOf: allOf,
	type: type$c,
	$comment: $comment,
	properties: properties$b
};

var $schema$a = "https://json-schema.org/draft/2020-12/schema";
var $id$7 = "https://json-schema.org/draft/2020-12/meta/applicator";
var $vocabulary$6 = {
	"https://json-schema.org/draft/2020-12/vocab/applicator": true
};
var $dynamicAnchor$6 = "meta";
var title$7 = "Applicator vocabulary meta-schema";
var type$b = [
	"object",
	"boolean"
];
var properties$a = {
	prefixItems: {
		$ref: "#/$defs/schemaArray"
	},
	items: {
		$dynamicRef: "#meta"
	},
	contains: {
		$dynamicRef: "#meta"
	},
	additionalProperties: {
		$dynamicRef: "#meta"
	},
	properties: {
		type: "object",
		additionalProperties: {
			$dynamicRef: "#meta"
		},
		"default": {
		}
	},
	patternProperties: {
		type: "object",
		additionalProperties: {
			$dynamicRef: "#meta"
		},
		propertyNames: {
			format: "regex"
		},
		"default": {
		}
	},
	dependentSchemas: {
		type: "object",
		additionalProperties: {
			$dynamicRef: "#meta"
		},
		"default": {
		}
	},
	propertyNames: {
		$dynamicRef: "#meta"
	},
	"if": {
		$dynamicRef: "#meta"
	},
	then: {
		$dynamicRef: "#meta"
	},
	"else": {
		$dynamicRef: "#meta"
	},
	allOf: {
		$ref: "#/$defs/schemaArray"
	},
	anyOf: {
		$ref: "#/$defs/schemaArray"
	},
	oneOf: {
		$ref: "#/$defs/schemaArray"
	},
	not: {
		$dynamicRef: "#meta"
	}
};
var $defs$3 = {
	schemaArray: {
		type: "array",
		minItems: 1,
		items: {
			$dynamicRef: "#meta"
		}
	}
};
var require$$1$1 = {
	$schema: $schema$a,
	$id: $id$7,
	$vocabulary: $vocabulary$6,
	$dynamicAnchor: $dynamicAnchor$6,
	title: title$7,
	type: type$b,
	properties: properties$a,
	$defs: $defs$3
};

var $schema$9 = "https://json-schema.org/draft/2020-12/schema";
var $id$6 = "https://json-schema.org/draft/2020-12/meta/unevaluated";
var $vocabulary$5 = {
	"https://json-schema.org/draft/2020-12/vocab/unevaluated": true
};
var $dynamicAnchor$5 = "meta";
var title$6 = "Unevaluated applicator vocabulary meta-schema";
var type$a = [
	"object",
	"boolean"
];
var properties$9 = {
	unevaluatedItems: {
		$dynamicRef: "#meta"
	},
	unevaluatedProperties: {
		$dynamicRef: "#meta"
	}
};
var require$$2$1 = {
	$schema: $schema$9,
	$id: $id$6,
	$vocabulary: $vocabulary$5,
	$dynamicAnchor: $dynamicAnchor$5,
	title: title$6,
	type: type$a,
	properties: properties$9
};

var $schema$8 = "https://json-schema.org/draft/2020-12/schema";
var $id$5 = "https://json-schema.org/draft/2020-12/meta/content";
var $vocabulary$4 = {
	"https://json-schema.org/draft/2020-12/vocab/content": true
};
var $dynamicAnchor$4 = "meta";
var title$5 = "Content vocabulary meta-schema";
var type$9 = [
	"object",
	"boolean"
];
var properties$8 = {
	contentEncoding: {
		type: "string"
	},
	contentMediaType: {
		type: "string"
	},
	contentSchema: {
		$dynamicRef: "#meta"
	}
};
var require$$3$1 = {
	$schema: $schema$8,
	$id: $id$5,
	$vocabulary: $vocabulary$4,
	$dynamicAnchor: $dynamicAnchor$4,
	title: title$5,
	type: type$9,
	properties: properties$8
};

var $schema$7 = "https://json-schema.org/draft/2020-12/schema";
var $id$4 = "https://json-schema.org/draft/2020-12/meta/core";
var $vocabulary$3 = {
	"https://json-schema.org/draft/2020-12/vocab/core": true
};
var $dynamicAnchor$3 = "meta";
var title$4 = "Core vocabulary meta-schema";
var type$8 = [
	"object",
	"boolean"
];
var properties$7 = {
	$id: {
		$ref: "#/$defs/uriReferenceString",
		$comment: "Non-empty fragments not allowed.",
		pattern: "^[^#]*#?$"
	},
	$schema: {
		$ref: "#/$defs/uriString"
	},
	$ref: {
		$ref: "#/$defs/uriReferenceString"
	},
	$anchor: {
		$ref: "#/$defs/anchorString"
	},
	$dynamicRef: {
		$ref: "#/$defs/uriReferenceString"
	},
	$dynamicAnchor: {
		$ref: "#/$defs/anchorString"
	},
	$vocabulary: {
		type: "object",
		propertyNames: {
			$ref: "#/$defs/uriString"
		},
		additionalProperties: {
			type: "boolean"
		}
	},
	$comment: {
		type: "string"
	},
	$defs: {
		type: "object",
		additionalProperties: {
			$dynamicRef: "#meta"
		}
	}
};
var $defs$2 = {
	anchorString: {
		type: "string",
		pattern: "^[A-Za-z_][-A-Za-z0-9._]*$"
	},
	uriString: {
		type: "string",
		format: "uri"
	},
	uriReferenceString: {
		type: "string",
		format: "uri-reference"
	}
};
var require$$4 = {
	$schema: $schema$7,
	$id: $id$4,
	$vocabulary: $vocabulary$3,
	$dynamicAnchor: $dynamicAnchor$3,
	title: title$4,
	type: type$8,
	properties: properties$7,
	$defs: $defs$2
};

var $schema$6 = "https://json-schema.org/draft/2020-12/schema";
var $id$3 = "https://json-schema.org/draft/2020-12/meta/format-annotation";
var $vocabulary$2 = {
	"https://json-schema.org/draft/2020-12/vocab/format-annotation": true
};
var $dynamicAnchor$2 = "meta";
var title$3 = "Format vocabulary meta-schema for annotation results";
var type$7 = [
	"object",
	"boolean"
];
var properties$6 = {
	format: {
		type: "string"
	}
};
var require$$5 = {
	$schema: $schema$6,
	$id: $id$3,
	$vocabulary: $vocabulary$2,
	$dynamicAnchor: $dynamicAnchor$2,
	title: title$3,
	type: type$7,
	properties: properties$6
};

var $schema$5 = "https://json-schema.org/draft/2020-12/schema";
var $id$2 = "https://json-schema.org/draft/2020-12/meta/meta-data";
var $vocabulary$1 = {
	"https://json-schema.org/draft/2020-12/vocab/meta-data": true
};
var $dynamicAnchor$1 = "meta";
var title$2 = "Meta-data vocabulary meta-schema";
var type$6 = [
	"object",
	"boolean"
];
var properties$5 = {
	title: {
		type: "string"
	},
	description: {
		type: "string"
	},
	"default": true,
	deprecated: {
		type: "boolean",
		"default": false
	},
	readOnly: {
		type: "boolean",
		"default": false
	},
	writeOnly: {
		type: "boolean",
		"default": false
	},
	examples: {
		type: "array",
		items: true
	}
};
var require$$6 = {
	$schema: $schema$5,
	$id: $id$2,
	$vocabulary: $vocabulary$1,
	$dynamicAnchor: $dynamicAnchor$1,
	title: title$2,
	type: type$6,
	properties: properties$5
};

var $schema$4 = "https://json-schema.org/draft/2020-12/schema";
var $id$1 = "https://json-schema.org/draft/2020-12/meta/validation";
var $vocabulary = {
	"https://json-schema.org/draft/2020-12/vocab/validation": true
};
var $dynamicAnchor = "meta";
var title$1 = "Validation vocabulary meta-schema";
var type$5 = [
	"object",
	"boolean"
];
var properties$4 = {
	type: {
		anyOf: [
			{
				$ref: "#/$defs/simpleTypes"
			},
			{
				type: "array",
				items: {
					$ref: "#/$defs/simpleTypes"
				},
				minItems: 1,
				uniqueItems: true
			}
		]
	},
	"const": true,
	"enum": {
		type: "array",
		items: true
	},
	multipleOf: {
		type: "number",
		exclusiveMinimum: 0
	},
	maximum: {
		type: "number"
	},
	exclusiveMaximum: {
		type: "number"
	},
	minimum: {
		type: "number"
	},
	exclusiveMinimum: {
		type: "number"
	},
	maxLength: {
		$ref: "#/$defs/nonNegativeInteger"
	},
	minLength: {
		$ref: "#/$defs/nonNegativeIntegerDefault0"
	},
	pattern: {
		type: "string",
		format: "regex"
	},
	maxItems: {
		$ref: "#/$defs/nonNegativeInteger"
	},
	minItems: {
		$ref: "#/$defs/nonNegativeIntegerDefault0"
	},
	uniqueItems: {
		type: "boolean",
		"default": false
	},
	maxContains: {
		$ref: "#/$defs/nonNegativeInteger"
	},
	minContains: {
		$ref: "#/$defs/nonNegativeInteger",
		"default": 1
	},
	maxProperties: {
		$ref: "#/$defs/nonNegativeInteger"
	},
	minProperties: {
		$ref: "#/$defs/nonNegativeIntegerDefault0"
	},
	required: {
		$ref: "#/$defs/stringArray"
	},
	dependentRequired: {
		type: "object",
		additionalProperties: {
			$ref: "#/$defs/stringArray"
		}
	}
};
var $defs$1 = {
	nonNegativeInteger: {
		type: "integer",
		minimum: 0
	},
	nonNegativeIntegerDefault0: {
		$ref: "#/$defs/nonNegativeInteger",
		"default": 0
	},
	simpleTypes: {
		"enum": [
			"array",
			"boolean",
			"integer",
			"null",
			"number",
			"object",
			"string"
		]
	},
	stringArray: {
		type: "array",
		items: {
			type: "string"
		},
		uniqueItems: true,
		"default": [
		]
	}
};
var require$$7 = {
	$schema: $schema$4,
	$id: $id$1,
	$vocabulary: $vocabulary,
	$dynamicAnchor: $dynamicAnchor,
	title: title$1,
	type: type$5,
	properties: properties$4,
	$defs: $defs$1
};

var hasRequiredJsonSchema202012;

function requireJsonSchema202012 () {
	if (hasRequiredJsonSchema202012) return jsonSchema202012;
	hasRequiredJsonSchema202012 = 1;
	Object.defineProperty(jsonSchema202012, "__esModule", { value: true });
	const metaSchema = require$$0$2;
	const applicator = require$$1$1;
	const unevaluated = require$$2$1;
	const content = require$$3$1;
	const core = require$$4;
	const format = require$$5;
	const metadata = require$$6;
	const validation = require$$7;
	const META_SUPPORT_DATA = ["/properties"];
	function addMetaSchema2020($data) {
	    [
	        metaSchema,
	        applicator,
	        unevaluated,
	        content,
	        core,
	        with$data(this, format),
	        metadata,
	        with$data(this, validation),
	    ].forEach((sch) => this.addMetaSchema(sch, undefined, false));
	    return this;
	    function with$data(ajv, sch) {
	        return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch;
	    }
	}
	jsonSchema202012.default = addMetaSchema2020;
	
	return jsonSchema202012;
}

var hasRequired_2020;

function require_2020 () {
	if (hasRequired_2020) return _2020.exports;
	hasRequired_2020 = 1;
	(function (module, exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv2020 = undefined;
		const core_1 = requireCore$3();
		const draft2020_1 = requireDraft2020();
		const discriminator_1 = requireDiscriminator();
		const json_schema_2020_12_1 = requireJsonSchema202012();
		const META_SCHEMA_ID = "https://json-schema.org/draft/2020-12/schema";
		class Ajv2020 extends core_1.default {
		    constructor(opts = {}) {
		        super({
		            ...opts,
		            dynamicRef: true,
		            next: true,
		            unevaluated: true,
		        });
		    }
		    _addVocabularies() {
		        super._addVocabularies();
		        draft2020_1.default.forEach((v) => this.addVocabulary(v));
		        if (this.opts.discriminator)
		            this.addKeyword(discriminator_1.default);
		    }
		    _addDefaultMetaSchema() {
		        super._addDefaultMetaSchema();
		        const { $data, meta } = this.opts;
		        if (!meta)
		            return;
		        json_schema_2020_12_1.default.call(this, $data);
		        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.Ajv2020 = Ajv2020;
		module.exports = exports = Ajv2020;
		module.exports.Ajv2020 = Ajv2020;
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.default = Ajv2020;
		var validate_1 = requireValidate();
		Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function () { return validate_1.KeywordCxt; } });
		var codegen_1 = requireCodegen();
		Object.defineProperty(exports, "_", { enumerable: true, get: function () { return codegen_1._; } });
		Object.defineProperty(exports, "str", { enumerable: true, get: function () { return codegen_1.str; } });
		Object.defineProperty(exports, "stringify", { enumerable: true, get: function () { return codegen_1.stringify; } });
		Object.defineProperty(exports, "nil", { enumerable: true, get: function () { return codegen_1.nil; } });
		Object.defineProperty(exports, "Name", { enumerable: true, get: function () { return codegen_1.Name; } });
		Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function () { return codegen_1.CodeGen; } });
		var validation_error_1 = requireValidation_error();
		Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return validation_error_1.default; } });
		var ref_error_1 = requireRef_error();
		Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function () { return ref_error_1.default; } });
		
	} (_2020, _2020.exports));
	return _2020.exports;
}

var lib$3 = {exports: {}};

var id$2 = "https://raw.githubusercontent.com/OAI/OpenAPI-Specification/master/schemas/v1.2/apiDeclaration.json#";
var $schema$3 = "http://json-schema.org/draft-04/schema#";
var type$4 = "object";
var required$3 = [
	"swaggerVersion",
	"basePath",
	"apis"
];
var properties$3 = {
	swaggerVersion: {
		"enum": [
			"1.2"
		]
	},
	apiVersion: {
		type: "string"
	},
	basePath: {
		type: "string",
		format: "uri",
		pattern: "^https?://"
	},
	resourcePath: {
		type: "string",
		format: "uri",
		pattern: "^/"
	},
	apis: {
		type: "array",
		items: {
			$ref: "#/definitions/apiObject"
		}
	},
	models: {
		type: "object",
		additionalProperties: {
			$ref: "modelsObject.json#"
		}
	},
	produces: {
		$ref: "#/definitions/mimeTypeArray"
	},
	consumes: {
		$ref: "#/definitions/mimeTypeArray"
	},
	authorizations: {
		$ref: "authorizationObject.json#"
	}
};
var additionalProperties$2 = false;
var definitions$2 = {
	apiObject: {
		type: "object",
		required: [
			"path",
			"operations"
		],
		properties: {
			path: {
				type: "string",
				format: "uri-template",
				pattern: "^/"
			},
			description: {
				type: "string"
			},
			operations: {
				type: "array",
				items: {
					$ref: "operationObject.json#"
				}
			}
		},
		additionalProperties: false
	},
	mimeTypeArray: {
		type: "array",
		items: {
			type: "string",
			format: "mime-type"
		},
		uniqueItems: true
	}
};
var require$$0$1 = {
	id: id$2,
	$schema: $schema$3,
	type: type$4,
	required: required$3,
	properties: properties$3,
	additionalProperties: additionalProperties$2,
	definitions: definitions$2
};

var title = "A JSON Schema for Swagger 2.0 API.";
var id$1 = "http://swagger.io/v2/schema.json#";
var $schema$2 = "http://json-schema.org/draft-04/schema#";
var type$3 = "object";
var required$2 = [
	"swagger",
	"info",
	"paths"
];
var additionalProperties$1 = false;
var patternProperties$1 = {
	"^x-": {
		$ref: "#/definitions/vendorExtension"
	}
};
var properties$2 = {
	swagger: {
		type: "string",
		"enum": [
			"2.0"
		],
		description: "The Swagger version of this document."
	},
	info: {
		$ref: "#/definitions/info"
	},
	host: {
		type: "string",
		pattern: "^[^{}/ :\\\\]+(?::\\d+)?$",
		description: "The host (name or ip) of the API. Example: 'swagger.io'"
	},
	basePath: {
		type: "string",
		pattern: "^/",
		description: "The base path to the API. Example: '/api'."
	},
	schemes: {
		$ref: "#/definitions/schemesList"
	},
	consumes: {
		description: "A list of MIME types accepted by the API.",
		allOf: [
			{
				$ref: "#/definitions/mediaTypeList"
			}
		]
	},
	produces: {
		description: "A list of MIME types the API can produce.",
		allOf: [
			{
				$ref: "#/definitions/mediaTypeList"
			}
		]
	},
	paths: {
		$ref: "#/definitions/paths"
	},
	definitions: {
		$ref: "#/definitions/definitions"
	},
	parameters: {
		$ref: "#/definitions/parameterDefinitions"
	},
	responses: {
		$ref: "#/definitions/responseDefinitions"
	},
	security: {
		$ref: "#/definitions/security"
	},
	securityDefinitions: {
		$ref: "#/definitions/securityDefinitions"
	},
	tags: {
		type: "array",
		items: {
			$ref: "#/definitions/tag"
		},
		uniqueItems: true
	},
	externalDocs: {
		$ref: "#/definitions/externalDocs"
	}
};
var definitions$1 = {
	info: {
		type: "object",
		description: "General information about the API.",
		required: [
			"version",
			"title"
		],
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			title: {
				type: "string",
				description: "A unique and precise title of the API."
			},
			version: {
				type: "string",
				description: "A semantic version number of the API."
			},
			description: {
				type: "string",
				description: "A longer description of the API. Should be different from the title.  GitHub Flavored Markdown is allowed."
			},
			termsOfService: {
				type: "string",
				description: "The terms of service for the API."
			},
			contact: {
				$ref: "#/definitions/contact"
			},
			license: {
				$ref: "#/definitions/license"
			}
		}
	},
	contact: {
		type: "object",
		description: "Contact information for the owners of the API.",
		additionalProperties: false,
		properties: {
			name: {
				type: "string",
				description: "The identifying name of the contact person/organization."
			},
			url: {
				type: "string",
				description: "The URL pointing to the contact information.",
				format: "uri"
			},
			email: {
				type: "string",
				description: "The email address of the contact person/organization.",
				format: "email"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	license: {
		type: "object",
		required: [
			"name"
		],
		additionalProperties: false,
		properties: {
			name: {
				type: "string",
				description: "The name of the license type. It's encouraged to use an OSI compatible license."
			},
			url: {
				type: "string",
				description: "The URL pointing to the license.",
				format: "uri"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	paths: {
		type: "object",
		description: "Relative paths to the individual endpoints. They must be relative to the 'basePath'.",
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			},
			"^/": {
				$ref: "#/definitions/pathItem"
			}
		},
		additionalProperties: false
	},
	definitions: {
		type: "object",
		additionalProperties: {
			$ref: "#/definitions/schema"
		},
		description: "One or more JSON objects describing the schemas being consumed and produced by the API."
	},
	parameterDefinitions: {
		type: "object",
		additionalProperties: {
			$ref: "#/definitions/parameter"
		},
		description: "One or more JSON representations for parameters"
	},
	responseDefinitions: {
		type: "object",
		additionalProperties: {
			$ref: "#/definitions/response"
		},
		description: "One or more JSON representations for responses"
	},
	externalDocs: {
		type: "object",
		additionalProperties: false,
		description: "information about external documentation",
		required: [
			"url"
		],
		properties: {
			description: {
				type: "string"
			},
			url: {
				type: "string",
				format: "uri"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	examples: {
		type: "object",
		additionalProperties: true
	},
	mimeType: {
		type: "string",
		description: "The MIME type of the HTTP message."
	},
	operation: {
		type: "object",
		required: [
			"responses"
		],
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			tags: {
				type: "array",
				items: {
					type: "string"
				},
				uniqueItems: true
			},
			summary: {
				type: "string",
				description: "A brief summary of the operation."
			},
			description: {
				type: "string",
				description: "A longer description of the operation, GitHub Flavored Markdown is allowed."
			},
			externalDocs: {
				$ref: "#/definitions/externalDocs"
			},
			operationId: {
				type: "string",
				description: "A unique identifier of the operation."
			},
			produces: {
				description: "A list of MIME types the API can produce.",
				allOf: [
					{
						$ref: "#/definitions/mediaTypeList"
					}
				]
			},
			consumes: {
				description: "A list of MIME types the API can consume.",
				allOf: [
					{
						$ref: "#/definitions/mediaTypeList"
					}
				]
			},
			parameters: {
				$ref: "#/definitions/parametersList"
			},
			responses: {
				$ref: "#/definitions/responses"
			},
			schemes: {
				$ref: "#/definitions/schemesList"
			},
			deprecated: {
				type: "boolean",
				"default": false
			},
			security: {
				$ref: "#/definitions/security"
			}
		}
	},
	pathItem: {
		type: "object",
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			$ref: {
				type: "string"
			},
			get: {
				$ref: "#/definitions/operation"
			},
			put: {
				$ref: "#/definitions/operation"
			},
			post: {
				$ref: "#/definitions/operation"
			},
			"delete": {
				$ref: "#/definitions/operation"
			},
			options: {
				$ref: "#/definitions/operation"
			},
			head: {
				$ref: "#/definitions/operation"
			},
			patch: {
				$ref: "#/definitions/operation"
			},
			parameters: {
				$ref: "#/definitions/parametersList"
			}
		}
	},
	responses: {
		type: "object",
		description: "Response objects names can either be any valid HTTP status code or 'default'.",
		minProperties: 1,
		additionalProperties: false,
		patternProperties: {
			"^([0-9]{3})$|^(default)$": {
				$ref: "#/definitions/responseValue"
			},
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		not: {
			type: "object",
			additionalProperties: false,
			patternProperties: {
				"^x-": {
					$ref: "#/definitions/vendorExtension"
				}
			}
		}
	},
	responseValue: {
		oneOf: [
			{
				$ref: "#/definitions/response"
			},
			{
				$ref: "#/definitions/jsonReference"
			}
		]
	},
	response: {
		type: "object",
		required: [
			"description"
		],
		properties: {
			description: {
				type: "string"
			},
			schema: {
				oneOf: [
					{
						$ref: "#/definitions/schema"
					},
					{
						$ref: "#/definitions/fileSchema"
					}
				]
			},
			headers: {
				$ref: "#/definitions/headers"
			},
			examples: {
				$ref: "#/definitions/examples"
			}
		},
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	headers: {
		type: "object",
		additionalProperties: {
			$ref: "#/definitions/header"
		}
	},
	header: {
		type: "object",
		additionalProperties: false,
		required: [
			"type"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"string",
					"number",
					"integer",
					"boolean",
					"array"
				]
			},
			format: {
				type: "string"
			},
			items: {
				$ref: "#/definitions/primitivesItems"
			},
			collectionFormat: {
				$ref: "#/definitions/collectionFormat"
			},
			"default": {
				$ref: "#/definitions/default"
			},
			maximum: {
				$ref: "#/definitions/maximum"
			},
			exclusiveMaximum: {
				$ref: "#/definitions/exclusiveMaximum"
			},
			minimum: {
				$ref: "#/definitions/minimum"
			},
			exclusiveMinimum: {
				$ref: "#/definitions/exclusiveMinimum"
			},
			maxLength: {
				$ref: "#/definitions/maxLength"
			},
			minLength: {
				$ref: "#/definitions/minLength"
			},
			pattern: {
				$ref: "#/definitions/pattern"
			},
			maxItems: {
				$ref: "#/definitions/maxItems"
			},
			minItems: {
				$ref: "#/definitions/minItems"
			},
			uniqueItems: {
				$ref: "#/definitions/uniqueItems"
			},
			"enum": {
				$ref: "#/definitions/enum"
			},
			multipleOf: {
				$ref: "#/definitions/multipleOf"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	vendorExtension: {
		description: "Any property starting with x- is valid.",
		additionalProperties: true,
		additionalItems: true
	},
	bodyParameter: {
		type: "object",
		required: [
			"name",
			"in",
			"schema"
		],
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			description: {
				type: "string",
				description: "A brief description of the parameter. This could contain examples of use.  GitHub Flavored Markdown is allowed."
			},
			name: {
				type: "string",
				description: "The name of the parameter."
			},
			"in": {
				type: "string",
				description: "Determines the location of the parameter.",
				"enum": [
					"body"
				]
			},
			required: {
				type: "boolean",
				description: "Determines whether or not this parameter is required or optional.",
				"default": false
			},
			schema: {
				$ref: "#/definitions/schema"
			}
		},
		additionalProperties: false
	},
	headerParameterSubSchema: {
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			required: {
				type: "boolean",
				description: "Determines whether or not this parameter is required or optional.",
				"default": false
			},
			"in": {
				type: "string",
				description: "Determines the location of the parameter.",
				"enum": [
					"header"
				]
			},
			description: {
				type: "string",
				description: "A brief description of the parameter. This could contain examples of use.  GitHub Flavored Markdown is allowed."
			},
			name: {
				type: "string",
				description: "The name of the parameter."
			},
			type: {
				type: "string",
				"enum": [
					"string",
					"number",
					"boolean",
					"integer",
					"array"
				]
			},
			format: {
				type: "string"
			},
			items: {
				$ref: "#/definitions/primitivesItems"
			},
			collectionFormat: {
				$ref: "#/definitions/collectionFormat"
			},
			"default": {
				$ref: "#/definitions/default"
			},
			maximum: {
				$ref: "#/definitions/maximum"
			},
			exclusiveMaximum: {
				$ref: "#/definitions/exclusiveMaximum"
			},
			minimum: {
				$ref: "#/definitions/minimum"
			},
			exclusiveMinimum: {
				$ref: "#/definitions/exclusiveMinimum"
			},
			maxLength: {
				$ref: "#/definitions/maxLength"
			},
			minLength: {
				$ref: "#/definitions/minLength"
			},
			pattern: {
				$ref: "#/definitions/pattern"
			},
			maxItems: {
				$ref: "#/definitions/maxItems"
			},
			minItems: {
				$ref: "#/definitions/minItems"
			},
			uniqueItems: {
				$ref: "#/definitions/uniqueItems"
			},
			"enum": {
				$ref: "#/definitions/enum"
			},
			multipleOf: {
				$ref: "#/definitions/multipleOf"
			}
		}
	},
	queryParameterSubSchema: {
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			required: {
				type: "boolean",
				description: "Determines whether or not this parameter is required or optional.",
				"default": false
			},
			"in": {
				type: "string",
				description: "Determines the location of the parameter.",
				"enum": [
					"query"
				]
			},
			description: {
				type: "string",
				description: "A brief description of the parameter. This could contain examples of use.  GitHub Flavored Markdown is allowed."
			},
			name: {
				type: "string",
				description: "The name of the parameter."
			},
			allowEmptyValue: {
				type: "boolean",
				"default": false,
				description: "allows sending a parameter by name only or with an empty value."
			},
			type: {
				type: "string",
				"enum": [
					"string",
					"number",
					"boolean",
					"integer",
					"array"
				]
			},
			format: {
				type: "string"
			},
			items: {
				$ref: "#/definitions/primitivesItems"
			},
			collectionFormat: {
				$ref: "#/definitions/collectionFormatWithMulti"
			},
			"default": {
				$ref: "#/definitions/default"
			},
			maximum: {
				$ref: "#/definitions/maximum"
			},
			exclusiveMaximum: {
				$ref: "#/definitions/exclusiveMaximum"
			},
			minimum: {
				$ref: "#/definitions/minimum"
			},
			exclusiveMinimum: {
				$ref: "#/definitions/exclusiveMinimum"
			},
			maxLength: {
				$ref: "#/definitions/maxLength"
			},
			minLength: {
				$ref: "#/definitions/minLength"
			},
			pattern: {
				$ref: "#/definitions/pattern"
			},
			maxItems: {
				$ref: "#/definitions/maxItems"
			},
			minItems: {
				$ref: "#/definitions/minItems"
			},
			uniqueItems: {
				$ref: "#/definitions/uniqueItems"
			},
			"enum": {
				$ref: "#/definitions/enum"
			},
			multipleOf: {
				$ref: "#/definitions/multipleOf"
			}
		}
	},
	formDataParameterSubSchema: {
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			required: {
				type: "boolean",
				description: "Determines whether or not this parameter is required or optional.",
				"default": false
			},
			"in": {
				type: "string",
				description: "Determines the location of the parameter.",
				"enum": [
					"formData"
				]
			},
			description: {
				type: "string",
				description: "A brief description of the parameter. This could contain examples of use.  GitHub Flavored Markdown is allowed."
			},
			name: {
				type: "string",
				description: "The name of the parameter."
			},
			allowEmptyValue: {
				type: "boolean",
				"default": false,
				description: "allows sending a parameter by name only or with an empty value."
			},
			type: {
				type: "string",
				"enum": [
					"string",
					"number",
					"boolean",
					"integer",
					"array",
					"file"
				]
			},
			format: {
				type: "string"
			},
			items: {
				$ref: "#/definitions/primitivesItems"
			},
			collectionFormat: {
				$ref: "#/definitions/collectionFormatWithMulti"
			},
			"default": {
				$ref: "#/definitions/default"
			},
			maximum: {
				$ref: "#/definitions/maximum"
			},
			exclusiveMaximum: {
				$ref: "#/definitions/exclusiveMaximum"
			},
			minimum: {
				$ref: "#/definitions/minimum"
			},
			exclusiveMinimum: {
				$ref: "#/definitions/exclusiveMinimum"
			},
			maxLength: {
				$ref: "#/definitions/maxLength"
			},
			minLength: {
				$ref: "#/definitions/minLength"
			},
			pattern: {
				$ref: "#/definitions/pattern"
			},
			maxItems: {
				$ref: "#/definitions/maxItems"
			},
			minItems: {
				$ref: "#/definitions/minItems"
			},
			uniqueItems: {
				$ref: "#/definitions/uniqueItems"
			},
			"enum": {
				$ref: "#/definitions/enum"
			},
			multipleOf: {
				$ref: "#/definitions/multipleOf"
			}
		}
	},
	pathParameterSubSchema: {
		additionalProperties: false,
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		required: [
			"required"
		],
		properties: {
			required: {
				type: "boolean",
				"enum": [
					true
				],
				description: "Determines whether or not this parameter is required or optional."
			},
			"in": {
				type: "string",
				description: "Determines the location of the parameter.",
				"enum": [
					"path"
				]
			},
			description: {
				type: "string",
				description: "A brief description of the parameter. This could contain examples of use.  GitHub Flavored Markdown is allowed."
			},
			name: {
				type: "string",
				description: "The name of the parameter."
			},
			type: {
				type: "string",
				"enum": [
					"string",
					"number",
					"boolean",
					"integer",
					"array"
				]
			},
			format: {
				type: "string"
			},
			items: {
				$ref: "#/definitions/primitivesItems"
			},
			collectionFormat: {
				$ref: "#/definitions/collectionFormat"
			},
			"default": {
				$ref: "#/definitions/default"
			},
			maximum: {
				$ref: "#/definitions/maximum"
			},
			exclusiveMaximum: {
				$ref: "#/definitions/exclusiveMaximum"
			},
			minimum: {
				$ref: "#/definitions/minimum"
			},
			exclusiveMinimum: {
				$ref: "#/definitions/exclusiveMinimum"
			},
			maxLength: {
				$ref: "#/definitions/maxLength"
			},
			minLength: {
				$ref: "#/definitions/minLength"
			},
			pattern: {
				$ref: "#/definitions/pattern"
			},
			maxItems: {
				$ref: "#/definitions/maxItems"
			},
			minItems: {
				$ref: "#/definitions/minItems"
			},
			uniqueItems: {
				$ref: "#/definitions/uniqueItems"
			},
			"enum": {
				$ref: "#/definitions/enum"
			},
			multipleOf: {
				$ref: "#/definitions/multipleOf"
			}
		}
	},
	nonBodyParameter: {
		type: "object",
		required: [
			"name",
			"in",
			"type"
		],
		oneOf: [
			{
				$ref: "#/definitions/headerParameterSubSchema"
			},
			{
				$ref: "#/definitions/formDataParameterSubSchema"
			},
			{
				$ref: "#/definitions/queryParameterSubSchema"
			},
			{
				$ref: "#/definitions/pathParameterSubSchema"
			}
		]
	},
	parameter: {
		oneOf: [
			{
				$ref: "#/definitions/bodyParameter"
			},
			{
				$ref: "#/definitions/nonBodyParameter"
			}
		]
	},
	schema: {
		type: "object",
		description: "A deterministic version of a JSON Schema object.",
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		properties: {
			$ref: {
				type: "string"
			},
			format: {
				type: "string"
			},
			title: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/title"
			},
			description: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/description"
			},
			"default": {
				$ref: "http://json-schema.org/draft-04/schema#/properties/default"
			},
			multipleOf: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/multipleOf"
			},
			maximum: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/maximum"
			},
			exclusiveMaximum: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum"
			},
			minimum: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/minimum"
			},
			exclusiveMinimum: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum"
			},
			maxLength: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
			},
			minLength: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
			},
			pattern: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/pattern"
			},
			maxItems: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
			},
			minItems: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
			},
			uniqueItems: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/uniqueItems"
			},
			maxProperties: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
			},
			minProperties: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
			},
			required: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/stringArray"
			},
			"enum": {
				$ref: "http://json-schema.org/draft-04/schema#/properties/enum"
			},
			additionalProperties: {
				anyOf: [
					{
						$ref: "#/definitions/schema"
					},
					{
						type: "boolean"
					}
				],
				"default": {
				}
			},
			type: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/type"
			},
			items: {
				anyOf: [
					{
						$ref: "#/definitions/schema"
					},
					{
						type: "array",
						minItems: 1,
						items: {
							$ref: "#/definitions/schema"
						}
					}
				],
				"default": {
				}
			},
			allOf: {
				type: "array",
				minItems: 1,
				items: {
					$ref: "#/definitions/schema"
				}
			},
			properties: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/schema"
				},
				"default": {
				}
			},
			discriminator: {
				type: "string"
			},
			readOnly: {
				type: "boolean",
				"default": false
			},
			xml: {
				$ref: "#/definitions/xml"
			},
			externalDocs: {
				$ref: "#/definitions/externalDocs"
			},
			example: {
			}
		},
		additionalProperties: false
	},
	fileSchema: {
		type: "object",
		description: "A deterministic version of a JSON Schema object.",
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		},
		required: [
			"type"
		],
		properties: {
			format: {
				type: "string"
			},
			title: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/title"
			},
			description: {
				$ref: "http://json-schema.org/draft-04/schema#/properties/description"
			},
			"default": {
				$ref: "http://json-schema.org/draft-04/schema#/properties/default"
			},
			required: {
				$ref: "http://json-schema.org/draft-04/schema#/definitions/stringArray"
			},
			type: {
				type: "string",
				"enum": [
					"file"
				]
			},
			readOnly: {
				type: "boolean",
				"default": false
			},
			externalDocs: {
				$ref: "#/definitions/externalDocs"
			},
			example: {
			}
		},
		additionalProperties: false
	},
	primitivesItems: {
		type: "object",
		additionalProperties: false,
		properties: {
			type: {
				type: "string",
				"enum": [
					"string",
					"number",
					"integer",
					"boolean",
					"array"
				]
			},
			format: {
				type: "string"
			},
			items: {
				$ref: "#/definitions/primitivesItems"
			},
			collectionFormat: {
				$ref: "#/definitions/collectionFormat"
			},
			"default": {
				$ref: "#/definitions/default"
			},
			maximum: {
				$ref: "#/definitions/maximum"
			},
			exclusiveMaximum: {
				$ref: "#/definitions/exclusiveMaximum"
			},
			minimum: {
				$ref: "#/definitions/minimum"
			},
			exclusiveMinimum: {
				$ref: "#/definitions/exclusiveMinimum"
			},
			maxLength: {
				$ref: "#/definitions/maxLength"
			},
			minLength: {
				$ref: "#/definitions/minLength"
			},
			pattern: {
				$ref: "#/definitions/pattern"
			},
			maxItems: {
				$ref: "#/definitions/maxItems"
			},
			minItems: {
				$ref: "#/definitions/minItems"
			},
			uniqueItems: {
				$ref: "#/definitions/uniqueItems"
			},
			"enum": {
				$ref: "#/definitions/enum"
			},
			multipleOf: {
				$ref: "#/definitions/multipleOf"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	security: {
		type: "array",
		items: {
			$ref: "#/definitions/securityRequirement"
		},
		uniqueItems: true
	},
	securityRequirement: {
		type: "object",
		additionalProperties: {
			type: "array",
			items: {
				type: "string"
			},
			uniqueItems: true
		}
	},
	xml: {
		type: "object",
		additionalProperties: false,
		properties: {
			name: {
				type: "string"
			},
			namespace: {
				type: "string"
			},
			prefix: {
				type: "string"
			},
			attribute: {
				type: "boolean",
				"default": false
			},
			wrapped: {
				type: "boolean",
				"default": false
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	tag: {
		type: "object",
		additionalProperties: false,
		required: [
			"name"
		],
		properties: {
			name: {
				type: "string"
			},
			description: {
				type: "string"
			},
			externalDocs: {
				$ref: "#/definitions/externalDocs"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	securityDefinitions: {
		type: "object",
		additionalProperties: {
			oneOf: [
				{
					$ref: "#/definitions/basicAuthenticationSecurity"
				},
				{
					$ref: "#/definitions/apiKeySecurity"
				},
				{
					$ref: "#/definitions/oauth2ImplicitSecurity"
				},
				{
					$ref: "#/definitions/oauth2PasswordSecurity"
				},
				{
					$ref: "#/definitions/oauth2ApplicationSecurity"
				},
				{
					$ref: "#/definitions/oauth2AccessCodeSecurity"
				}
			]
		}
	},
	basicAuthenticationSecurity: {
		type: "object",
		additionalProperties: false,
		required: [
			"type"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"basic"
				]
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	apiKeySecurity: {
		type: "object",
		additionalProperties: false,
		required: [
			"type",
			"name",
			"in"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"apiKey"
				]
			},
			name: {
				type: "string"
			},
			"in": {
				type: "string",
				"enum": [
					"header",
					"query"
				]
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	oauth2ImplicitSecurity: {
		type: "object",
		additionalProperties: false,
		required: [
			"type",
			"flow",
			"authorizationUrl"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"oauth2"
				]
			},
			flow: {
				type: "string",
				"enum": [
					"implicit"
				]
			},
			scopes: {
				$ref: "#/definitions/oauth2Scopes"
			},
			authorizationUrl: {
				type: "string",
				format: "uri"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	oauth2PasswordSecurity: {
		type: "object",
		additionalProperties: false,
		required: [
			"type",
			"flow",
			"tokenUrl"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"oauth2"
				]
			},
			flow: {
				type: "string",
				"enum": [
					"password"
				]
			},
			scopes: {
				$ref: "#/definitions/oauth2Scopes"
			},
			tokenUrl: {
				type: "string",
				format: "uri"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	oauth2ApplicationSecurity: {
		type: "object",
		additionalProperties: false,
		required: [
			"type",
			"flow",
			"tokenUrl"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"oauth2"
				]
			},
			flow: {
				type: "string",
				"enum": [
					"application"
				]
			},
			scopes: {
				$ref: "#/definitions/oauth2Scopes"
			},
			tokenUrl: {
				type: "string",
				format: "uri"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	oauth2AccessCodeSecurity: {
		type: "object",
		additionalProperties: false,
		required: [
			"type",
			"flow",
			"authorizationUrl",
			"tokenUrl"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"oauth2"
				]
			},
			flow: {
				type: "string",
				"enum": [
					"accessCode"
				]
			},
			scopes: {
				$ref: "#/definitions/oauth2Scopes"
			},
			authorizationUrl: {
				type: "string",
				format: "uri"
			},
			tokenUrl: {
				type: "string",
				format: "uri"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
				$ref: "#/definitions/vendorExtension"
			}
		}
	},
	oauth2Scopes: {
		type: "object",
		additionalProperties: {
			type: "string"
		}
	},
	mediaTypeList: {
		type: "array",
		items: {
			$ref: "#/definitions/mimeType"
		},
		uniqueItems: true
	},
	parametersList: {
		type: "array",
		description: "The parameters needed to send a valid API call.",
		additionalItems: false,
		items: {
			oneOf: [
				{
					$ref: "#/definitions/parameter"
				},
				{
					$ref: "#/definitions/jsonReference"
				}
			]
		},
		uniqueItems: true
	},
	schemesList: {
		type: "array",
		description: "The transfer protocol of the API.",
		items: {
			type: "string",
			"enum": [
				"http",
				"https",
				"ws",
				"wss"
			]
		},
		uniqueItems: true
	},
	collectionFormat: {
		type: "string",
		"enum": [
			"csv",
			"ssv",
			"tsv",
			"pipes"
		],
		"default": "csv"
	},
	collectionFormatWithMulti: {
		type: "string",
		"enum": [
			"csv",
			"ssv",
			"tsv",
			"pipes",
			"multi"
		],
		"default": "csv"
	},
	title: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/title"
	},
	description: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/description"
	},
	"default": {
		$ref: "http://json-schema.org/draft-04/schema#/properties/default"
	},
	multipleOf: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/multipleOf"
	},
	maximum: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/maximum"
	},
	exclusiveMaximum: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMaximum"
	},
	minimum: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/minimum"
	},
	exclusiveMinimum: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/exclusiveMinimum"
	},
	maxLength: {
		$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
	},
	minLength: {
		$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
	},
	pattern: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/pattern"
	},
	maxItems: {
		$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveInteger"
	},
	minItems: {
		$ref: "http://json-schema.org/draft-04/schema#/definitions/positiveIntegerDefault0"
	},
	uniqueItems: {
		$ref: "http://json-schema.org/draft-04/schema#/properties/uniqueItems"
	},
	"enum": {
		$ref: "http://json-schema.org/draft-04/schema#/properties/enum"
	},
	jsonReference: {
		type: "object",
		required: [
			"$ref"
		],
		additionalProperties: false,
		properties: {
			$ref: {
				type: "string"
			}
		}
	}
};
var require$$1 = {
	title: title,
	id: id$1,
	$schema: $schema$2,
	type: type$3,
	required: required$2,
	additionalProperties: additionalProperties$1,
	patternProperties: patternProperties$1,
	properties: properties$2,
	definitions: definitions$1
};

var id = "https://spec.openapis.org/oas/3.0/schema/2019-04-02";
var $schema$1 = "http://json-schema.org/draft-04/schema#";
var description = "Validation schema for OpenAPI Specification 3.0.X.";
var type$2 = "object";
var required$1 = [
	"openapi",
	"info",
	"paths"
];
var properties$1 = {
	openapi: {
		type: "string",
		pattern: "^3\\.0\\.\\d(-.+)?$"
	},
	info: {
		$ref: "#/definitions/Info"
	},
	externalDocs: {
		$ref: "#/definitions/ExternalDocumentation"
	},
	servers: {
		type: "array",
		items: {
			$ref: "#/definitions/Server"
		}
	},
	security: {
		type: "array",
		items: {
			$ref: "#/definitions/SecurityRequirement"
		}
	},
	tags: {
		type: "array",
		items: {
			$ref: "#/definitions/Tag"
		},
		uniqueItems: true
	},
	paths: {
		$ref: "#/definitions/Paths"
	},
	components: {
		$ref: "#/definitions/Components"
	}
};
var patternProperties = {
	"^x-": {
	}
};
var additionalProperties = false;
var definitions = {
	Reference: {
		type: "object",
		required: [
			"$ref"
		],
		patternProperties: {
			"^\\$ref$": {
				type: "string",
				format: "uri-reference"
			}
		}
	},
	Info: {
		type: "object",
		required: [
			"title",
			"version"
		],
		properties: {
			title: {
				type: "string"
			},
			description: {
				type: "string"
			},
			termsOfService: {
				type: "string",
				format: "uri-reference"
			},
			contact: {
				$ref: "#/definitions/Contact"
			},
			license: {
				$ref: "#/definitions/License"
			},
			version: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Contact: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			url: {
				type: "string",
				format: "uri-reference"
			},
			email: {
				type: "string",
				format: "email"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	License: {
		type: "object",
		required: [
			"name"
		],
		properties: {
			name: {
				type: "string"
			},
			url: {
				type: "string",
				format: "uri-reference"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Server: {
		type: "object",
		required: [
			"url"
		],
		properties: {
			url: {
				type: "string"
			},
			description: {
				type: "string"
			},
			variables: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/ServerVariable"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	ServerVariable: {
		type: "object",
		required: [
			"default"
		],
		properties: {
			"enum": {
				type: "array",
				items: {
					type: "string"
				}
			},
			"default": {
				type: "string"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Components: {
		type: "object",
		properties: {
			schemas: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Schema"
							},
							{
								$ref: "#/definitions/Reference"
							}
						]
					}
				}
			},
			responses: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/Response"
							}
						]
					}
				}
			},
			parameters: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/Parameter"
							}
						]
					}
				}
			},
			examples: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/Example"
							}
						]
					}
				}
			},
			requestBodies: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/RequestBody"
							}
						]
					}
				}
			},
			headers: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/Header"
							}
						]
					}
				}
			},
			securitySchemes: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/SecurityScheme"
							}
						]
					}
				}
			},
			links: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/Link"
							}
						]
					}
				}
			},
			callbacks: {
				type: "object",
				patternProperties: {
					"^[a-zA-Z0-9\\.\\-_]+$": {
						oneOf: [
							{
								$ref: "#/definitions/Reference"
							},
							{
								$ref: "#/definitions/Callback"
							}
						]
					}
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Schema: {
		type: "object",
		properties: {
			title: {
				type: "string"
			},
			multipleOf: {
				type: "number",
				minimum: 0,
				exclusiveMinimum: true
			},
			maximum: {
				type: "number"
			},
			exclusiveMaximum: {
				type: "boolean",
				"default": false
			},
			minimum: {
				type: "number"
			},
			exclusiveMinimum: {
				type: "boolean",
				"default": false
			},
			maxLength: {
				type: "integer",
				minimum: 0
			},
			minLength: {
				type: "integer",
				minimum: 0,
				"default": 0
			},
			pattern: {
				type: "string",
				format: "regex"
			},
			maxItems: {
				type: "integer",
				minimum: 0
			},
			minItems: {
				type: "integer",
				minimum: 0,
				"default": 0
			},
			uniqueItems: {
				type: "boolean",
				"default": false
			},
			maxProperties: {
				type: "integer",
				minimum: 0
			},
			minProperties: {
				type: "integer",
				minimum: 0,
				"default": 0
			},
			required: {
				type: "array",
				items: {
					type: "string"
				},
				minItems: 1,
				uniqueItems: true
			},
			"enum": {
				type: "array",
				items: {
				},
				minItems: 1,
				uniqueItems: false
			},
			type: {
				type: "string",
				"enum": [
					"array",
					"boolean",
					"integer",
					"number",
					"object",
					"string"
				]
			},
			not: {
				oneOf: [
					{
						$ref: "#/definitions/Schema"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			allOf: {
				type: "array",
				items: {
					oneOf: [
						{
							$ref: "#/definitions/Schema"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			oneOf: {
				type: "array",
				items: {
					oneOf: [
						{
							$ref: "#/definitions/Schema"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			anyOf: {
				type: "array",
				items: {
					oneOf: [
						{
							$ref: "#/definitions/Schema"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			items: {
				oneOf: [
					{
						$ref: "#/definitions/Schema"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			properties: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Schema"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			additionalProperties: {
				oneOf: [
					{
						$ref: "#/definitions/Schema"
					},
					{
						$ref: "#/definitions/Reference"
					},
					{
						type: "boolean"
					}
				],
				"default": true
			},
			description: {
				type: "string"
			},
			format: {
				type: "string"
			},
			"default": {
			},
			nullable: {
				type: "boolean",
				"default": false
			},
			discriminator: {
				$ref: "#/definitions/Discriminator"
			},
			readOnly: {
				type: "boolean",
				"default": false
			},
			writeOnly: {
				type: "boolean",
				"default": false
			},
			example: {
			},
			externalDocs: {
				$ref: "#/definitions/ExternalDocumentation"
			},
			deprecated: {
				type: "boolean",
				"default": false
			},
			xml: {
				$ref: "#/definitions/XML"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Discriminator: {
		type: "object",
		required: [
			"propertyName"
		],
		properties: {
			propertyName: {
				type: "string"
			},
			mapping: {
				type: "object",
				additionalProperties: {
					type: "string"
				}
			}
		}
	},
	XML: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			namespace: {
				type: "string",
				format: "uri"
			},
			prefix: {
				type: "string"
			},
			attribute: {
				type: "boolean",
				"default": false
			},
			wrapped: {
				type: "boolean",
				"default": false
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Response: {
		type: "object",
		required: [
			"description"
		],
		properties: {
			description: {
				type: "string"
			},
			headers: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Header"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			content: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/MediaType"
				}
			},
			links: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Link"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	MediaType: {
		type: "object",
		properties: {
			schema: {
				oneOf: [
					{
						$ref: "#/definitions/Schema"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			example: {
			},
			examples: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Example"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			encoding: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/Encoding"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false,
		allOf: [
			{
				$ref: "#/definitions/ExampleXORExamples"
			}
		]
	},
	Example: {
		type: "object",
		properties: {
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			value: {
			},
			externalValue: {
				type: "string",
				format: "uri-reference"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Header: {
		type: "object",
		properties: {
			description: {
				type: "string"
			},
			required: {
				type: "boolean",
				"default": false
			},
			deprecated: {
				type: "boolean",
				"default": false
			},
			allowEmptyValue: {
				type: "boolean",
				"default": false
			},
			style: {
				type: "string",
				"enum": [
					"simple"
				],
				"default": "simple"
			},
			explode: {
				type: "boolean"
			},
			allowReserved: {
				type: "boolean",
				"default": false
			},
			schema: {
				oneOf: [
					{
						$ref: "#/definitions/Schema"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			content: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/MediaType"
				},
				minProperties: 1,
				maxProperties: 1
			},
			example: {
			},
			examples: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Example"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false,
		allOf: [
			{
				$ref: "#/definitions/ExampleXORExamples"
			},
			{
				$ref: "#/definitions/SchemaXORContent"
			}
		]
	},
	Paths: {
		type: "object",
		patternProperties: {
			"^\\/": {
				$ref: "#/definitions/PathItem"
			},
			"^x-": {
			}
		},
		additionalProperties: false
	},
	PathItem: {
		type: "object",
		properties: {
			$ref: {
				type: "string"
			},
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			servers: {
				type: "array",
				items: {
					$ref: "#/definitions/Server"
				}
			},
			parameters: {
				type: "array",
				items: {
					oneOf: [
						{
							$ref: "#/definitions/Parameter"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				},
				uniqueItems: true
			}
		},
		patternProperties: {
			"^(get|put|post|delete|options|head|patch|trace)$": {
				$ref: "#/definitions/Operation"
			},
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Operation: {
		type: "object",
		required: [
			"responses"
		],
		properties: {
			tags: {
				type: "array",
				items: {
					type: "string"
				}
			},
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			externalDocs: {
				$ref: "#/definitions/ExternalDocumentation"
			},
			operationId: {
				type: "string"
			},
			parameters: {
				type: "array",
				items: {
					oneOf: [
						{
							$ref: "#/definitions/Parameter"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				},
				uniqueItems: true
			},
			requestBody: {
				oneOf: [
					{
						$ref: "#/definitions/RequestBody"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			responses: {
				$ref: "#/definitions/Responses"
			},
			callbacks: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Callback"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			},
			deprecated: {
				type: "boolean",
				"default": false
			},
			security: {
				type: "array",
				items: {
					$ref: "#/definitions/SecurityRequirement"
				}
			},
			servers: {
				type: "array",
				items: {
					$ref: "#/definitions/Server"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Responses: {
		type: "object",
		properties: {
			"default": {
				oneOf: [
					{
						$ref: "#/definitions/Response"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			}
		},
		patternProperties: {
			"^[1-5](?:\\d{2}|XX)$": {
				oneOf: [
					{
						$ref: "#/definitions/Response"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			"^x-": {
			}
		},
		minProperties: 1,
		additionalProperties: false
	},
	SecurityRequirement: {
		type: "object",
		additionalProperties: {
			type: "array",
			items: {
				type: "string"
			}
		}
	},
	Tag: {
		type: "object",
		required: [
			"name"
		],
		properties: {
			name: {
				type: "string"
			},
			description: {
				type: "string"
			},
			externalDocs: {
				$ref: "#/definitions/ExternalDocumentation"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	ExternalDocumentation: {
		type: "object",
		required: [
			"url"
		],
		properties: {
			description: {
				type: "string"
			},
			url: {
				type: "string",
				format: "uri-reference"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	ExampleXORExamples: {
		description: "Example and examples are mutually exclusive",
		not: {
			required: [
				"example",
				"examples"
			]
		}
	},
	SchemaXORContent: {
		description: "Schema and content are mutually exclusive, at least one is required",
		not: {
			required: [
				"schema",
				"content"
			]
		},
		oneOf: [
			{
				required: [
					"schema"
				]
			},
			{
				required: [
					"content"
				],
				description: "Some properties are not allowed if content is present",
				allOf: [
					{
						not: {
							required: [
								"style"
							]
						}
					},
					{
						not: {
							required: [
								"explode"
							]
						}
					},
					{
						not: {
							required: [
								"allowReserved"
							]
						}
					},
					{
						not: {
							required: [
								"example"
							]
						}
					},
					{
						not: {
							required: [
								"examples"
							]
						}
					}
				]
			}
		]
	},
	Parameter: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			"in": {
				type: "string"
			},
			description: {
				type: "string"
			},
			required: {
				type: "boolean",
				"default": false
			},
			deprecated: {
				type: "boolean",
				"default": false
			},
			allowEmptyValue: {
				type: "boolean",
				"default": false
			},
			style: {
				type: "string"
			},
			explode: {
				type: "boolean"
			},
			allowReserved: {
				type: "boolean",
				"default": false
			},
			schema: {
				oneOf: [
					{
						$ref: "#/definitions/Schema"
					},
					{
						$ref: "#/definitions/Reference"
					}
				]
			},
			content: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/MediaType"
				},
				minProperties: 1,
				maxProperties: 1
			},
			example: {
			},
			examples: {
				type: "object",
				additionalProperties: {
					oneOf: [
						{
							$ref: "#/definitions/Example"
						},
						{
							$ref: "#/definitions/Reference"
						}
					]
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false,
		required: [
			"name",
			"in"
		],
		allOf: [
			{
				$ref: "#/definitions/ExampleXORExamples"
			},
			{
				$ref: "#/definitions/SchemaXORContent"
			},
			{
				$ref: "#/definitions/ParameterLocation"
			}
		]
	},
	ParameterLocation: {
		description: "Parameter location",
		oneOf: [
			{
				description: "Parameter in path",
				required: [
					"required"
				],
				properties: {
					"in": {
						"enum": [
							"path"
						]
					},
					style: {
						"enum": [
							"matrix",
							"label",
							"simple"
						],
						"default": "simple"
					},
					required: {
						"enum": [
							true
						]
					}
				}
			},
			{
				description: "Parameter in query",
				properties: {
					"in": {
						"enum": [
							"query"
						]
					},
					style: {
						"enum": [
							"form",
							"spaceDelimited",
							"pipeDelimited",
							"deepObject"
						],
						"default": "form"
					}
				}
			},
			{
				description: "Parameter in header",
				properties: {
					"in": {
						"enum": [
							"header"
						]
					},
					style: {
						"enum": [
							"simple"
						],
						"default": "simple"
					}
				}
			},
			{
				description: "Parameter in cookie",
				properties: {
					"in": {
						"enum": [
							"cookie"
						]
					},
					style: {
						"enum": [
							"form"
						],
						"default": "form"
					}
				}
			}
		]
	},
	RequestBody: {
		type: "object",
		required: [
			"content"
		],
		properties: {
			description: {
				type: "string"
			},
			content: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/MediaType"
				}
			},
			required: {
				type: "boolean",
				"default": false
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	SecurityScheme: {
		oneOf: [
			{
				$ref: "#/definitions/APIKeySecurityScheme"
			},
			{
				$ref: "#/definitions/HTTPSecurityScheme"
			},
			{
				$ref: "#/definitions/OAuth2SecurityScheme"
			},
			{
				$ref: "#/definitions/OpenIdConnectSecurityScheme"
			}
		]
	},
	APIKeySecurityScheme: {
		type: "object",
		required: [
			"type",
			"name",
			"in"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"apiKey"
				]
			},
			name: {
				type: "string"
			},
			"in": {
				type: "string",
				"enum": [
					"header",
					"query",
					"cookie"
				]
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	HTTPSecurityScheme: {
		type: "object",
		required: [
			"scheme",
			"type"
		],
		properties: {
			scheme: {
				type: "string"
			},
			bearerFormat: {
				type: "string"
			},
			description: {
				type: "string"
			},
			type: {
				type: "string",
				"enum": [
					"http"
				]
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false,
		oneOf: [
			{
				description: "Bearer",
				properties: {
					scheme: {
						"enum": [
							"bearer"
						]
					}
				}
			},
			{
				description: "Non Bearer",
				not: {
					required: [
						"bearerFormat"
					]
				},
				properties: {
					scheme: {
						not: {
							"enum": [
								"bearer"
							]
						}
					}
				}
			}
		]
	},
	OAuth2SecurityScheme: {
		type: "object",
		required: [
			"type",
			"flows"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"oauth2"
				]
			},
			flows: {
				$ref: "#/definitions/OAuthFlows"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	OpenIdConnectSecurityScheme: {
		type: "object",
		required: [
			"type",
			"openIdConnectUrl"
		],
		properties: {
			type: {
				type: "string",
				"enum": [
					"openIdConnect"
				]
			},
			openIdConnectUrl: {
				type: "string",
				format: "uri-reference"
			},
			description: {
				type: "string"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	OAuthFlows: {
		type: "object",
		properties: {
			implicit: {
				$ref: "#/definitions/ImplicitOAuthFlow"
			},
			password: {
				$ref: "#/definitions/PasswordOAuthFlow"
			},
			clientCredentials: {
				$ref: "#/definitions/ClientCredentialsFlow"
			},
			authorizationCode: {
				$ref: "#/definitions/AuthorizationCodeOAuthFlow"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	ImplicitOAuthFlow: {
		type: "object",
		required: [
			"authorizationUrl",
			"scopes"
		],
		properties: {
			authorizationUrl: {
				type: "string",
				format: "uri-reference"
			},
			refreshUrl: {
				type: "string",
				format: "uri-reference"
			},
			scopes: {
				type: "object",
				additionalProperties: {
					type: "string"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	PasswordOAuthFlow: {
		type: "object",
		required: [
			"tokenUrl"
		],
		properties: {
			tokenUrl: {
				type: "string",
				format: "uri-reference"
			},
			refreshUrl: {
				type: "string",
				format: "uri-reference"
			},
			scopes: {
				type: "object",
				additionalProperties: {
					type: "string"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	ClientCredentialsFlow: {
		type: "object",
		required: [
			"tokenUrl"
		],
		properties: {
			tokenUrl: {
				type: "string",
				format: "uri-reference"
			},
			refreshUrl: {
				type: "string",
				format: "uri-reference"
			},
			scopes: {
				type: "object",
				additionalProperties: {
					type: "string"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	AuthorizationCodeOAuthFlow: {
		type: "object",
		required: [
			"authorizationUrl",
			"tokenUrl"
		],
		properties: {
			authorizationUrl: {
				type: "string",
				format: "uri-reference"
			},
			tokenUrl: {
				type: "string",
				format: "uri-reference"
			},
			refreshUrl: {
				type: "string",
				format: "uri-reference"
			},
			scopes: {
				type: "object",
				additionalProperties: {
					type: "string"
				}
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false
	},
	Link: {
		type: "object",
		properties: {
			operationId: {
				type: "string"
			},
			operationRef: {
				type: "string",
				format: "uri-reference"
			},
			parameters: {
				type: "object",
				additionalProperties: {
				}
			},
			requestBody: {
			},
			description: {
				type: "string"
			},
			server: {
				$ref: "#/definitions/Server"
			}
		},
		patternProperties: {
			"^x-": {
			}
		},
		additionalProperties: false,
		not: {
			description: "Operation Id and Operation Ref are mutually exclusive",
			required: [
				"operationId",
				"operationRef"
			]
		}
	},
	Callback: {
		type: "object",
		additionalProperties: {
			$ref: "#/definitions/PathItem"
		},
		patternProperties: {
			"^x-": {
			}
		}
	},
	Encoding: {
		type: "object",
		properties: {
			contentType: {
				type: "string"
			},
			headers: {
				type: "object",
				additionalProperties: {
					$ref: "#/definitions/Header"
				}
			},
			style: {
				type: "string",
				"enum": [
					"form",
					"spaceDelimited",
					"pipeDelimited",
					"deepObject"
				]
			},
			explode: {
				type: "boolean"
			},
			allowReserved: {
				type: "boolean",
				"default": false
			}
		},
		additionalProperties: false
	}
};
var require$$2 = {
	id: id,
	$schema: $schema$1,
	description: description,
	type: type$2,
	required: required$1,
	properties: properties$1,
	patternProperties: patternProperties,
	additionalProperties: additionalProperties,
	definitions: definitions
};

var $id = "https://spec.openapis.org/oas/3.1/schema/2021-04-15";
var $schema = "https://json-schema.org/draft/2020-12/schema";
var type$1 = "object";
var properties = {
	openapi: {
		type: "string",
		pattern: "^3\\.1\\.\\d+(-.+)?$"
	},
	info: {
		$ref: "#/$defs/info"
	},
	jsonSchemaDialect: {
		$ref: "#/$defs/uri",
		"default": "https://spec.openapis.org/oas/3.1/dialect/base"
	},
	servers: {
		type: "array",
		items: {
			$ref: "#/$defs/server"
		}
	},
	paths: {
		$ref: "#/$defs/paths"
	},
	webhooks: {
		type: "object",
		additionalProperties: {
			$ref: "#/$defs/path-item-or-reference"
		}
	},
	components: {
		$ref: "#/$defs/components"
	},
	security: {
		type: "array",
		items: {
			$ref: "#/$defs/security-requirement"
		}
	},
	tags: {
		type: "array",
		items: {
			$ref: "#/$defs/tag"
		}
	},
	externalDocs: {
		$ref: "#/$defs/external-documentation"
	}
};
var required = [
	"openapi",
	"info"
];
var anyOf = [
	{
		required: [
			"paths"
		]
	},
	{
		required: [
			"components"
		]
	},
	{
		required: [
			"webhooks"
		]
	}
];
var $ref = "#/$defs/specification-extensions";
var unevaluatedProperties = false;
var $defs = {
	info: {
		type: "object",
		properties: {
			title: {
				type: "string"
			},
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			termsOfService: {
				type: "string"
			},
			contact: {
				$ref: "#/$defs/contact"
			},
			license: {
				$ref: "#/$defs/license"
			},
			version: {
				type: "string"
			}
		},
		required: [
			"title",
			"version"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	contact: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			url: {
				type: "string"
			},
			email: {
				type: "string"
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	license: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			identifier: {
				type: "string"
			},
			url: {
				$ref: "#/$defs/uri"
			}
		},
		required: [
			"name"
		],
		oneOf: [
			{
				required: [
					"identifier"
				]
			},
			{
				required: [
					"url"
				]
			}
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	server: {
		type: "object",
		properties: {
			url: {
				$ref: "#/$defs/uri"
			},
			description: {
				type: "string"
			},
			variables: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/server-variable"
				}
			}
		},
		required: [
			"url"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"server-variable": {
		type: "object",
		properties: {
			"enum": {
				type: "array",
				items: {
					type: "string"
				},
				minItems: 1
			},
			"default": {
				type: "string"
			},
			descriptions: {
				type: "string"
			}
		},
		required: [
			"default"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	components: {
		type: "object",
		properties: {
			schemas: {
				type: "object",
				additionalProperties: {
					$dynamicRef: "#meta"
				}
			},
			responses: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/response-or-reference"
				}
			},
			parameters: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/parameter-or-reference"
				}
			},
			examples: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/example-or-reference"
				}
			},
			requestBodies: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/request-body-or-reference"
				}
			},
			headers: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/header-or-reference"
				}
			},
			securitySchemes: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/security-scheme-or-reference"
				}
			},
			links: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/link-or-reference"
				}
			},
			callbacks: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/callbacks-or-reference"
				}
			},
			pathItems: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/path-item-or-reference"
				}
			}
		},
		patternProperties: {
			"^(schemas|responses|parameters|examples|requestBodies|headers|securitySchemes|links|callbacks|pathItems)$": {
				$comment: "Enumerating all of the property names in the regex above is necessary for unevaluatedProperties to work as expected",
				propertyNames: {
					pattern: "^[a-zA-Z0-9._-]+$"
				}
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	paths: {
		type: "object",
		patternProperties: {
			"^/": {
				$ref: "#/$defs/path-item"
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"path-item": {
		type: "object",
		properties: {
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			servers: {
				type: "array",
				items: {
					$ref: "#/$defs/server"
				}
			},
			parameters: {
				type: "array",
				items: {
					$ref: "#/$defs/parameter-or-reference"
				}
			}
		},
		patternProperties: {
			"^(get|put|post|delete|options|head|patch|trace)$": {
				$ref: "#/$defs/operation"
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"path-item-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/path-item"
		}
	},
	operation: {
		type: "object",
		properties: {
			tags: {
				type: "array",
				items: {
					type: "string"
				}
			},
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			externalDocs: {
				$ref: "#/$defs/external-documentation"
			},
			operationId: {
				type: "string"
			},
			parameters: {
				type: "array",
				items: {
					$ref: "#/$defs/parameter-or-reference"
				}
			},
			requestBody: {
				$ref: "#/$defs/request-body-or-reference"
			},
			responses: {
				$ref: "#/$defs/responses"
			},
			callbacks: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/callbacks-or-reference"
				}
			},
			deprecated: {
				"default": false,
				type: "boolean"
			},
			security: {
				type: "array",
				items: {
					$ref: "#/$defs/security-requirement"
				}
			},
			servers: {
				type: "array",
				items: {
					$ref: "#/$defs/server"
				}
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"external-documentation": {
		type: "object",
		properties: {
			description: {
				type: "string"
			},
			url: {
				$ref: "#/$defs/uri"
			}
		},
		required: [
			"url"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	parameter: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			"in": {
				"enum": [
					"query",
					"header",
					"path",
					"cookie"
				]
			},
			description: {
				type: "string"
			},
			required: {
				"default": false,
				type: "boolean"
			},
			deprecated: {
				"default": false,
				type: "boolean"
			},
			allowEmptyValue: {
				"default": false,
				type: "boolean"
			},
			schema: {
				$dynamicRef: "#meta"
			},
			content: {
				$ref: "#/$defs/content"
			}
		},
		required: [
			"in"
		],
		oneOf: [
			{
				required: [
					"schema"
				]
			},
			{
				required: [
					"content"
				]
			}
		],
		dependentSchemas: {
			schema: {
				properties: {
					style: {
						type: "string"
					},
					explode: {
						type: "boolean"
					},
					allowReserved: {
						"default": false,
						type: "boolean"
					}
				},
				allOf: [
					{
						$ref: "#/$defs/examples"
					},
					{
						$ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-path"
					},
					{
						$ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-header"
					},
					{
						$ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-query"
					},
					{
						$ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-cookie"
					},
					{
						$ref: "#/$defs/parameter/dependentSchemas/schema/$defs/styles-for-form"
					}
				],
				$defs: {
					"styles-for-path": {
						"if": {
							properties: {
								"in": {
									"const": "path"
								}
							},
							required: [
								"in"
							]
						},
						then: {
							properties: {
								style: {
									"default": "simple",
									"enum": [
										"matrix",
										"label",
										"simple"
									]
								},
								required: {
									"const": true
								}
							},
							required: [
								"required"
							]
						}
					},
					"styles-for-header": {
						"if": {
							properties: {
								"in": {
									"const": "header"
								}
							},
							required: [
								"in"
							]
						},
						then: {
							properties: {
								style: {
									"default": "simple",
									"enum": [
										"simple"
									]
								}
							}
						}
					},
					"styles-for-query": {
						"if": {
							properties: {
								"in": {
									"const": "query"
								}
							},
							required: [
								"in"
							]
						},
						then: {
							properties: {
								style: {
									"default": "form",
									"enum": [
										"form",
										"spaceDelimited",
										"pipeDelimited",
										"deepObject"
									]
								}
							}
						}
					},
					"styles-for-cookie": {
						"if": {
							properties: {
								"in": {
									"const": "cookie"
								}
							},
							required: [
								"in"
							]
						},
						then: {
							properties: {
								style: {
									"default": "form",
									"enum": [
										"form"
									]
								}
							}
						}
					},
					"styles-for-form": {
						"if": {
							properties: {
								style: {
									"const": "form"
								}
							},
							required: [
								"style"
							]
						},
						then: {
							properties: {
								explode: {
									"default": true
								}
							}
						},
						"else": {
							properties: {
								explode: {
									"default": false
								}
							}
						}
					}
				}
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"parameter-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/parameter"
		}
	},
	"request-body": {
		type: "object",
		properties: {
			description: {
				type: "string"
			},
			content: {
				$ref: "#/$defs/content"
			},
			required: {
				"default": false,
				type: "boolean"
			}
		},
		required: [
			"content"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"request-body-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/request-body"
		}
	},
	content: {
		type: "object",
		additionalProperties: {
			$ref: "#/$defs/media-type"
		},
		propertyNames: {
			format: "media-range"
		}
	},
	"media-type": {
		type: "object",
		properties: {
			schema: {
				$dynamicRef: "#meta"
			},
			encoding: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/encoding"
				}
			}
		},
		allOf: [
			{
				$ref: "#/$defs/specification-extensions"
			},
			{
				$ref: "#/$defs/examples"
			}
		],
		unevaluatedProperties: false
	},
	encoding: {
		type: "object",
		properties: {
			contentType: {
				type: "string",
				format: "media-range"
			},
			headers: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/header-or-reference"
				}
			},
			style: {
				"default": "form",
				"enum": [
					"form",
					"spaceDelimited",
					"pipeDelimited",
					"deepObject"
				]
			},
			explode: {
				type: "boolean"
			},
			allowReserved: {
				"default": false,
				type: "boolean"
			}
		},
		allOf: [
			{
				$ref: "#/$defs/specification-extensions"
			},
			{
				$ref: "#/$defs/encoding/$defs/explode-default"
			}
		],
		unevaluatedProperties: false,
		$defs: {
			"explode-default": {
				"if": {
					properties: {
						style: {
							"const": "form"
						}
					},
					required: [
						"style"
					]
				},
				then: {
					properties: {
						explode: {
							"default": true
						}
					}
				},
				"else": {
					properties: {
						explode: {
							"default": false
						}
					}
				}
			}
		}
	},
	responses: {
		type: "object",
		properties: {
			"default": {
				$ref: "#/$defs/response-or-reference"
			}
		},
		patternProperties: {
			"^[1-5][0-9X]{2}$": {
				$ref: "#/$defs/response-or-reference"
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	response: {
		type: "object",
		properties: {
			description: {
				type: "string"
			},
			headers: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/header-or-reference"
				}
			},
			content: {
				$ref: "#/$defs/content"
			},
			links: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/link-or-reference"
				}
			}
		},
		required: [
			"description"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"response-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/response"
		}
	},
	callbacks: {
		type: "object",
		$ref: "#/$defs/specification-extensions",
		additionalProperties: {
			$ref: "#/$defs/path-item-or-reference"
		}
	},
	"callbacks-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/callbacks"
		}
	},
	example: {
		type: "object",
		properties: {
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			},
			value: true,
			externalValue: {
				$ref: "#/$defs/uri"
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"example-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/example"
		}
	},
	link: {
		type: "object",
		properties: {
			operationRef: {
				$ref: "#/$defs/uri"
			},
			operationId: true,
			parameters: {
				$ref: "#/$defs/map-of-strings"
			},
			requestBody: true,
			description: {
				type: "string"
			},
			body: {
				$ref: "#/$defs/server"
			}
		},
		oneOf: [
			{
				required: [
					"operationRef"
				]
			},
			{
				required: [
					"operationId"
				]
			}
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"link-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/link"
		}
	},
	header: {
		type: "object",
		properties: {
			description: {
				type: "string"
			},
			required: {
				"default": false,
				type: "boolean"
			},
			deprecated: {
				"default": false,
				type: "boolean"
			},
			allowEmptyValue: {
				"default": false,
				type: "boolean"
			}
		},
		dependentSchemas: {
			schema: {
				properties: {
					style: {
						"default": "simple",
						"enum": [
							"simple"
						]
					},
					explode: {
						"default": false,
						type: "boolean"
					},
					allowReserved: {
						"default": false,
						type: "boolean"
					},
					schema: {
						$dynamicRef: "#meta"
					}
				},
				$ref: "#/$defs/examples"
			},
			content: {
				properties: {
					content: {
						$ref: "#/$defs/content"
					}
				}
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	"header-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/header"
		}
	},
	tag: {
		type: "object",
		properties: {
			name: {
				type: "string"
			},
			description: {
				type: "string"
			},
			externalDocs: {
				$ref: "#/$defs/external-documentation"
			}
		},
		required: [
			"name"
		],
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false
	},
	reference: {
		type: "object",
		properties: {
			$ref: {
				$ref: "#/$defs/uri"
			},
			summary: {
				type: "string"
			},
			description: {
				type: "string"
			}
		},
		unevaluatedProperties: false
	},
	schema: {
		$dynamicAnchor: "meta",
		type: [
			"object",
			"boolean"
		]
	},
	"security-scheme": {
		type: "object",
		properties: {
			type: {
				"enum": [
					"apiKey",
					"http",
					"mutualTLS",
					"oauth2",
					"openIdConnect"
				]
			},
			description: {
				type: "string"
			}
		},
		required: [
			"type"
		],
		allOf: [
			{
				$ref: "#/$defs/specification-extensions"
			},
			{
				$ref: "#/$defs/security-scheme/$defs/type-apikey"
			},
			{
				$ref: "#/$defs/security-scheme/$defs/type-http"
			},
			{
				$ref: "#/$defs/security-scheme/$defs/type-http-bearer"
			},
			{
				$ref: "#/$defs/security-scheme/$defs/type-oauth2"
			},
			{
				$ref: "#/$defs/security-scheme/$defs/type-oidc"
			}
		],
		unevaluatedProperties: false,
		$defs: {
			"type-apikey": {
				"if": {
					properties: {
						type: {
							"const": "apiKey"
						}
					},
					required: [
						"type"
					]
				},
				then: {
					properties: {
						name: {
							type: "string"
						},
						"in": {
							"enum": [
								"query",
								"header",
								"cookie"
							]
						}
					},
					required: [
						"name",
						"in"
					]
				}
			},
			"type-http": {
				"if": {
					properties: {
						type: {
							"const": "http"
						}
					},
					required: [
						"type"
					]
				},
				then: {
					properties: {
						scheme: {
							type: "string"
						}
					},
					required: [
						"scheme"
					]
				}
			},
			"type-http-bearer": {
				"if": {
					properties: {
						type: {
							"const": "http"
						},
						scheme: {
							"const": "bearer"
						}
					},
					required: [
						"type",
						"scheme"
					]
				},
				then: {
					properties: {
						bearerFormat: {
							type: "string"
						}
					},
					required: [
						"scheme"
					]
				}
			},
			"type-oauth2": {
				"if": {
					properties: {
						type: {
							"const": "oauth2"
						}
					},
					required: [
						"type"
					]
				},
				then: {
					properties: {
						flows: {
							$ref: "#/$defs/oauth-flows"
						}
					},
					required: [
						"flows"
					]
				}
			},
			"type-oidc": {
				"if": {
					properties: {
						type: {
							"const": "openIdConnect"
						}
					},
					required: [
						"type"
					]
				},
				then: {
					properties: {
						openIdConnectUrl: {
							$ref: "#/$defs/uri"
						}
					},
					required: [
						"openIdConnectUrl"
					]
				}
			}
		}
	},
	"security-scheme-or-reference": {
		"if": {
			required: [
				"$ref"
			]
		},
		then: {
			$ref: "#/$defs/reference"
		},
		"else": {
			$ref: "#/$defs/security-scheme"
		}
	},
	"oauth-flows": {
		type: "object",
		properties: {
			implicit: {
				$ref: "#/$defs/oauth-flows/$defs/implicit"
			},
			password: {
				$ref: "#/$defs/oauth-flows/$defs/password"
			},
			clientCredentials: {
				$ref: "#/$defs/oauth-flows/$defs/client-credentials"
			},
			authorizationCode: {
				$ref: "#/$defs/oauth-flows/$defs/authorization-code"
			}
		},
		$ref: "#/$defs/specification-extensions",
		unevaluatedProperties: false,
		$defs: {
			implicit: {
				type: "object",
				properties: {
					authorizationUrl: {
						type: "string"
					},
					refreshUrl: {
						type: "string"
					},
					scopes: {
						$ref: "#/$defs/map-of-strings"
					}
				},
				required: [
					"authorizationUrl",
					"scopes"
				],
				$ref: "#/$defs/specification-extensions",
				unevaluatedProperties: false
			},
			password: {
				type: "object",
				properties: {
					tokenUrl: {
						type: "string"
					},
					refreshUrl: {
						type: "string"
					},
					scopes: {
						$ref: "#/$defs/map-of-strings"
					}
				},
				required: [
					"tokenUrl",
					"scopes"
				],
				$ref: "#/$defs/specification-extensions",
				unevaluatedProperties: false
			},
			"client-credentials": {
				type: "object",
				properties: {
					tokenUrl: {
						type: "string"
					},
					refreshUrl: {
						type: "string"
					},
					scopes: {
						$ref: "#/$defs/map-of-strings"
					}
				},
				required: [
					"tokenUrl",
					"scopes"
				],
				$ref: "#/$defs/specification-extensions",
				unevaluatedProperties: false
			},
			"authorization-code": {
				type: "object",
				properties: {
					authorizationUrl: {
						type: "string"
					},
					tokenUrl: {
						type: "string"
					},
					refreshUrl: {
						type: "string"
					},
					scopes: {
						$ref: "#/$defs/map-of-strings"
					}
				},
				required: [
					"authorizationUrl",
					"tokenUrl",
					"scopes"
				],
				$ref: "#/$defs/specification-extensions",
				unevaluatedProperties: false
			}
		}
	},
	"security-requirement": {
		type: "object",
		additionalProperties: {
			type: "array",
			items: {
				type: "string"
			}
		}
	},
	"specification-extensions": {
		patternProperties: {
			"^x-": true
		}
	},
	examples: {
		properties: {
			example: true,
			examples: {
				type: "object",
				additionalProperties: {
					$ref: "#/$defs/example-or-reference"
				}
			}
		}
	},
	uri: {
		type: "string",
		format: "uri"
	},
	"map-of-strings": {
		type: "object",
		additionalProperties: {
			type: "string"
		}
	}
};
var require$$3 = {
	$id: $id,
	$schema: $schema,
	type: type$1,
	properties: properties,
	required: required,
	anyOf: anyOf,
	$ref: $ref,
	unevaluatedProperties: unevaluatedProperties,
	$defs: $defs
};

var hasRequiredLib$3;

function requireLib$3 () {
	if (hasRequiredLib$3) return lib$3.exports;
	hasRequiredLib$3 = 1;
	(function (module, exports) {
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.openapi = exports.openapiV31 = exports.openapiV3 = exports.openapiV2 = exports.openapiV1 = undefined;
		/**
		 * JSON Schema for OpenAPI Specification v1.2
		 */
		exports.openapiV1 = require$$0$1;
		/**
		 * JSON Schema for OpenAPI Specification v2.0
		 */
		exports.openapiV2 = require$$1;
		/**
		 * JSON Schema for OpenAPI Specification v3.0
		 */
		exports.openapiV3 = require$$2;
		/**
		 * JSON Schema for OpenAPI Specification v3.1
		 */
		exports.openapiV31 = require$$3;
		/**
		 * JSON Schemas for every version of the OpenAPI Specification
		 */
		exports.openapi = {
		    v1: exports.openapiV1,
		    v2: exports.openapiV2,
		    v3: exports.openapiV3,
		    v31: exports.openapiV31,
		};
		// Export `openapi` as the default export
		exports.default = exports.openapi;
		// CommonJS default export hack
		/* eslint-env commonjs */
		{
		    module.exports = Object.assign(module.exports.default, module.exports);
		}
		
	} (lib$3, lib$3.exports));
	return lib$3.exports;
}

var schema$4;
var hasRequiredSchema$1;

function requireSchema$1 () {
	if (hasRequiredSchema$1) return schema$4;
	hasRequiredSchema$1 = 1;

	const util = requireUtil$1();
	const { ono } = require$$6$1;
	const AjvDraft4 = requireDist();
	const Ajv = require_2020();
	const { openapi } = requireLib$3();

	schema$4 = validateSchema;

	/**
	 * Validates the given Swagger API against the Swagger 2.0 or OpenAPI 3.0 and 3.1 schemas.
	 *
	 * @param {SwaggerObject} api
	 */
	function validateSchema (api) {
	  let ajv;

	  // Choose the appropriate schema (Swagger or OpenAPI)
	  let schema;

	  if (api.swagger) {
	    schema = openapi.v2;
	    ajv = initializeAjv();
	  }
	  else {
	    if (api.openapi.startsWith("3.1")) {
	      schema = openapi.v31;

	      // There's a bug with Ajv in how it handles `$dynamicRef` in the way that it's used within the 3.1 schema so we
	      // need to do some adhoc workarounds.
	      // https://github.com/OAI/OpenAPI-Specification/issues/2689
	      // https://github.com/ajv-validator/ajv/issues/1573
	      const schemaDynamicRef = schema.$defs.schema;
	      delete schemaDynamicRef.$dynamicAnchor;

	      schema.$defs.components.properties.schemas.additionalProperties = schemaDynamicRef;
	      schema.$defs.header.dependentSchemas.schema.properties.schema = schemaDynamicRef;
	      schema.$defs["media-type"].properties.schema = schemaDynamicRef;
	      schema.$defs.parameter.properties.schema = schemaDynamicRef;

	      ajv = initializeAjv(false);
	    }
	    else {
	      schema = openapi.v3;
	      ajv = initializeAjv();
	    }
	  }

	  // Validate against the schema
	  let isValid = ajv.validate(schema, api);
	  if (!isValid) {
	    let err = ajv.errors;
	    let message = "Swagger schema validation failed.\n" + formatAjvError(err);
	    throw ono.syntax(err, { details: err }, message);
	  }
	}

	/**
	 * Determines which version of Ajv to load and prepares it for use.
	 *
	 * @param {bool} draft04
	 * @returns {Ajv}
	 */
	function initializeAjv (draft04 = true) {
	  const opts = {
	    allErrors: true,
	    strict: false,
	    validateFormats: false,
	  };

	  if (draft04) {
	    return new AjvDraft4(opts);
	  }

	  return new Ajv(opts);
	}

	/**
	 * Run through a set of Ajv errors and compile them into an error message string.
	 *
	 * @param {object[]}  errors     - The Ajv errors
	 * @param {string}    [indent]   - The whitespace used to indent the error message
	 * @returns {string}
	 */
	function formatAjvError (errors, indent) {
	  indent = indent || "  ";
	  let message = "";
	  for (let error of errors) {
	    message += util.format(`${indent}#${error.instancePath.length ? error.instancePath : "/"} ${error.message}\n`);
	  }
	  return message;
	}
	return schema$4;
}

var lib$2;
var hasRequiredLib$2;

function requireLib$2 () {
	if (hasRequiredLib$2) return lib$2;
	hasRequiredLib$2 = 1;

	lib$2 = [
	  "get", "put", "post", "delete", "options", "head", "patch"
	];
	return lib$2;
}

var spec;
var hasRequiredSpec;

function requireSpec () {
	if (hasRequiredSpec) return spec;
	hasRequiredSpec = 1;

	const util = requireUtil$1();
	const { ono } = require$$6$1;
	const swaggerMethods = requireLib$2();
	const primitiveTypes = ["array", "boolean", "integer", "number", "string"];
	const schemaTypes = ["array", "boolean", "integer", "number", "string", "object", "null", undefined];

	spec = validateSpec;

	/**
	 * Validates parts of the Swagger 2.0 spec that aren't covered by the Swagger 2.0 JSON Schema.
	 *
	 * @param {SwaggerObject} api
	 */
	function validateSpec (api) {
	  if (api.openapi) {
	    // We don't (yet) support validating against the OpenAPI spec
	    return;
	  }

	  let paths = Object.keys(api.paths || {});
	  let operationIds = [];
	  for (let pathName of paths) {
	    let path = api.paths[pathName];
	    let pathId = "/paths" + pathName;

	    if (path && pathName.indexOf("/") === 0) {
	      validatePath(api, path, pathId, operationIds);
	    }
	  }

	  let definitions = Object.keys(api.definitions || {});
	  for (let definitionName of definitions) {
	    let definition = api.definitions[definitionName];
	    let definitionId = "/definitions/" + definitionName;
	    validateRequiredPropertiesExist(definition, definitionId);
	  }
	}

	/**
	 * Validates the given path.
	 *
	 * @param {SwaggerObject} api           - The entire Swagger API object
	 * @param {object}        path          - A Path object, from the Swagger API
	 * @param {string}        pathId        - A value that uniquely identifies the path
	 * @param {string}        operationIds  - An array of collected operationIds found in other paths
	 */
	function validatePath (api, path, pathId, operationIds) {
	  for (let operationName of swaggerMethods) {
	    let operation = path[operationName];
	    let operationId = pathId + "/" + operationName;

	    if (operation) {
	      let declaredOperationId = operation.operationId;
	      if (declaredOperationId) {
	        if (operationIds.indexOf(declaredOperationId) === -1) {
	          operationIds.push(declaredOperationId);
	        }
	        else {
	          throw ono.syntax(`Validation failed. Duplicate operation id '${declaredOperationId}'`);
	        }
	      }
	      validateParameters(api, path, pathId, operation, operationId);

	      let responses = Object.keys(operation.responses || {});
	      for (let responseName of responses) {
	        let response = operation.responses[responseName];
	        let responseId = operationId + "/responses/" + responseName;
	        validateResponse(responseName, (response || {}), responseId);
	      }
	    }
	  }
	}

	/**
	 * Validates the parameters for the given operation.
	 *
	 * @param {SwaggerObject} api           - The entire Swagger API object
	 * @param {object}        path          - A Path object, from the Swagger API
	 * @param {string}        pathId        - A value that uniquely identifies the path
	 * @param {object}        operation     - An Operation object, from the Swagger API
	 * @param {string}        operationId   - A value that uniquely identifies the operation
	 */
	function validateParameters (api, path, pathId, operation, operationId) {
	  let pathParams = path.parameters || [];
	  let operationParams = operation.parameters || [];

	  // Check for duplicate path parameters
	  try {
	    checkForDuplicates(pathParams);
	  }
	  catch (e) {
	    throw ono.syntax(e, `Validation failed. ${pathId} has duplicate parameters`);
	  }

	  // Check for duplicate operation parameters
	  try {
	    checkForDuplicates(operationParams);
	  }
	  catch (e) {
	    throw ono.syntax(e, `Validation failed. ${operationId} has duplicate parameters`);
	  }

	  // Combine the path and operation parameters,
	  // with the operation params taking precedence over the path params
	  let params = pathParams.reduce((combinedParams, value) => {
	    let duplicate = combinedParams.some((param) => {
	      return param.in === value.in && param.name === value.name;
	    });
	    if (!duplicate) {
	      combinedParams.push(value);
	    }
	    return combinedParams;
	  }, operationParams.slice());

	  validateBodyParameters(params, operationId);
	  validatePathParameters(params, pathId, operationId);
	  validateParameterTypes(params, api, operation, operationId);
	}

	/**
	 * Validates body and formData parameters for the given operation.
	 *
	 * @param   {object[]}  params       -  An array of Parameter objects
	 * @param   {string}    operationId  -  A value that uniquely identifies the operation
	 */
	function validateBodyParameters (params, operationId) {
	  let bodyParams = params.filter((param) => { return param.in === "body"; });
	  let formParams = params.filter((param) => { return param.in === "formData"; });

	  // There can only be one "body" parameter
	  if (bodyParams.length > 1) {
	    throw ono.syntax(
	      `Validation failed. ${operationId} has ${bodyParams.length} body parameters. Only one is allowed.`,
	    );
	  }
	  else if (bodyParams.length > 0 && formParams.length > 0) {
	    // "body" params and "formData" params are mutually exclusive
	    throw ono.syntax(
	      `Validation failed. ${operationId} has body parameters and formData parameters. Only one or the other is allowed.`,
	    );
	  }
	}

	/**
	 * Validates path parameters for the given path.
	 *
	 * @param   {object[]}  params        - An array of Parameter objects
	 * @param   {string}    pathId        - A value that uniquely identifies the path
	 * @param   {string}    operationId   - A value that uniquely identifies the operation
	 */
	function validatePathParameters (params, pathId, operationId) {
	  // Find all {placeholders} in the path string
	  let placeholders = pathId.match(util.swaggerParamRegExp) || [];

	  // Check for duplicates
	  for (let i = 0; i < placeholders.length; i++) {
	    for (let j = i + 1; j < placeholders.length; j++) {
	      if (placeholders[i] === placeholders[j]) {
	        throw ono.syntax(
	          `Validation failed. ${operationId} has multiple path placeholders named ${placeholders[i]}`);
	      }
	    }
	  }

	  params = params.filter((param) => { return param.in === "path"; });

	  for (let param of params) {
	    if (param.required !== true) {
	      throw ono.syntax(
	        "Validation failed. Path parameters cannot be optional. " +
	        `Set required=true for the "${param.name}" parameter at ${operationId}`,
	      );
	    }
	    let match = placeholders.indexOf("{" + param.name + "}");
	    if (match === -1) {
	      throw ono.syntax(
	        `Validation failed. ${operationId} has a path parameter named "${param.name}", ` +
	        `but there is no corresponding {${param.name}} in the path string`
	      );
	    }
	    placeholders.splice(match, 1);
	  }

	  if (placeholders.length > 0) {
	    throw ono.syntax(`Validation failed. ${operationId} is missing path parameter(s) for ${placeholders}`);
	  }
	}

	/**
	 * Validates data types of parameters for the given operation.
	 *
	 * @param   {object[]}  params       -  An array of Parameter objects
	 * @param   {object}    api          -  The entire Swagger API object
	 * @param   {object}    operation    -  An Operation object, from the Swagger API
	 * @param   {string}    operationId  -  A value that uniquely identifies the operation
	 */
	function validateParameterTypes (params, api, operation, operationId) {
	  for (let param of params) {
	    let parameterId = operationId + "/parameters/" + param.name;
	    let schema, validTypes;

	    switch (param.in) {
	      case "body":
	        schema = param.schema;
	        validTypes = schemaTypes;
	        break;
	      case "formData":
	        schema = param;
	        validTypes = primitiveTypes.concat("file");
	        break;
	      default:
	        schema = param;
	        validTypes = primitiveTypes;
	    }

	    validateSchema(schema, parameterId, validTypes);
	    validateRequiredPropertiesExist(schema, parameterId);

	    if (schema.type === "file") {
	      // "file" params must consume at least one of these MIME types
	      let formData = /multipart\/(.*\+)?form-data/;
	      let urlEncoded = /application\/(.*\+)?x-www-form-urlencoded/;

	      let consumes = operation.consumes || api.consumes || [];

	      let hasValidMimeType = consumes.some((consume) => {
	        return formData.test(consume) || urlEncoded.test(consume);
	      });

	      if (!hasValidMimeType) {
	        throw ono.syntax(
	          `Validation failed. ${operationId} has a file parameter, so it must consume multipart/form-data ` +
	          "or application/x-www-form-urlencoded",
	        );
	      }
	    }
	  }
	}

	/**
	 * Checks the given parameter list for duplicates, and throws an error if found.
	 *
	 * @param   {object[]}  params  - An array of Parameter objects
	 */
	function checkForDuplicates (params) {
	  for (let i = 0; i < params.length - 1; i++) {
	    let outer = params[i];
	    for (let j = i + 1; j < params.length; j++) {
	      let inner = params[j];
	      if (outer.name === inner.name && outer.in === inner.in) {
	        throw ono.syntax(`Validation failed. Found multiple ${outer.in} parameters named "${outer.name}"`);
	      }
	    }
	  }
	}

	/**
	 * Validates the given response object.
	 *
	 * @param   {string}    code        -  The HTTP response code (or "default")
	 * @param   {object}    response    -  A Response object, from the Swagger API
	 * @param   {string}    responseId  -  A value that uniquely identifies the response
	 */
	function validateResponse (code, response, responseId) {
	  if (code !== "default" && (code < 100 || code > 599)) {
	    throw ono.syntax(`Validation failed. ${responseId} has an invalid response code (${code})`);
	  }

	  let headers = Object.keys(response.headers || {});
	  for (let headerName of headers) {
	    let header = response.headers[headerName];
	    let headerId = responseId + "/headers/" + headerName;
	    validateSchema(header, headerId, primitiveTypes);
	  }

	  if (response.schema) {
	    let validTypes = schemaTypes.concat("file");
	    if (validTypes.indexOf(response.schema.type) === -1) {
	      throw ono.syntax(
	        `Validation failed. ${responseId} has an invalid response schema type (${response.schema.type})`);
	    }
	    else {
	      validateSchema(response.schema, responseId + "/schema", validTypes);
	    }
	  }
	}

	/**
	 * Validates the given Swagger schema object.
	 *
	 * @param {object}    schema      - A Schema object, from the Swagger API
	 * @param {string}    schemaId    - A value that uniquely identifies the schema object
	 * @param {string[]}  validTypes  - An array of the allowed schema types
	 */
	function validateSchema (schema, schemaId, validTypes) {
	  if (validTypes.indexOf(schema.type) === -1) {
	    throw ono.syntax(
	      `Validation failed. ${schemaId} has an invalid type (${schema.type})`);
	  }

	  if (schema.type === "array" && !schema.items) {
	    throw ono.syntax(`Validation failed. ${schemaId} is an array, so it must include an "items" schema`);
	  }
	}

	/**
	 * Validates that the declared properties of the given Swagger schema object actually exist.
	 *
	 * @param {object}    schema      - A Schema object, from the Swagger API
	 * @param {string}    schemaId    - A value that uniquely identifies the schema object
	 */
	function validateRequiredPropertiesExist (schema, schemaId) {
	  /**
	   * Recursively collects all properties of the schema and its ancestors. They are added to the props object.
	   */
	  function collectProperties (schemaObj, props) {
	    if (schemaObj.properties) {
	      for (let property in schemaObj.properties) {
	        if (schemaObj.properties.hasOwnProperty(property)) {
	          props[property] = schemaObj.properties[property];
	        }
	      }
	    }
	    if (schemaObj.allOf) {
	      for (let parent of schemaObj.allOf) {
	        collectProperties(parent, props);
	      }
	    }
	  }

	  // The "required" keyword is only applicable for objects
	  if (Array.isArray(schema.type) && !schema.type.includes("object")) {
	    return;
	  }
	  else if (!Array.isArray(schema.type) && schema.type !== "object") {
	    return;
	  }

	  if (schema.required && Array.isArray(schema.required)) {
	    let props = {};
	    collectProperties(schema, props);
	    for (let requiredProperty of schema.required) {
	      if (!props[requiredProperty]) {
	        throw ono.syntax(
	          `Validation failed. Property '${requiredProperty}' listed as required but does not exist in '${schemaId}'`
	        );
	      }
	    }
	  }
	}
	return spec;
}

var lib$1 = {};

var refs = {};

var ref = {};

var pointer = {};

var url = {};

var convertPathToPosix = {};

var pathBrowserify;
var hasRequiredPathBrowserify;

function requirePathBrowserify () {
	if (hasRequiredPathBrowserify) return pathBrowserify;
	hasRequiredPathBrowserify = 1;

	function assertPath(path) {
	  if (typeof path !== 'string') {
	    throw new TypeError('Path must be a string. Received ' + JSON.stringify(path));
	  }
	}

	// Resolves . and .. elements in a path with directory names
	function normalizeStringPosix(path, allowAboveRoot) {
	  var res = '';
	  var lastSegmentLength = 0;
	  var lastSlash = -1;
	  var dots = 0;
	  var code;
	  for (var i = 0; i <= path.length; ++i) {
	    if (i < path.length)
	      code = path.charCodeAt(i);
	    else if (code === 47 /*/*/)
	      break;
	    else
	      code = 47 /*/*/;
	    if (code === 47 /*/*/) {
	      if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) {
	        if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) {
	          if (res.length > 2) {
	            var lastSlashIndex = res.lastIndexOf('/');
	            if (lastSlashIndex !== res.length - 1) {
	              if (lastSlashIndex === -1) {
	                res = '';
	                lastSegmentLength = 0;
	              } else {
	                res = res.slice(0, lastSlashIndex);
	                lastSegmentLength = res.length - 1 - res.lastIndexOf('/');
	              }
	              lastSlash = i;
	              dots = 0;
	              continue;
	            }
	          } else if (res.length === 2 || res.length === 1) {
	            res = '';
	            lastSegmentLength = 0;
	            lastSlash = i;
	            dots = 0;
	            continue;
	          }
	        }
	        if (allowAboveRoot) {
	          if (res.length > 0)
	            res += '/..';
	          else
	            res = '..';
	          lastSegmentLength = 2;
	        }
	      } else {
	        if (res.length > 0)
	          res += '/' + path.slice(lastSlash + 1, i);
	        else
	          res = path.slice(lastSlash + 1, i);
	        lastSegmentLength = i - lastSlash - 1;
	      }
	      lastSlash = i;
	      dots = 0;
	    } else if (code === 46 /*.*/ && dots !== -1) {
	      ++dots;
	    } else {
	      dots = -1;
	    }
	  }
	  return res;
	}

	function _format(sep, pathObject) {
	  var dir = pathObject.dir || pathObject.root;
	  var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || '');
	  if (!dir) {
	    return base;
	  }
	  if (dir === pathObject.root) {
	    return dir + base;
	  }
	  return dir + sep + base;
	}

	var posix = {
	  // path.resolve([from ...], to)
	  resolve: function resolve() {
	    var resolvedPath = '';
	    var resolvedAbsolute = false;
	    var cwd;

	    for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
	      var path;
	      if (i >= 0)
	        path = arguments[i];
	      else {
	        if (cwd === undefined)
	          cwd = api.cwd();
	        path = cwd;
	      }

	      assertPath(path);

	      // Skip empty entries
	      if (path.length === 0) {
	        continue;
	      }

	      resolvedPath = path + '/' + resolvedPath;
	      resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/;
	    }

	    // At this point the path should be resolved to a full absolute path, but
	    // handle relative paths to be safe (might happen when process.cwd() fails)

	    // Normalize the path
	    resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute);

	    if (resolvedAbsolute) {
	      if (resolvedPath.length > 0)
	        return '/' + resolvedPath;
	      else
	        return '/';
	    } else if (resolvedPath.length > 0) {
	      return resolvedPath;
	    } else {
	      return '.';
	    }
	  },

	  normalize: function normalize(path) {
	    assertPath(path);

	    if (path.length === 0) return '.';

	    var isAbsolute = path.charCodeAt(0) === 47 /*/*/;
	    var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/;

	    // Normalize the path
	    path = normalizeStringPosix(path, !isAbsolute);

	    if (path.length === 0 && !isAbsolute) path = '.';
	    if (path.length > 0 && trailingSeparator) path += '/';

	    if (isAbsolute) return '/' + path;
	    return path;
	  },

	  isAbsolute: function isAbsolute(path) {
	    assertPath(path);
	    return path.length > 0 && path.charCodeAt(0) === 47 /*/*/;
	  },

	  join: function join() {
	    if (arguments.length === 0)
	      return '.';
	    var joined;
	    for (var i = 0; i < arguments.length; ++i) {
	      var arg = arguments[i];
	      assertPath(arg);
	      if (arg.length > 0) {
	        if (joined === undefined)
	          joined = arg;
	        else
	          joined += '/' + arg;
	      }
	    }
	    if (joined === undefined)
	      return '.';
	    return posix.normalize(joined);
	  },

	  relative: function relative(from, to) {
	    assertPath(from);
	    assertPath(to);

	    if (from === to) return '';

	    from = posix.resolve(from);
	    to = posix.resolve(to);

	    if (from === to) return '';

	    // Trim any leading backslashes
	    var fromStart = 1;
	    for (; fromStart < from.length; ++fromStart) {
	      if (from.charCodeAt(fromStart) !== 47 /*/*/)
	        break;
	    }
	    var fromEnd = from.length;
	    var fromLen = fromEnd - fromStart;

	    // Trim any leading backslashes
	    var toStart = 1;
	    for (; toStart < to.length; ++toStart) {
	      if (to.charCodeAt(toStart) !== 47 /*/*/)
	        break;
	    }
	    var toEnd = to.length;
	    var toLen = toEnd - toStart;

	    // Compare paths to find the longest common path from root
	    var length = fromLen < toLen ? fromLen : toLen;
	    var lastCommonSep = -1;
	    var i = 0;
	    for (; i <= length; ++i) {
	      if (i === length) {
	        if (toLen > length) {
	          if (to.charCodeAt(toStart + i) === 47 /*/*/) {
	            // We get here if `from` is the exact base path for `to`.
	            // For example: from='/foo/bar'; to='/foo/bar/baz'
	            return to.slice(toStart + i + 1);
	          } else if (i === 0) {
	            // We get here if `from` is the root
	            // For example: from='/'; to='/foo'
	            return to.slice(toStart + i);
	          }
	        } else if (fromLen > length) {
	          if (from.charCodeAt(fromStart + i) === 47 /*/*/) {
	            // We get here if `to` is the exact base path for `from`.
	            // For example: from='/foo/bar/baz'; to='/foo/bar'
	            lastCommonSep = i;
	          } else if (i === 0) {
	            // We get here if `to` is the root.
	            // For example: from='/foo'; to='/'
	            lastCommonSep = 0;
	          }
	        }
	        break;
	      }
	      var fromCode = from.charCodeAt(fromStart + i);
	      var toCode = to.charCodeAt(toStart + i);
	      if (fromCode !== toCode)
	        break;
	      else if (fromCode === 47 /*/*/)
	        lastCommonSep = i;
	    }

	    var out = '';
	    // Generate the relative path based on the path difference between `to`
	    // and `from`
	    for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) {
	      if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) {
	        if (out.length === 0)
	          out += '..';
	        else
	          out += '/..';
	      }
	    }

	    // Lastly, append the rest of the destination (`to`) path that comes after
	    // the common path parts
	    if (out.length > 0)
	      return out + to.slice(toStart + lastCommonSep);
	    else {
	      toStart += lastCommonSep;
	      if (to.charCodeAt(toStart) === 47 /*/*/)
	        ++toStart;
	      return to.slice(toStart);
	    }
	  },

	  _makeLong: function _makeLong(path) {
	    return path;
	  },

	  dirname: function dirname(path) {
	    assertPath(path);
	    if (path.length === 0) return '.';
	    var code = path.charCodeAt(0);
	    var hasRoot = code === 47 /*/*/;
	    var end = -1;
	    var matchedSlash = true;
	    for (var i = path.length - 1; i >= 1; --i) {
	      code = path.charCodeAt(i);
	      if (code === 47 /*/*/) {
	          if (!matchedSlash) {
	            end = i;
	            break;
	          }
	        } else {
	        // We saw the first non-path separator
	        matchedSlash = false;
	      }
	    }

	    if (end === -1) return hasRoot ? '/' : '.';
	    if (hasRoot && end === 1) return '//';
	    return path.slice(0, end);
	  },

	  basename: function basename(path, ext) {
	    if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string');
	    assertPath(path);

	    var start = 0;
	    var end = -1;
	    var matchedSlash = true;
	    var i;

	    if (ext !== undefined && ext.length > 0 && ext.length <= path.length) {
	      if (ext.length === path.length && ext === path) return '';
	      var extIdx = ext.length - 1;
	      var firstNonSlashEnd = -1;
	      for (i = path.length - 1; i >= 0; --i) {
	        var code = path.charCodeAt(i);
	        if (code === 47 /*/*/) {
	            // If we reached a path separator that was not part of a set of path
	            // separators at the end of the string, stop now
	            if (!matchedSlash) {
	              start = i + 1;
	              break;
	            }
	          } else {
	          if (firstNonSlashEnd === -1) {
	            // We saw the first non-path separator, remember this index in case
	            // we need it if the extension ends up not matching
	            matchedSlash = false;
	            firstNonSlashEnd = i + 1;
	          }
	          if (extIdx >= 0) {
	            // Try to match the explicit extension
	            if (code === ext.charCodeAt(extIdx)) {
	              if (--extIdx === -1) {
	                // We matched the extension, so mark this as the end of our path
	                // component
	                end = i;
	              }
	            } else {
	              // Extension does not match, so our result is the entire path
	              // component
	              extIdx = -1;
	              end = firstNonSlashEnd;
	            }
	          }
	        }
	      }

	      if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length;
	      return path.slice(start, end);
	    } else {
	      for (i = path.length - 1; i >= 0; --i) {
	        if (path.charCodeAt(i) === 47 /*/*/) {
	            // If we reached a path separator that was not part of a set of path
	            // separators at the end of the string, stop now
	            if (!matchedSlash) {
	              start = i + 1;
	              break;
	            }
	          } else if (end === -1) {
	          // We saw the first non-path separator, mark this as the end of our
	          // path component
	          matchedSlash = false;
	          end = i + 1;
	        }
	      }

	      if (end === -1) return '';
	      return path.slice(start, end);
	    }
	  },

	  extname: function extname(path) {
	    assertPath(path);
	    var startDot = -1;
	    var startPart = 0;
	    var end = -1;
	    var matchedSlash = true;
	    // Track the state of characters (if any) we see before our first dot and
	    // after any path separator we find
	    var preDotState = 0;
	    for (var i = path.length - 1; i >= 0; --i) {
	      var code = path.charCodeAt(i);
	      if (code === 47 /*/*/) {
	          // If we reached a path separator that was not part of a set of path
	          // separators at the end of the string, stop now
	          if (!matchedSlash) {
	            startPart = i + 1;
	            break;
	          }
	          continue;
	        }
	      if (end === -1) {
	        // We saw the first non-path separator, mark this as the end of our
	        // extension
	        matchedSlash = false;
	        end = i + 1;
	      }
	      if (code === 46 /*.*/) {
	          // If this is our first dot, mark it as the start of our extension
	          if (startDot === -1)
	            startDot = i;
	          else if (preDotState !== 1)
	            preDotState = 1;
	      } else if (startDot !== -1) {
	        // We saw a non-dot and non-path separator before our dot, so we should
	        // have a good chance at having a non-empty extension
	        preDotState = -1;
	      }
	    }

	    if (startDot === -1 || end === -1 ||
	        // We saw a non-dot character immediately before the dot
	        preDotState === 0 ||
	        // The (right-most) trimmed path component is exactly '..'
	        preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
	      return '';
	    }
	    return path.slice(startDot, end);
	  },

	  format: function format(pathObject) {
	    if (pathObject === null || typeof pathObject !== 'object') {
	      throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject);
	    }
	    return _format('/', pathObject);
	  },

	  parse: function parse(path) {
	    assertPath(path);

	    var ret = { root: '', dir: '', base: '', ext: '', name: '' };
	    if (path.length === 0) return ret;
	    var code = path.charCodeAt(0);
	    var isAbsolute = code === 47 /*/*/;
	    var start;
	    if (isAbsolute) {
	      ret.root = '/';
	      start = 1;
	    } else {
	      start = 0;
	    }
	    var startDot = -1;
	    var startPart = 0;
	    var end = -1;
	    var matchedSlash = true;
	    var i = path.length - 1;

	    // Track the state of characters (if any) we see before our first dot and
	    // after any path separator we find
	    var preDotState = 0;

	    // Get non-dir info
	    for (; i >= start; --i) {
	      code = path.charCodeAt(i);
	      if (code === 47 /*/*/) {
	          // If we reached a path separator that was not part of a set of path
	          // separators at the end of the string, stop now
	          if (!matchedSlash) {
	            startPart = i + 1;
	            break;
	          }
	          continue;
	        }
	      if (end === -1) {
	        // We saw the first non-path separator, mark this as the end of our
	        // extension
	        matchedSlash = false;
	        end = i + 1;
	      }
	      if (code === 46 /*.*/) {
	          // If this is our first dot, mark it as the start of our extension
	          if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1;
	        } else if (startDot !== -1) {
	        // We saw a non-dot and non-path separator before our dot, so we should
	        // have a good chance at having a non-empty extension
	        preDotState = -1;
	      }
	    }

	    if (startDot === -1 || end === -1 ||
	    // We saw a non-dot character immediately before the dot
	    preDotState === 0 ||
	    // The (right-most) trimmed path component is exactly '..'
	    preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) {
	      if (end !== -1) {
	        if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end);
	      }
	    } else {
	      if (startPart === 0 && isAbsolute) {
	        ret.name = path.slice(1, startDot);
	        ret.base = path.slice(1, end);
	      } else {
	        ret.name = path.slice(startPart, startDot);
	        ret.base = path.slice(startPart, end);
	      }
	      ret.ext = path.slice(startDot, end);
	    }

	    if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/';

	    return ret;
	  },

	  sep: '/',
	  delimiter: ':',
	  win32: null,
	  posix: null
	};

	posix.posix = posix;

	pathBrowserify = posix;
	return pathBrowserify;
}

var hasRequiredConvertPathToPosix;

function requireConvertPathToPosix () {
	if (hasRequiredConvertPathToPosix) return convertPathToPosix;
	hasRequiredConvertPathToPosix = 1;
	var __importDefault = (convertPathToPosix.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(convertPathToPosix, "__esModule", { value: true });
	convertPathToPosix.default = convertPathToPosix$1;
	const path_1 = __importDefault(requirePathBrowserify());
	function convertPathToPosix$1(filePath) {
	    const isExtendedLengthPath = filePath.startsWith("\\\\?\\");
	    if (isExtendedLengthPath) {
	        return filePath;
	    }
	    return filePath.split(path_1.default?.win32?.sep).join(path_1.default?.posix?.sep ?? "/");
	}
	return convertPathToPosix;
}

var isWindows = {};

var hasRequiredIsWindows;

function requireIsWindows () {
	if (hasRequiredIsWindows) return isWindows;
	hasRequiredIsWindows = 1;
	Object.defineProperty(isWindows, "__esModule", { value: true });
	isWindows.isWindows = undefined;
	const isWindowsConst = /^win/.test(globalThis.process ? globalThis.process.platform : "");
	const isWindows$1 = () => isWindowsConst;
	isWindows.isWindows = isWindows$1;
	return isWindows;
}

var hasRequiredUrl;

function requireUrl () {
	if (hasRequiredUrl) return url;
	hasRequiredUrl = 1;
	var __createBinding = (url.__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 = (url.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (url.__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 = (url.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(url, "__esModule", { value: true });
	url.parse = undefined;
	url.resolve = resolve;
	url.cwd = cwd;
	url.getProtocol = getProtocol;
	url.getExtension = getExtension;
	url.stripQuery = stripQuery;
	url.getHash = getHash;
	url.stripHash = stripHash;
	url.isHttp = isHttp;
	url.isFileSystemPath = isFileSystemPath;
	url.fromFileSystemPath = fromFileSystemPath;
	url.toFileSystemPath = toFileSystemPath;
	url.safePointerToPath = safePointerToPath;
	url.relative = relative;
	const convert_path_to_posix_1 = __importDefault(requireConvertPathToPosix());
	const path_1 = __importStar(requirePathBrowserify());
	const forwardSlashPattern = /\//g;
	const protocolPattern = /^(\w{2,}):\/\//i;
	const jsonPointerSlash = /~1/g;
	const jsonPointerTilde = /~0/g;
	const path_2 = requirePathBrowserify();
	const is_windows_1 = requireIsWindows();
	// RegExp patterns to URL-encode special characters in local filesystem paths
	const urlEncodePatterns = [
	    [/\?/g, "%3F"],
	    [/#/g, "%23"],
	];
	// RegExp patterns to URL-decode special characters for local filesystem paths
	const urlDecodePatterns = [/%23/g, "#", /%24/g, "$", /%26/g, "&", /%2C/g, ",", /%40/g, "@"];
	const parse = (u) => new URL(u);
	url.parse = parse;
	/**
	 * Returns resolved target URL relative to a base URL in a manner similar to that of a Web browser resolving an anchor tag HREF.
	 *
	 * @returns
	 */
	function resolve(from, to) {
	    const fromUrl = new URL((0, convert_path_to_posix_1.default)(from), "resolve://");
	    const resolvedUrl = new URL((0, convert_path_to_posix_1.default)(to), fromUrl);
	    const endSpaces = to.match(/(\s*)$/)?.[1] || "";
	    if (resolvedUrl.protocol === "resolve:") {
	        // `from` is a relative URL.
	        const { pathname, search, hash } = resolvedUrl;
	        return pathname + search + hash + endSpaces;
	    }
	    return resolvedUrl.toString() + endSpaces;
	}
	/**
	 * Returns the current working directory (in Node) or the current page URL (in browsers).
	 *
	 * @returns
	 */
	function cwd() {
	    if (typeof window !== "undefined") {
	        return location.href;
	    }
	    const path = api.cwd();
	    const lastChar = path.slice(-1);
	    if (lastChar === "/" || lastChar === "\\") {
	        return path;
	    }
	    else {
	        return path + "/";
	    }
	}
	/**
	 * Returns the protocol of the given URL, or `undefined` if it has no protocol.
	 *
	 * @param path
	 * @returns
	 */
	function getProtocol(path) {
	    const match = protocolPattern.exec(path || "");
	    if (match) {
	        return match[1].toLowerCase();
	    }
	    return undefined;
	}
	/**
	 * Returns the lowercased file extension of the given URL,
	 * or an empty string if it has no extension.
	 *
	 * @param path
	 * @returns
	 */
	function getExtension(path) {
	    const lastDot = path.lastIndexOf(".");
	    if (lastDot >= 0) {
	        return stripQuery(path.substr(lastDot).toLowerCase());
	    }
	    return "";
	}
	/**
	 * Removes the query, if any, from the given path.
	 *
	 * @param path
	 * @returns
	 */
	function stripQuery(path) {
	    const queryIndex = path.indexOf("?");
	    if (queryIndex >= 0) {
	        path = path.substr(0, queryIndex);
	    }
	    return path;
	}
	/**
	 * Returns the hash (URL fragment), of the given path.
	 * If there is no hash, then the root hash ("#") is returned.
	 *
	 * @param path
	 * @returns
	 */
	function getHash(path) {
	    if (!path) {
	        return "#";
	    }
	    const hashIndex = path.indexOf("#");
	    if (hashIndex >= 0) {
	        return path.substring(hashIndex);
	    }
	    return "#";
	}
	/**
	 * Removes the hash (URL fragment), if any, from the given path.
	 *
	 * @param path
	 * @returns
	 */
	function stripHash(path) {
	    if (!path) {
	        return "";
	    }
	    const hashIndex = path.indexOf("#");
	    if (hashIndex >= 0) {
	        path = path.substring(0, hashIndex);
	    }
	    return path;
	}
	/**
	 * Determines whether the given path is an HTTP(S) URL.
	 *
	 * @param path
	 * @returns
	 */
	function isHttp(path) {
	    const protocol = getProtocol(path);
	    if (protocol === "http" || protocol === "https") {
	        return true;
	    }
	    else if (protocol === undefined) {
	        // There is no protocol.  If we're running in a browser, then assume it's HTTP.
	        return typeof window !== "undefined";
	    }
	    else {
	        // It's some other protocol, such as "ftp://", "mongodb://", etc.
	        return false;
	    }
	}
	/**
	 * Determines whether the given path is a filesystem path.
	 * This includes "file://" URLs.
	 *
	 * @param path
	 * @returns
	 */
	function isFileSystemPath(path) {
	    // @ts-ignore
	    if (typeof window !== "undefined" || (typeof api !== "undefined" && api.browser)) {
	        // We're running in a browser, so assume that all paths are URLs.
	        // This way, even relative paths will be treated as URLs rather than as filesystem paths
	        return false;
	    }
	    const protocol = getProtocol(path);
	    return protocol === undefined || protocol === "file";
	}
	/**
	 * Converts a filesystem path to a properly-encoded URL.
	 *
	 * This is intended to handle situations where JSON Schema $Ref Parser is called
	 * with a filesystem path that contains characters which are not allowed in URLs.
	 *
	 * @example
	 * The following filesystem paths would be converted to the following URLs:
	 *
	 *    <"!@#$%^&*+=?'>.json              ==>   %3C%22!@%23$%25%5E&*+=%3F\'%3E.json
	 *    C:\\My Documents\\File (1).json   ==>   C:/My%20Documents/File%20(1).json
	 *    file://Project #42/file.json      ==>   file://Project%20%2342/file.json
	 *
	 * @param path
	 * @returns
	 */
	function fromFileSystemPath(path) {
	    // Step 1: On Windows, replace backslashes with forward slashes,
	    // rather than encoding them as "%5C"
	    if ((0, is_windows_1.isWindows)()) {
	        const projectDir = cwd();
	        const upperPath = path.toUpperCase();
	        const projectDirPosixPath = (0, convert_path_to_posix_1.default)(projectDir);
	        const posixUpper = projectDirPosixPath.toUpperCase();
	        const hasProjectDir = upperPath.includes(posixUpper);
	        const hasProjectUri = upperPath.includes(posixUpper);
	        const isAbsolutePath = path_1.win32?.isAbsolute(path) ||
	            path.startsWith("http://") ||
	            path.startsWith("https://") ||
	            path.startsWith("file://");
	        if (!(hasProjectDir || hasProjectUri || isAbsolutePath) && !projectDir.startsWith("http")) {
	            path = (0, path_2.join)(projectDir, path);
	        }
	        path = (0, convert_path_to_posix_1.default)(path);
	    }
	    // Step 2: `encodeURI` will take care of MOST characters
	    path = encodeURI(path);
	    // Step 3: Manually encode characters that are not encoded by `encodeURI`.
	    // This includes characters such as "#" and "?", which have special meaning in URLs,
	    // but are just normal characters in a filesystem path.
	    for (const pattern of urlEncodePatterns) {
	        path = path.replace(pattern[0], pattern[1]);
	    }
	    return path;
	}
	/**
	 * Converts a URL to a local filesystem path.
	 */
	function toFileSystemPath(path, keepFileProtocol) {
	    // Step 1: `decodeURI` will decode characters such as Cyrillic characters, spaces, etc.
	    path = decodeURI(path);
	    // Step 2: Manually decode characters that are not decoded by `decodeURI`.
	    // This includes characters such as "#" and "?", which have special meaning in URLs,
	    // but are just normal characters in a filesystem path.
	    for (let i = 0; i < urlDecodePatterns.length; i += 2) {
	        path = path.replace(urlDecodePatterns[i], urlDecodePatterns[i + 1]);
	    }
	    // Step 3: If it's a "file://" URL, then format it consistently
	    // or convert it to a local filesystem path
	    let isFileUrl = path.substr(0, 7).toLowerCase() === "file://";
	    if (isFileUrl) {
	        // Strip-off the protocol, and the initial "/", if there is one
	        path = path[7] === "/" ? path.substr(8) : path.substr(7);
	        // insert a colon (":") after the drive letter on Windows
	        if ((0, is_windows_1.isWindows)() && path[1] === "/") {
	            path = path[0] + ":" + path.substr(1);
	        }
	        if (keepFileProtocol) {
	            // Return the consistently-formatted "file://" URL
	            path = "file:///" + path;
	        }
	        else {
	            // Convert the "file://" URL to a local filesystem path.
	            // On Windows, it will start with something like "C:/".
	            // On Posix, it will start with "/"
	            isFileUrl = false;
	            path = (0, is_windows_1.isWindows)() ? path : "/" + path;
	        }
	    }
	    // Step 4: Normalize Windows paths (unless it's a "file://" URL)
	    if ((0, is_windows_1.isWindows)() && !isFileUrl) {
	        // Replace forward slashes with backslashes
	        path = path.replace(forwardSlashPattern, "\\");
	        // Capitalize the drive letter
	        if (path.substr(1, 2) === ":\\") {
	            path = path[0].toUpperCase() + path.substr(1);
	        }
	    }
	    return path;
	}
	/**
	 * Converts a $ref pointer to a valid JSON Path.
	 *
	 * @param pointer
	 * @returns
	 */
	function safePointerToPath(pointer) {
	    if (pointer.length <= 1 || pointer[0] !== "#" || pointer[1] !== "/") {
	        return [];
	    }
	    return pointer
	        .slice(2)
	        .split("/")
	        .map((value) => {
	        return decodeURIComponent(value).replace(jsonPointerSlash, "/").replace(jsonPointerTilde, "~");
	    });
	}
	function relative(from, to) {
	    if (!isFileSystemPath(from) || !isFileSystemPath(to)) {
	        return resolve(from, to);
	    }
	    const fromDir = path_1.default.dirname(stripHash(from));
	    const toPath = stripHash(to);
	    const result = path_1.default.relative(fromDir, toPath);
	    return result + getHash(to);
	}
	return url;
}

var errors = {};

var hasRequiredErrors;

function requireErrors () {
	if (hasRequiredErrors) return errors;
	hasRequiredErrors = 1;
	Object.defineProperty(errors, "__esModule", { value: true });
	errors.InvalidPointerError = errors.TimeoutError = errors.MissingPointerError = errors.UnmatchedResolverError = errors.ResolverError = errors.UnmatchedParserError = errors.ParserError = errors.JSONParserErrorGroup = errors.JSONParserError = undefined;
	errors.isHandledError = isHandledError;
	errors.normalizeError = normalizeError;
	const ono_1 = require$$6$1;
	const url_js_1 = requireUrl();
	class JSONParserError extends Error {
	    constructor(message, source) {
	        super();
	        this.code = "EUNKNOWN";
	        this.name = "JSONParserError";
	        this.message = message;
	        this.source = source;
	        this.path = null;
	        ono_1.Ono.extend(this);
	    }
	    get footprint() {
	        return `${this.path}+${this.source}+${this.code}+${this.message}`;
	    }
	}
	errors.JSONParserError = JSONParserError;
	class JSONParserErrorGroup extends Error {
	    constructor(parser) {
	        super();
	        this.files = parser;
	        this.name = "JSONParserErrorGroup";
	        this.message = `${this.errors.length} error${this.errors.length > 1 ? "s" : ""} occurred while reading '${(0, url_js_1.toFileSystemPath)(parser.$refs._root$Ref.path)}'`;
	        ono_1.Ono.extend(this);
	    }
	    static getParserErrors(parser) {
	        const errors = [];
	        for (const $ref of Object.values(parser.$refs._$refs)) {
	            if ($ref.errors) {
	                errors.push(...$ref.errors);
	            }
	        }
	        return errors;
	    }
	    get errors() {
	        return JSONParserErrorGroup.getParserErrors(this.files);
	    }
	}
	errors.JSONParserErrorGroup = JSONParserErrorGroup;
	class ParserError extends JSONParserError {
	    constructor(message, source) {
	        super(`Error parsing ${source}: ${message}`, source);
	        this.code = "EPARSER";
	        this.name = "ParserError";
	    }
	}
	errors.ParserError = ParserError;
	class UnmatchedParserError extends JSONParserError {
	    constructor(source) {
	        super(`Could not find parser for "${source}"`, source);
	        this.code = "EUNMATCHEDPARSER";
	        this.name = "UnmatchedParserError";
	    }
	}
	errors.UnmatchedParserError = UnmatchedParserError;
	class ResolverError extends JSONParserError {
	    constructor(ex, source) {
	        super(ex.message || `Error reading file "${source}"`, source);
	        this.code = "ERESOLVER";
	        this.name = "ResolverError";
	        if ("code" in ex) {
	            this.ioErrorCode = String(ex.code);
	        }
	    }
	}
	errors.ResolverError = ResolverError;
	class UnmatchedResolverError extends JSONParserError {
	    constructor(source) {
	        super(`Could not find resolver for "${source}"`, source);
	        this.code = "EUNMATCHEDRESOLVER";
	        this.name = "UnmatchedResolverError";
	    }
	}
	errors.UnmatchedResolverError = UnmatchedResolverError;
	class MissingPointerError extends JSONParserError {
	    constructor(token, path) {
	        super(`Token "${token}" does not exist.`, (0, url_js_1.stripHash)(path));
	        this.code = "EUNMATCHEDRESOLVER";
	        this.name = "MissingPointerError";
	    }
	}
	errors.MissingPointerError = MissingPointerError;
	class TimeoutError extends JSONParserError {
	    constructor(timeout) {
	        super(`Dereferencing timeout reached: ${timeout}ms`);
	        this.code = "ETIMEOUT";
	        this.name = "TimeoutError";
	    }
	}
	errors.TimeoutError = TimeoutError;
	class InvalidPointerError extends JSONParserError {
	    constructor(pointer, path) {
	        super(`Invalid $ref pointer "${pointer}". Pointers must begin with "#/"`, (0, url_js_1.stripHash)(path));
	        this.code = "EUNMATCHEDRESOLVER";
	        this.name = "InvalidPointerError";
	    }
	}
	errors.InvalidPointerError = InvalidPointerError;
	function isHandledError(err) {
	    return err instanceof JSONParserError || err instanceof JSONParserErrorGroup;
	}
	function normalizeError(err) {
	    if (err.path === null) {
	        err.path = [];
	    }
	    return err;
	}
	return errors;
}

var hasRequiredPointer;

function requirePointer () {
	if (hasRequiredPointer) return pointer;
	hasRequiredPointer = 1;
	var __createBinding = (pointer.__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 = (pointer.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (pointer.__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 = (pointer.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(pointer, "__esModule", { value: true });
	const ref_js_1 = __importDefault(requireRef());
	const url = __importStar(requireUrl());
	const errors_js_1 = requireErrors();
	const slashes = /\//g;
	const tildes = /~/g;
	const escapedSlash = /~1/g;
	const escapedTilde = /~0/g;
	const safeDecodeURIComponent = (encodedURIComponent) => {
	    try {
	        return decodeURIComponent(encodedURIComponent);
	    }
	    catch {
	        return encodedURIComponent;
	    }
	};
	/**
	 * This class represents a single JSON pointer and its resolved value.
	 *
	 * @param $ref
	 * @param path
	 * @param [friendlyPath] - The original user-specified path (used for error messages)
	 * @class
	 */
	class Pointer {
	    constructor($ref, path, friendlyPath) {
	        this.$ref = $ref;
	        this.path = path;
	        this.originalPath = friendlyPath || path;
	        this.value = undefined;
	        this.circular = false;
	        this.indirections = 0;
	    }
	    /**
	     * Resolves the value of a nested property within the given object.
	     *
	     * @param obj - The object that will be crawled
	     * @param options
	     * @param pathFromRoot - the path of place that initiated resolving
	     *
	     * @returns
	     * Returns a JSON pointer whose {@link Pointer#value} is the resolved value.
	     * If resolving this value required resolving other JSON references, then
	     * the {@link Pointer#$ref} and {@link Pointer#path} will reflect the resolution path
	     * of the resolved value.
	     */
	    resolve(obj, options, pathFromRoot) {
	        const tokens = Pointer.parse(this.path, this.originalPath);
	        // Crawl the object, one token at a time
	        this.value = unwrapOrThrow(obj);
	        for (let i = 0; i < tokens.length; i++) {
	            if (resolveIf$Ref(this, options, pathFromRoot)) {
	                // The $ref path has changed, so append the remaining tokens to the path
	                this.path = Pointer.join(this.path, tokens.slice(i));
	            }
	            if (typeof this.value === "object" && this.value !== null && !isRootPath(pathFromRoot) && "$ref" in this.value) {
	                return this;
	            }
	            const token = tokens[i];
	            if (this.value[token] === undefined || (this.value[token] === null && i === tokens.length - 1)) {
	                // one final case is if the entry itself includes slashes, and was parsed out as a token - we can join the remaining tokens and try again
	                let didFindSubstringSlashMatch = false;
	                for (let j = tokens.length - 1; j > i; j--) {
	                    const joinedToken = tokens.slice(i, j + 1).join("/");
	                    if (this.value[joinedToken] !== undefined) {
	                        this.value = this.value[joinedToken];
	                        i = j;
	                        didFindSubstringSlashMatch = true;
	                        break;
	                    }
	                }
	                if (didFindSubstringSlashMatch) {
	                    continue;
	                }
	                this.value = null;
	                throw new errors_js_1.MissingPointerError(token, decodeURI(this.originalPath));
	            }
	            else {
	                this.value = this.value[token];
	            }
	        }
	        // Resolve the final value
	        if (!this.value || (this.value.$ref && url.resolve(this.path, this.value.$ref) !== pathFromRoot)) {
	            resolveIf$Ref(this, options, pathFromRoot);
	        }
	        return this;
	    }
	    /**
	     * Sets the value of a nested property within the given object.
	     *
	     * @param obj - The object that will be crawled
	     * @param value - the value to assign
	     * @param options
	     *
	     * @returns
	     * Returns the modified object, or an entirely new object if the entire object is overwritten.
	     */
	    set(obj, value, options) {
	        const tokens = Pointer.parse(this.path);
	        let token;
	        if (tokens.length === 0) {
	            // There are no tokens, replace the entire object with the new value
	            this.value = value;
	            return value;
	        }
	        // Crawl the object, one token at a time
	        this.value = unwrapOrThrow(obj);
	        for (let i = 0; i < tokens.length - 1; i++) {
	            resolveIf$Ref(this, options);
	            token = tokens[i];
	            if (this.value && this.value[token] !== undefined) {
	                // The token exists
	                this.value = this.value[token];
	            }
	            else {
	                // The token doesn't exist, so create it
	                this.value = setValue(this, token, {});
	            }
	        }
	        // Set the value of the final token
	        resolveIf$Ref(this, options);
	        token = tokens[tokens.length - 1];
	        setValue(this, token, value);
	        // Return the updated object
	        return obj;
	    }
	    /**
	     * Parses a JSON pointer (or a path containing a JSON pointer in the hash)
	     * and returns an array of the pointer's tokens.
	     * (e.g. "schema.json#/definitions/person/name" => ["definitions", "person", "name"])
	     *
	     * The pointer is parsed according to RFC 6901
	     * {@link https://tools.ietf.org/html/rfc6901#section-3}
	     *
	     * @param path
	     * @param [originalPath]
	     * @returns
	     */
	    static parse(path, originalPath) {
	        // Get the JSON pointer from the path's hash
	        const pointer = url.getHash(path).substring(1);
	        // If there's no pointer, then there are no tokens,
	        // so return an empty array
	        if (!pointer) {
	            return [];
	        }
	        // Split into an array
	        const split = pointer.split("/");
	        // Decode each part, according to RFC 6901
	        for (let i = 0; i < split.length; i++) {
	            split[i] = safeDecodeURIComponent(split[i].replace(escapedSlash, "/").replace(escapedTilde, "~"));
	        }
	        if (split[0] !== "") {
	            throw new errors_js_1.InvalidPointerError(split, originalPath === undefined ? path : originalPath);
	        }
	        return split.slice(1);
	    }
	    /**
	     * Creates a JSON pointer path, by joining one or more tokens to a base path.
	     *
	     * @param base - The base path (e.g. "schema.json#/definitions/person")
	     * @param tokens - The token(s) to append (e.g. ["name", "first"])
	     * @returns
	     */
	    static join(base, tokens) {
	        // Ensure that the base path contains a hash
	        if (base.indexOf("#") === -1) {
	            base += "#";
	        }
	        // Append each token to the base path
	        tokens = Array.isArray(tokens) ? tokens : [tokens];
	        for (let i = 0; i < tokens.length; i++) {
	            const token = tokens[i];
	            // Encode the token, according to RFC 6901
	            base += "/" + encodeURIComponent(token.replace(tildes, "~0").replace(slashes, "~1"));
	        }
	        return base;
	    }
	}
	/**
	 * If the given pointer's {@link Pointer#value} is a JSON reference,
	 * then the reference is resolved and {@link Pointer#value} is replaced with the resolved value.
	 * In addition, {@link Pointer#path} and {@link Pointer#$ref} are updated to reflect the
	 * resolution path of the new value.
	 *
	 * @param pointer
	 * @param options
	 * @param [pathFromRoot] - the path of place that initiated resolving
	 * @returns - Returns `true` if the resolution path changed
	 */
	function resolveIf$Ref(pointer, options, pathFromRoot) {
	    // Is the value a JSON reference? (and allowed?)
	    if (ref_js_1.default.isAllowed$Ref(pointer.value, options)) {
	        const $refPath = url.resolve(pointer.path, pointer.value.$ref);
	        if ($refPath === pointer.path && !isRootPath(pathFromRoot)) {
	            // The value is a reference to itself, so there's nothing to do.
	            pointer.circular = true;
	        }
	        else {
	            const resolved = pointer.$ref.$refs._resolve($refPath, pointer.path, options);
	            if (resolved === null) {
	                return false;
	            }
	            pointer.indirections += resolved.indirections + 1;
	            if (ref_js_1.default.isExtended$Ref(pointer.value)) {
	                // This JSON reference "extends" the resolved value, rather than simply pointing to it.
	                // So the resolved path does NOT change.  Just the value does.
	                pointer.value = ref_js_1.default.dereference(pointer.value, resolved.value);
	                return false;
	            }
	            else {
	                // Resolve the reference
	                pointer.$ref = resolved.$ref;
	                pointer.path = resolved.path;
	                pointer.value = resolved.value;
	            }
	            return true;
	        }
	    }
	    return undefined;
	}
	pointer.default = Pointer;
	/**
	 * Sets the specified token value of the {@link Pointer#value}.
	 *
	 * The token is evaluated according to RFC 6901.
	 * {@link https://tools.ietf.org/html/rfc6901#section-4}
	 *
	 * @param pointer - The JSON Pointer whose value will be modified
	 * @param token - A JSON Pointer token that indicates how to modify `obj`
	 * @param value - The value to assign
	 * @returns - Returns the assigned value
	 */
	function setValue(pointer, token, value) {
	    if (pointer.value && typeof pointer.value === "object") {
	        if (token === "-" && Array.isArray(pointer.value)) {
	            pointer.value.push(value);
	        }
	        else {
	            pointer.value[token] = value;
	        }
	    }
	    else {
	        throw new errors_js_1.JSONParserError(`Error assigning $ref pointer "${pointer.path}". \nCannot set "${token}" of a non-object.`);
	    }
	    return value;
	}
	function unwrapOrThrow(value) {
	    if ((0, errors_js_1.isHandledError)(value)) {
	        throw value;
	    }
	    return value;
	}
	function isRootPath(pathFromRoot) {
	    return typeof pathFromRoot == "string" && Pointer.parse(pathFromRoot).length == 0;
	}
	return pointer;
}

var hasRequiredRef;

function requireRef () {
	if (hasRequiredRef) return ref;
	hasRequiredRef = 1;
	var __importDefault = (ref.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(ref, "__esModule", { value: true });
	const pointer_js_1 = __importDefault(requirePointer());
	const errors_js_1 = requireErrors();
	const url_js_1 = requireUrl();
	/**
	 * This class represents a single JSON reference and its resolved value.
	 *
	 * @class
	 */
	class $Ref {
	    constructor($refs) {
	        /**
	         * List of all errors. Undefined if no errors.
	         */
	        this.errors = [];
	        this.$refs = $refs;
	    }
	    /**
	     * Pushes an error to errors array.
	     *
	     * @param err - The error to be pushed
	     * @returns
	     */
	    addError(err) {
	        if (this.errors === undefined) {
	            this.errors = [];
	        }
	        const existingErrors = this.errors.map(({ footprint }) => footprint);
	        // the path has been almost certainly set at this point,
	        // but just in case something went wrong, normalizeError injects path if necessary
	        // moreover, certain errors might point at the same spot, so filter them out to reduce noise
	        if ("errors" in err && Array.isArray(err.errors)) {
	            this.errors.push(...err.errors.map(errors_js_1.normalizeError).filter(({ footprint }) => !existingErrors.includes(footprint)));
	        }
	        else if (!("footprint" in err) || !existingErrors.includes(err.footprint)) {
	            this.errors.push((0, errors_js_1.normalizeError)(err));
	        }
	    }
	    /**
	     * Determines whether the given JSON reference exists within this {@link $Ref#value}.
	     *
	     * @param path - The full path being resolved, optionally with a JSON pointer in the hash
	     * @param options
	     * @returns
	     */
	    exists(path, options) {
	        try {
	            this.resolve(path, options);
	            return true;
	        }
	        catch {
	            return false;
	        }
	    }
	    /**
	     * Resolves the given JSON reference within this {@link $Ref#value} and returns the resolved value.
	     *
	     * @param path - The full path being resolved, optionally with a JSON pointer in the hash
	     * @param options
	     * @returns - Returns the resolved value
	     */
	    get(path, options) {
	        return this.resolve(path, options)?.value;
	    }
	    /**
	     * Resolves the given JSON reference within this {@link $Ref#value}.
	     *
	     * @param path - The full path being resolved, optionally with a JSON pointer in the hash
	     * @param options
	     * @param friendlyPath - The original user-specified path (used for error messages)
	     * @param pathFromRoot - The path of `obj` from the schema root
	     * @returns
	     */
	    resolve(path, options, friendlyPath, pathFromRoot) {
	        const pointer = new pointer_js_1.default(this, path, friendlyPath);
	        try {
	            return pointer.resolve(this.value, options, pathFromRoot);
	        }
	        catch (err) {
	            if (!options || !options.continueOnError || !(0, errors_js_1.isHandledError)(err)) {
	                throw err;
	            }
	            if (err.path === null) {
	                err.path = (0, url_js_1.safePointerToPath)((0, url_js_1.getHash)(pathFromRoot));
	            }
	            if (err instanceof errors_js_1.InvalidPointerError) {
	                err.source = decodeURI((0, url_js_1.stripHash)(pathFromRoot));
	            }
	            this.addError(err);
	            return null;
	        }
	    }
	    /**
	     * Sets the value of a nested property within this {@link $Ref#value}.
	     * If the property, or any of its parents don't exist, they will be created.
	     *
	     * @param path - The full path of the property to set, optionally with a JSON pointer in the hash
	     * @param value - The value to assign
	     */
	    set(path, value) {
	        const pointer = new pointer_js_1.default(this, path);
	        this.value = pointer.set(this.value, value);
	    }
	    /**
	     * Determines whether the given value is a JSON reference.
	     *
	     * @param value - The value to inspect
	     * @returns
	     */
	    static is$Ref(value) {
	        return (Boolean(value) &&
	            typeof value === "object" &&
	            value !== null &&
	            "$ref" in value &&
	            typeof value.$ref === "string" &&
	            value.$ref.length > 0);
	    }
	    /**
	     * Determines whether the given value is an external JSON reference.
	     *
	     * @param value - The value to inspect
	     * @returns
	     */
	    static isExternal$Ref(value) {
	        return $Ref.is$Ref(value) && value.$ref[0] !== "#";
	    }
	    /**
	     * Determines whether the given value is a JSON reference, and whether it is allowed by the options.
	     * For example, if it references an external file, then options.resolve.external must be true.
	     *
	     * @param value - The value to inspect
	     * @param options
	     * @returns
	     */
	    static isAllowed$Ref(value, options) {
	        if (this.is$Ref(value)) {
	            if (value.$ref.substring(0, 2) === "#/" || value.$ref === "#") {
	                // It's a JSON Pointer reference, which is always allowed
	                return true;
	            }
	            else if (value.$ref[0] !== "#" && (!options || options.resolve?.external)) {
	                // It's an external reference, which is allowed by the options
	                return true;
	            }
	        }
	        return undefined;
	    }
	    /**
	     * Determines whether the given value is a JSON reference that "extends" its resolved value.
	     * That is, it has extra properties (in addition to "$ref"), so rather than simply pointing to
	     * an existing value, this $ref actually creates a NEW value that is a shallow copy of the resolved
	     * value, plus the extra properties.
	     *
	     * @example: {
	       person: {
	         properties: {
	           firstName: { type: string }
	           lastName: { type: string }
	         }
	       }
	       employee: {
	         properties: {
	           $ref: #/person/properties
	           salary: { type: number }
	         }
	       }
	     }
	     *  In this example, "employee" is an extended $ref, since it extends "person" with an additional
	     *  property (salary).  The result is a NEW value that looks like this:
	     *
	     *  {
	     *    properties: {
	     *      firstName: { type: string }
	     *      lastName: { type: string }
	     *      salary: { type: number }
	     *    }
	     *  }
	     *
	     * @param value - The value to inspect
	     * @returns
	     */
	    static isExtended$Ref(value) {
	        return $Ref.is$Ref(value) && Object.keys(value).length > 1;
	    }
	    /**
	     * Returns the resolved value of a JSON Reference.
	     * If necessary, the resolved value is merged with the JSON Reference to create a new object
	     *
	     * @example: {
	    person: {
	      properties: {
	        firstName: { type: string }
	        lastName: { type: string }
	      }
	    }
	    employee: {
	      properties: {
	        $ref: #/person/properties
	        salary: { type: number }
	      }
	    }
	    } When "person" and "employee" are merged, you end up with the following object:
	     *
	     *  {
	     *    properties: {
	     *      firstName: { type: string }
	     *      lastName: { type: string }
	     *      salary: { type: number }
	     *    }
	     *  }
	     *
	     * @param $ref - The JSON reference object (the one with the "$ref" property)
	     * @param resolvedValue - The resolved value, which can be any type
	     * @returns - Returns the dereferenced value
	     */
	    static dereference($ref, resolvedValue) {
	        if (resolvedValue && typeof resolvedValue === "object" && $Ref.isExtended$Ref($ref)) {
	            const merged = {};
	            for (const key of Object.keys($ref)) {
	                if (key !== "$ref") {
	                    // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
	                    merged[key] = $ref[key];
	                }
	            }
	            for (const key of Object.keys(resolvedValue)) {
	                if (!(key in merged)) {
	                    // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
	                    merged[key] = resolvedValue[key];
	                }
	            }
	            return merged;
	        }
	        else {
	            // Completely replace the original reference with the resolved value
	            return resolvedValue;
	        }
	    }
	}
	ref.default = $Ref;
	return ref;
}

var hasRequiredRefs;

function requireRefs () {
	if (hasRequiredRefs) return refs;
	hasRequiredRefs = 1;
	var __createBinding = (refs.__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 = (refs.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (refs.__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 = (refs.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(refs, "__esModule", { value: true });
	const ono_1 = require$$6$1;
	const ref_js_1 = __importDefault(requireRef());
	const url = __importStar(requireUrl());
	const convert_path_to_posix_1 = __importDefault(requireConvertPathToPosix());
	/**
	 * When you call the resolve method, the value that gets passed to the callback function (or Promise) is a $Refs object. This same object is accessible via the parser.$refs property of $RefParser objects.
	 *
	 * This object is a map of JSON References and their resolved values. It also has several convenient helper methods that make it easy for you to navigate and manipulate the JSON References.
	 *
	 * See https://apitools.dev/json-schema-ref-parser/docs/refs.html
	 */
	class $Refs {
	    /**
	     * Returns the paths/URLs of all the files in your schema (including the main schema file).
	     *
	     * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#pathstypes
	     *
	     * @param types (optional) Optionally only return certain types of paths ("file", "http", etc.)
	     */
	    paths(...types) {
	        const paths = getPaths(this._$refs, types.flat());
	        return paths.map((path) => {
	            return (0, convert_path_to_posix_1.default)(path.decoded);
	        });
	    }
	    /**
	     * Returns a map of paths/URLs and their correspond values.
	     *
	     * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#valuestypes
	     *
	     * @param types (optional) Optionally only return values from certain locations ("file", "http", etc.)
	     */
	    values(...types) {
	        const $refs = this._$refs;
	        const paths = getPaths($refs, types.flat());
	        return paths.reduce((obj, path) => {
	            obj[(0, convert_path_to_posix_1.default)(path.decoded)] = $refs[path.encoded].value;
	            return obj;
	        }, {});
	    }
	    /**
	     * Returns `true` if the given path exists in the schema; otherwise, returns `false`
	     *
	     * See https://apitools.dev/json-schema-ref-parser/docs/refs.html#existsref
	     *
	     * @param $ref The JSON Reference path, optionally with a JSON Pointer in the hash
	     */
	    /**
	     * Determines whether the given JSON reference exists.
	     *
	     * @param path - The path being resolved, optionally with a JSON pointer in the hash
	     * @param [options]
	     * @returns
	     */
	    exists(path, options) {
	        try {
	            this._resolve(path, "", options);
	            return true;
	        }
	        catch {
	            return false;
	        }
	    }
	    /**
	     * Resolves the given JSON reference and returns the resolved value.
	     *
	     * @param path - The path being resolved, with a JSON pointer in the hash
	     * @param [options]
	     * @returns - Returns the resolved value
	     */
	    get(path, options) {
	        return this._resolve(path, "", options).value;
	    }
	    /**
	     * Sets the value at the given path in the schema. If the property, or any of its parents, don't exist, they will be created.
	     *
	     * @param path The JSON Reference path, optionally with a JSON Pointer in the hash
	     * @param value The value to assign. Can be anything (object, string, number, etc.)
	     */
	    set(path, value) {
	        const absPath = url.resolve(this._root$Ref.path, path);
	        const withoutHash = url.stripHash(absPath);
	        const $ref = this._$refs[withoutHash];
	        if (!$ref) {
	            throw (0, ono_1.ono)(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
	        }
	        $ref.set(absPath, value);
	    }
	    /**
	     * Returns the specified {@link $Ref} object, or undefined.
	     *
	     * @param path - The path being resolved, optionally with a JSON pointer in the hash
	     * @returns
	     * @protected
	     */
	    _get$Ref(path) {
	        path = url.resolve(this._root$Ref.path, path);
	        const withoutHash = url.stripHash(path);
	        return this._$refs[withoutHash];
	    }
	    /**
	     * Creates a new {@link $Ref} object and adds it to this {@link $Refs} object.
	     *
	     * @param path  - The file path or URL of the referenced file
	     */
	    _add(path) {
	        const withoutHash = url.stripHash(path);
	        const $ref = new ref_js_1.default(this);
	        $ref.path = withoutHash;
	        this._$refs[withoutHash] = $ref;
	        this._root$Ref = this._root$Ref || $ref;
	        return $ref;
	    }
	    /**
	     * Resolves the given JSON reference.
	     *
	     * @param path - The path being resolved, optionally with a JSON pointer in the hash
	     * @param pathFromRoot - The path of `obj` from the schema root
	     * @param [options]
	     * @returns
	     * @protected
	     */
	    _resolve(path, pathFromRoot, options) {
	        const absPath = url.resolve(this._root$Ref.path, path);
	        const withoutHash = url.stripHash(absPath);
	        const $ref = this._$refs[withoutHash];
	        if (!$ref) {
	            throw (0, ono_1.ono)(`Error resolving $ref pointer "${path}". \n"${withoutHash}" not found.`);
	        }
	        return $ref.resolve(absPath, options, path, pathFromRoot);
	    }
	    constructor() {
	        /**
	         * A map of paths/urls to {@link $Ref} objects
	         *
	         * @type {object}
	         * @protected
	         */
	        this._$refs = {};
	        /**
	         * Returns the paths of all the files/URLs that are referenced by the JSON schema,
	         * including the schema itself.
	         *
	         * @param [types] - Only return paths of the given types ("file", "http", etc.)
	         * @returns
	         */
	        /**
	         * Returns the map of JSON references and their resolved values.
	         *
	         * @param [types] - Only return references of the given types ("file", "http", etc.)
	         * @returns
	         */
	        /**
	         * Returns a POJO (plain old JavaScript object) for serialization as JSON.
	         *
	         * @returns {object}
	         */
	        this.toJSON = this.values;
	        /**
	         * Indicates whether the schema contains any circular references.
	         *
	         * @type {boolean}
	         */
	        this.circular = false;
	        this._$refs = {};
	        // @ts-ignore
	        this._root$Ref = null;
	    }
	}
	refs.default = $Refs;
	/**
	 * Returns the encoded and decoded paths keys of the given object.
	 *
	 * @param $refs - The object whose keys are URL-encoded paths
	 * @param [types] - Only return paths of the given types ("file", "http", etc.)
	 * @returns
	 */
	function getPaths($refs, types) {
	    let paths = Object.keys($refs);
	    // Filter the paths by type
	    types = Array.isArray(types[0]) ? types[0] : Array.prototype.slice.call(types);
	    if (types.length > 0 && types[0]) {
	        paths = paths.filter((key) => {
	            return types.includes($refs[key].pathType);
	        });
	    }
	    // Decode local filesystem paths
	    return paths.map((path) => {
	        return {
	            encoded: path,
	            decoded: $refs[path].pathType === "file" ? url.toFileSystemPath(path, true) : path,
	        };
	    });
	}
	return refs;
}

var parse = {};

var plugins = {};

var hasRequiredPlugins;

function requirePlugins () {
	if (hasRequiredPlugins) return plugins;
	hasRequiredPlugins = 1;
	Object.defineProperty(plugins, "__esModule", { value: true });
	plugins.all = all;
	plugins.filter = filter;
	plugins.sort = sort;
	plugins.run = run;
	/**
	 * Returns the given plugins as an array, rather than an object map.
	 * All other methods in this module expect an array of plugins rather than an object map.
	 *
	 * @returns
	 */
	function all(plugins) {
	    return Object.keys(plugins || {})
	        .filter((key) => {
	        return typeof plugins[key] === "object";
	    })
	        .map((key) => {
	        plugins[key].name = key;
	        return plugins[key];
	    });
	}
	/**
	 * Filters the given plugins, returning only the ones return `true` for the given method.
	 */
	function filter(plugins, method, file) {
	    return plugins.filter((plugin) => {
	        return !!getResult(plugin, method, file);
	    });
	}
	/**
	 * Sorts the given plugins, in place, by their `order` property.
	 */
	function sort(plugins) {
	    for (const plugin of plugins) {
	        plugin.order = plugin.order || Number.MAX_SAFE_INTEGER;
	    }
	    return plugins.sort((a, b) => {
	        return a.order - b.order;
	    });
	}
	/**
	 * Runs the specified method of the given plugins, in order, until one of them returns a successful result.
	 * Each method can return a synchronous value, a Promise, or call an error-first callback.
	 * If the promise resolves successfully, or the callback is called without an error, then the result
	 * is immediately returned and no further plugins are called.
	 * If the promise rejects, or the callback is called with an error, then the next plugin is called.
	 * If ALL plugins fail, then the last error is thrown.
	 */
	async function run(plugins, method, file, $refs) {
	    let plugin;
	    let lastError;
	    let index = 0;
	    return new Promise((resolve, reject) => {
	        runNextPlugin();
	        function runNextPlugin() {
	            plugin = plugins[index++];
	            if (!plugin) {
	                // There are no more functions, so re-throw the last error
	                return reject(lastError);
	            }
	            try {
	                // console.log('  %s', plugin.name);
	                const result = getResult(plugin, method, file, callback, $refs);
	                if (result && typeof result.then === "function") {
	                    // A promise was returned
	                    result.then(onSuccess, onError);
	                }
	                else if (result !== undefined) {
	                    // A synchronous result was returned
	                    onSuccess(result);
	                }
	                else if (index === plugins.length) {
	                    throw new Error("No promise has been returned or callback has been called.");
	                }
	            }
	            catch (e) {
	                onError(e);
	            }
	        }
	        function callback(err, result) {
	            if (err) {
	                onError(err);
	            }
	            else {
	                onSuccess(result);
	            }
	        }
	        function onSuccess(result) {
	            // console.log('    success');
	            resolve({
	                plugin,
	                result,
	            });
	        }
	        function onError(error) {
	            // console.log('    %s', err.message || err);
	            lastError = {
	                plugin,
	                error,
	            };
	            runNextPlugin();
	        }
	    });
	}
	/**
	 * Returns the value of the given property.
	 * If the property is a function, then the result of the function is returned.
	 * If the value is a RegExp, then it will be tested against the file URL.
	 * If the value is an array, then it will be compared against the file extension.
	 */
	function getResult(obj, prop, file, callback, $refs) {
	    const value = obj[prop];
	    if (typeof value === "function") {
	        return value.apply(obj, [file, callback, $refs]);
	    }
	    if (!callback) {
	        // The synchronous plugin functions (canParse and canRead)
	        // allow a "shorthand" syntax, where the user can match
	        // files by RegExp or by file extension.
	        if (value instanceof RegExp) {
	            return value.test(file.url);
	        }
	        else if (typeof value === "string") {
	            return value === file.extension;
	        }
	        else if (Array.isArray(value)) {
	            return value.indexOf(file.extension) !== -1;
	        }
	    }
	    return value;
	}
	return plugins;
}

var hasRequiredParse;

function requireParse () {
	if (hasRequiredParse) return parse;
	hasRequiredParse = 1;
	var __createBinding = (parse.__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 = (parse.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (parse.__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(parse, "__esModule", { value: true });
	const ono_1 = require$$6$1;
	const url = __importStar(requireUrl());
	const plugins = __importStar(requirePlugins());
	const errors_js_1 = requireErrors();
	/**
	 * Reads and parses the specified file path or URL.
	 */
	async function parse$1(path, $refs, options) {
	    // Remove the URL fragment, if any
	    const hashIndex = path.indexOf("#");
	    let hash = "";
	    if (hashIndex >= 0) {
	        hash = path.substring(hashIndex);
	        // Remove the URL fragment, if any
	        path = path.substring(0, hashIndex);
	    }
	    // Add a new $Ref for this file, even though we don't have the value yet.
	    // This ensures that we don't simultaneously read & parse the same file multiple times
	    const $ref = $refs._add(path);
	    // This "file object" will be passed to all resolvers and parsers.
	    const file = {
	        url: path,
	        hash,
	        extension: url.getExtension(path),
	    };
	    // Read the file and then parse the data
	    try {
	        const resolver = await readFile(file, options, $refs);
	        $ref.pathType = resolver.plugin.name;
	        file.data = resolver.result;
	        const parser = await parseFile(file, options, $refs);
	        $ref.value = parser.result;
	        return parser.result;
	    }
	    catch (err) {
	        if ((0, errors_js_1.isHandledError)(err)) {
	            $ref.value = err;
	        }
	        throw err;
	    }
	}
	/**
	 * Reads the given file, using the configured resolver plugins
	 *
	 * @param file           - An object containing information about the referenced file
	 * @param file.url       - The full URL of the referenced file
	 * @param file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
	 * @param options
	 * @param $refs
	 * @returns
	 * The promise resolves with the raw file contents and the resolver that was used.
	 */
	async function readFile(file, options, $refs) {
	    // console.log('Reading %s', file.url);
	    // Find the resolvers that can read this file
	    let resolvers = plugins.all(options.resolve);
	    resolvers = plugins.filter(resolvers, "canRead", file);
	    // Run the resolvers, in order, until one of them succeeds
	    plugins.sort(resolvers);
	    try {
	        const data = await plugins.run(resolvers, "read", file, $refs);
	        return data;
	    }
	    catch (err) {
	        if (!err && options.continueOnError) {
	            // No resolver could be matched
	            throw new errors_js_1.UnmatchedResolverError(file.url);
	        }
	        else if (!err || !("error" in err)) {
	            // Throw a generic, friendly error.
	            throw ono_1.ono.syntax(`Unable to resolve $ref pointer "${file.url}"`);
	        }
	        // Throw the original error, if it's one of our own (user-friendly) errors.
	        else if (err.error instanceof errors_js_1.ResolverError) {
	            throw err.error;
	        }
	        else {
	            throw new errors_js_1.ResolverError(err, file.url);
	        }
	    }
	}
	/**
	 * Parses the given file's contents, using the configured parser plugins.
	 *
	 * @param file           - An object containing information about the referenced file
	 * @param file.url       - The full URL of the referenced file
	 * @param file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
	 * @param file.data      - The file contents. This will be whatever data type was returned by the resolver
	 * @param options
	 * @param $refs
	 *
	 * @returns
	 * The promise resolves with the parsed file contents and the parser that was used.
	 */
	async function parseFile(file, options, $refs) {
	    // Find the parsers that can read this file type.
	    // If none of the parsers are an exact match for this file, then we'll try ALL of them.
	    // This handles situations where the file IS a supported type, just with an unknown extension.
	    const allParsers = plugins.all(options.parse);
	    const filteredParsers = plugins.filter(allParsers, "canParse", file);
	    const parsers = filteredParsers.length > 0 ? filteredParsers : allParsers;
	    // Run the parsers, in order, until one of them succeeds
	    plugins.sort(parsers);
	    try {
	        const parser = await plugins.run(parsers, "parse", file, $refs);
	        if (!parser.plugin.allowEmpty && isEmpty(parser.result)) {
	            throw ono_1.ono.syntax(`Error parsing "${file.url}" as ${parser.plugin.name}. \nParsed value is empty`);
	        }
	        else {
	            return parser;
	        }
	    }
	    catch (err) {
	        if (!err && options.continueOnError) {
	            // No resolver could be matched
	            throw new errors_js_1.UnmatchedParserError(file.url);
	        }
	        else if (err && err.message && err.message.startsWith("Error parsing")) {
	            throw err;
	        }
	        else if (!err || !("error" in err)) {
	            throw ono_1.ono.syntax(`Unable to parse ${file.url}`);
	        }
	        else if (err.error instanceof errors_js_1.ParserError) {
	            throw err.error;
	        }
	        else {
	            throw new errors_js_1.ParserError(err.error.message, file.url);
	        }
	    }
	}
	/**
	 * Determines whether the parsed value is "empty".
	 *
	 * @param value
	 * @returns
	 */
	function isEmpty(value) {
	    return (value === undefined ||
	        (typeof value === "object" && Object.keys(value).length === 0) ||
	        (typeof value === "string" && value.trim().length === 0) ||
	        (Buffer.isBuffer(value) && value.length === 0));
	}
	parse.default = parse$1;
	return parse;
}

var normalizeArgs = {};

var options$1 = {};

var json$1 = {};

var hasRequiredJson$1;

function requireJson$1 () {
	if (hasRequiredJson$1) return json$1;
	hasRequiredJson$1 = 1;
	Object.defineProperty(json$1, "__esModule", { value: true });
	const errors_js_1 = requireErrors();
	json$1.default = {
	    /**
	     * The order that this parser will run, in relation to other parsers.
	     */
	    order: 100,
	    /**
	     * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
	     */
	    allowEmpty: true,
	    /**
	     * Determines whether this parser can parse a given file reference.
	     * Parsers that match will be tried, in order, until one successfully parses the file.
	     * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
	     * every parser will be tried.
	     */
	    canParse: ".json",
	    /**
	     * Allow JSON files with byte order marks (BOM)
	     */
	    allowBOM: true,
	    /**
	     * Parses the given file as JSON
	     */
	    async parse(file) {
	        let data = file.data;
	        if (Buffer.isBuffer(data)) {
	            data = data.toString();
	        }
	        if (typeof data === "string") {
	            if (data.trim().length === 0) {
	                return; // This mirrors the YAML behavior
	            }
	            else {
	                try {
	                    return JSON.parse(data);
	                }
	                catch (e) {
	                    if (this.allowBOM) {
	                        try {
	                            // find the first curly brace
	                            const firstCurlyBrace = data.indexOf("{");
	                            // remove any characters before the first curly brace
	                            data = data.slice(firstCurlyBrace);
	                            return JSON.parse(data);
	                        }
	                        catch (e) {
	                            throw new errors_js_1.ParserError(e.message, file.url);
	                        }
	                    }
	                    throw new errors_js_1.ParserError(e.message, file.url);
	                }
	            }
	        }
	        else {
	            // data is already a JavaScript value (object, array, number, null, NaN, etc.)
	            return data;
	        }
	    },
	};
	return json$1;
}

var yaml = {};

var jsYaml = {};

var loader = {};

var common = {};

var hasRequiredCommon;

function requireCommon () {
	if (hasRequiredCommon) return common;
	hasRequiredCommon = 1;


	function isNothing(subject) {
	  return (typeof subject === 'undefined') || (subject === null);
	}


	function isObject(subject) {
	  return (typeof subject === 'object') && (subject !== null);
	}


	function toArray(sequence) {
	  if (Array.isArray(sequence)) return sequence;
	  else if (isNothing(sequence)) return [];

	  return [ sequence ];
	}


	function extend(target, source) {
	  var index, length, key, sourceKeys;

	  if (source) {
	    sourceKeys = Object.keys(source);

	    for (index = 0, length = sourceKeys.length; index < length; index += 1) {
	      key = sourceKeys[index];
	      target[key] = source[key];
	    }
	  }

	  return target;
	}


	function repeat(string, count) {
	  var result = '', cycle;

	  for (cycle = 0; cycle < count; cycle += 1) {
	    result += string;
	  }

	  return result;
	}


	function isNegativeZero(number) {
	  return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number);
	}


	common.isNothing      = isNothing;
	common.isObject       = isObject;
	common.toArray        = toArray;
	common.repeat         = repeat;
	common.isNegativeZero = isNegativeZero;
	common.extend         = extend;
	return common;
}

var exception;
var hasRequiredException;

function requireException () {
	if (hasRequiredException) return exception;
	hasRequiredException = 1;


	function formatError(exception, compact) {
	  var where = '', message = exception.reason || '(unknown reason)';

	  if (!exception.mark) return message;

	  if (exception.mark.name) {
	    where += 'in "' + exception.mark.name + '" ';
	  }

	  where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')';

	  if (!compact && exception.mark.snippet) {
	    where += '\n\n' + exception.mark.snippet;
	  }

	  return message + ' ' + where;
	}


	function YAMLException(reason, mark) {
	  // Super constructor
	  Error.call(this);

	  this.name = 'YAMLException';
	  this.reason = reason;
	  this.mark = mark;
	  this.message = formatError(this, false);

	  // Include stack trace in error object
	  if (Error.captureStackTrace) {
	    // Chrome and NodeJS
	    Error.captureStackTrace(this, this.constructor);
	  } else {
	    // FF, IE 10+ and Safari 6+. Fallback for others
	    this.stack = (new Error()).stack || '';
	  }
	}


	// Inherit from Error
	YAMLException.prototype = Object.create(Error.prototype);
	YAMLException.prototype.constructor = YAMLException;


	YAMLException.prototype.toString = function toString(compact) {
	  return this.name + ': ' + formatError(this, compact);
	};


	exception = YAMLException;
	return exception;
}

var snippet;
var hasRequiredSnippet;

function requireSnippet () {
	if (hasRequiredSnippet) return snippet;
	hasRequiredSnippet = 1;


	var common = requireCommon();


	// get snippet for a single line, respecting maxLength
	function getLine(buffer, lineStart, lineEnd, position, maxLineLength) {
	  var head = '';
	  var tail = '';
	  var maxHalfLength = Math.floor(maxLineLength / 2) - 1;

	  if (position - lineStart > maxHalfLength) {
	    head = ' ... ';
	    lineStart = position - maxHalfLength + head.length;
	  }

	  if (lineEnd - position > maxHalfLength) {
	    tail = ' ...';
	    lineEnd = position + maxHalfLength - tail.length;
	  }

	  return {
	    str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail,
	    pos: position - lineStart + head.length // relative position
	  };
	}


	function padStart(string, max) {
	  return common.repeat(' ', max - string.length) + string;
	}


	function makeSnippet(mark, options) {
	  options = Object.create(options || null);

	  if (!mark.buffer) return null;

	  if (!options.maxLength) options.maxLength = 79;
	  if (typeof options.indent      !== 'number') options.indent      = 1;
	  if (typeof options.linesBefore !== 'number') options.linesBefore = 3;
	  if (typeof options.linesAfter  !== 'number') options.linesAfter  = 2;

	  var re = /\r?\n|\r|\0/g;
	  var lineStarts = [ 0 ];
	  var lineEnds = [];
	  var match;
	  var foundLineNo = -1;

	  while ((match = re.exec(mark.buffer))) {
	    lineEnds.push(match.index);
	    lineStarts.push(match.index + match[0].length);

	    if (mark.position <= match.index && foundLineNo < 0) {
	      foundLineNo = lineStarts.length - 2;
	    }
	  }

	  if (foundLineNo < 0) foundLineNo = lineStarts.length - 1;

	  var result = '', i, line;
	  var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length;
	  var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3);

	  for (i = 1; i <= options.linesBefore; i++) {
	    if (foundLineNo - i < 0) break;
	    line = getLine(
	      mark.buffer,
	      lineStarts[foundLineNo - i],
	      lineEnds[foundLineNo - i],
	      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]),
	      maxLineLength
	    );
	    result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) +
	      ' | ' + line.str + '\n' + result;
	  }

	  line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength);
	  result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) +
	    ' | ' + line.str + '\n';
	  result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n';

	  for (i = 1; i <= options.linesAfter; i++) {
	    if (foundLineNo + i >= lineEnds.length) break;
	    line = getLine(
	      mark.buffer,
	      lineStarts[foundLineNo + i],
	      lineEnds[foundLineNo + i],
	      mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]),
	      maxLineLength
	    );
	    result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) +
	      ' | ' + line.str + '\n';
	  }

	  return result.replace(/\n$/, '');
	}


	snippet = makeSnippet;
	return snippet;
}

var type;
var hasRequiredType;

function requireType () {
	if (hasRequiredType) return type;
	hasRequiredType = 1;

	var YAMLException = requireException();

	var TYPE_CONSTRUCTOR_OPTIONS = [
	  'kind',
	  'multi',
	  'resolve',
	  'construct',
	  'instanceOf',
	  'predicate',
	  'represent',
	  'representName',
	  'defaultStyle',
	  'styleAliases'
	];

	var YAML_NODE_KINDS = [
	  'scalar',
	  'sequence',
	  'mapping'
	];

	function compileStyleAliases(map) {
	  var result = {};

	  if (map !== null) {
	    Object.keys(map).forEach(function (style) {
	      map[style].forEach(function (alias) {
	        result[String(alias)] = style;
	      });
	    });
	  }

	  return result;
	}

	function Type(tag, options) {
	  options = options || {};

	  Object.keys(options).forEach(function (name) {
	    if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) {
	      throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.');
	    }
	  });

	  // TODO: Add tag format check.
	  this.options       = options; // keep original options in case user wants to extend this type later
	  this.tag           = tag;
	  this.kind          = options['kind']          || null;
	  this.resolve       = options['resolve']       || function () { return true; };
	  this.construct     = options['construct']     || function (data) { return data; };
	  this.instanceOf    = options['instanceOf']    || null;
	  this.predicate     = options['predicate']     || null;
	  this.represent     = options['represent']     || null;
	  this.representName = options['representName'] || null;
	  this.defaultStyle  = options['defaultStyle']  || null;
	  this.multi         = options['multi']         || false;
	  this.styleAliases  = compileStyleAliases(options['styleAliases'] || null);

	  if (YAML_NODE_KINDS.indexOf(this.kind) === -1) {
	    throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.');
	  }
	}

	type = Type;
	return type;
}

var schema$3;
var hasRequiredSchema;

function requireSchema () {
	if (hasRequiredSchema) return schema$3;
	hasRequiredSchema = 1;

	/*eslint-disable max-len*/

	var YAMLException = requireException();
	var Type          = requireType();


	function compileList(schema, name) {
	  var result = [];

	  schema[name].forEach(function (currentType) {
	    var newIndex = result.length;

	    result.forEach(function (previousType, previousIndex) {
	      if (previousType.tag === currentType.tag &&
	          previousType.kind === currentType.kind &&
	          previousType.multi === currentType.multi) {

	        newIndex = previousIndex;
	      }
	    });

	    result[newIndex] = currentType;
	  });

	  return result;
	}


	function compileMap(/* lists... */) {
	  var result = {
	        scalar: {},
	        sequence: {},
	        mapping: {},
	        fallback: {},
	        multi: {
	          scalar: [],
	          sequence: [],
	          mapping: [],
	          fallback: []
	        }
	      }, index, length;

	  function collectType(type) {
	    if (type.multi) {
	      result.multi[type.kind].push(type);
	      result.multi['fallback'].push(type);
	    } else {
	      result[type.kind][type.tag] = result['fallback'][type.tag] = type;
	    }
	  }

	  for (index = 0, length = arguments.length; index < length; index += 1) {
	    arguments[index].forEach(collectType);
	  }
	  return result;
	}


	function Schema(definition) {
	  return this.extend(definition);
	}


	Schema.prototype.extend = function extend(definition) {
	  var implicit = [];
	  var explicit = [];

	  if (definition instanceof Type) {
	    // Schema.extend(type)
	    explicit.push(definition);

	  } else if (Array.isArray(definition)) {
	    // Schema.extend([ type1, type2, ... ])
	    explicit = explicit.concat(definition);

	  } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) {
	    // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] })
	    if (definition.implicit) implicit = implicit.concat(definition.implicit);
	    if (definition.explicit) explicit = explicit.concat(definition.explicit);

	  } else {
	    throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' +
	      'or a schema definition ({ implicit: [...], explicit: [...] })');
	  }

	  implicit.forEach(function (type) {
	    if (!(type instanceof Type)) {
	      throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
	    }

	    if (type.loadKind && type.loadKind !== 'scalar') {
	      throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
	    }

	    if (type.multi) {
	      throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.');
	    }
	  });

	  explicit.forEach(function (type) {
	    if (!(type instanceof Type)) {
	      throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
	    }
	  });

	  var result = Object.create(Schema.prototype);

	  result.implicit = (this.implicit || []).concat(implicit);
	  result.explicit = (this.explicit || []).concat(explicit);

	  result.compiledImplicit = compileList(result, 'implicit');
	  result.compiledExplicit = compileList(result, 'explicit');
	  result.compiledTypeMap  = compileMap(result.compiledImplicit, result.compiledExplicit);

	  return result;
	};


	schema$3 = Schema;
	return schema$3;
}

var str;
var hasRequiredStr;

function requireStr () {
	if (hasRequiredStr) return str;
	hasRequiredStr = 1;

	var Type = requireType();

	str = new Type('tag:yaml.org,2002:str', {
	  kind: 'scalar',
	  construct: function (data) { return data !== null ? data : ''; }
	});
	return str;
}

var seq$1;
var hasRequiredSeq;

function requireSeq () {
	if (hasRequiredSeq) return seq$1;
	hasRequiredSeq = 1;

	var Type = requireType();

	seq$1 = new Type('tag:yaml.org,2002:seq', {
	  kind: 'sequence',
	  construct: function (data) { return data !== null ? data : []; }
	});
	return seq$1;
}

var map$1;
var hasRequiredMap;

function requireMap () {
	if (hasRequiredMap) return map$1;
	hasRequiredMap = 1;

	var Type = requireType();

	map$1 = new Type('tag:yaml.org,2002:map', {
	  kind: 'mapping',
	  construct: function (data) { return data !== null ? data : {}; }
	});
	return map$1;
}

var failsafe;
var hasRequiredFailsafe;

function requireFailsafe () {
	if (hasRequiredFailsafe) return failsafe;
	hasRequiredFailsafe = 1;


	var Schema = requireSchema();


	failsafe = new Schema({
	  explicit: [
	    requireStr(),
	    requireSeq(),
	    requireMap()
	  ]
	});
	return failsafe;
}

var _null;
var hasRequired_null;

function require_null () {
	if (hasRequired_null) return _null;
	hasRequired_null = 1;

	var Type = requireType();

	function resolveYamlNull(data) {
	  if (data === null) return true;

	  var max = data.length;

	  return (max === 1 && data === '~') ||
	         (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL'));
	}

	function constructYamlNull() {
	  return null;
	}

	function isNull(object) {
	  return object === null;
	}

	_null = new Type('tag:yaml.org,2002:null', {
	  kind: 'scalar',
	  resolve: resolveYamlNull,
	  construct: constructYamlNull,
	  predicate: isNull,
	  represent: {
	    canonical: function () { return '~';    },
	    lowercase: function () { return 'null'; },
	    uppercase: function () { return 'NULL'; },
	    camelcase: function () { return 'Null'; },
	    empty:     function () { return '';     }
	  },
	  defaultStyle: 'lowercase'
	});
	return _null;
}

var bool;
var hasRequiredBool;

function requireBool () {
	if (hasRequiredBool) return bool;
	hasRequiredBool = 1;

	var Type = requireType();

	function resolveYamlBoolean(data) {
	  if (data === null) return false;

	  var max = data.length;

	  return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) ||
	         (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE'));
	}

	function constructYamlBoolean(data) {
	  return data === 'true' ||
	         data === 'True' ||
	         data === 'TRUE';
	}

	function isBoolean(object) {
	  return Object.prototype.toString.call(object) === '[object Boolean]';
	}

	bool = new Type('tag:yaml.org,2002:bool', {
	  kind: 'scalar',
	  resolve: resolveYamlBoolean,
	  construct: constructYamlBoolean,
	  predicate: isBoolean,
	  represent: {
	    lowercase: function (object) { return object ? 'true' : 'false'; },
	    uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; },
	    camelcase: function (object) { return object ? 'True' : 'False'; }
	  },
	  defaultStyle: 'lowercase'
	});
	return bool;
}

var int$2;
var hasRequiredInt;

function requireInt () {
	if (hasRequiredInt) return int$2;
	hasRequiredInt = 1;

	var common = requireCommon();
	var Type   = requireType();

	function isHexCode(c) {
	  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) ||
	         ((0x41/* A */ <= c) && (c <= 0x46/* F */)) ||
	         ((0x61/* a */ <= c) && (c <= 0x66/* f */));
	}

	function isOctCode(c) {
	  return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */));
	}

	function isDecCode(c) {
	  return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */));
	}

	function resolveYamlInteger(data) {
	  if (data === null) return false;

	  var max = data.length,
	      index = 0,
	      hasDigits = false,
	      ch;

	  if (!max) return false;

	  ch = data[index];

	  // sign
	  if (ch === '-' || ch === '+') {
	    ch = data[++index];
	  }

	  if (ch === '0') {
	    // 0
	    if (index + 1 === max) return true;
	    ch = data[++index];

	    // base 2, base 8, base 16

	    if (ch === 'b') {
	      // base 2
	      index++;

	      for (; index < max; index++) {
	        ch = data[index];
	        if (ch === '_') continue;
	        if (ch !== '0' && ch !== '1') return false;
	        hasDigits = true;
	      }
	      return hasDigits && ch !== '_';
	    }


	    if (ch === 'x') {
	      // base 16
	      index++;

	      for (; index < max; index++) {
	        ch = data[index];
	        if (ch === '_') continue;
	        if (!isHexCode(data.charCodeAt(index))) return false;
	        hasDigits = true;
	      }
	      return hasDigits && ch !== '_';
	    }


	    if (ch === 'o') {
	      // base 8
	      index++;

	      for (; index < max; index++) {
	        ch = data[index];
	        if (ch === '_') continue;
	        if (!isOctCode(data.charCodeAt(index))) return false;
	        hasDigits = true;
	      }
	      return hasDigits && ch !== '_';
	    }
	  }

	  // base 10 (except 0)

	  // value should not start with `_`;
	  if (ch === '_') return false;

	  for (; index < max; index++) {
	    ch = data[index];
	    if (ch === '_') continue;
	    if (!isDecCode(data.charCodeAt(index))) {
	      return false;
	    }
	    hasDigits = true;
	  }

	  // Should have digits and should not end with `_`
	  if (!hasDigits || ch === '_') return false;

	  return true;
	}

	function constructYamlInteger(data) {
	  var value = data, sign = 1, ch;

	  if (value.indexOf('_') !== -1) {
	    value = value.replace(/_/g, '');
	  }

	  ch = value[0];

	  if (ch === '-' || ch === '+') {
	    if (ch === '-') sign = -1;
	    value = value.slice(1);
	    ch = value[0];
	  }

	  if (value === '0') return 0;

	  if (ch === '0') {
	    if (value[1] === 'b') return sign * parseInt(value.slice(2), 2);
	    if (value[1] === 'x') return sign * parseInt(value.slice(2), 16);
	    if (value[1] === 'o') return sign * parseInt(value.slice(2), 8);
	  }

	  return sign * parseInt(value, 10);
	}

	function isInteger(object) {
	  return (Object.prototype.toString.call(object)) === '[object Number]' &&
	         (object % 1 === 0 && !common.isNegativeZero(object));
	}

	int$2 = new Type('tag:yaml.org,2002:int', {
	  kind: 'scalar',
	  resolve: resolveYamlInteger,
	  construct: constructYamlInteger,
	  predicate: isInteger,
	  represent: {
	    binary:      function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); },
	    octal:       function (obj) { return obj >= 0 ? '0o'  + obj.toString(8) : '-0o'  + obj.toString(8).slice(1); },
	    decimal:     function (obj) { return obj.toString(10); },
	    /* eslint-disable max-len */
	    hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() :  '-0x' + obj.toString(16).toUpperCase().slice(1); }
	  },
	  defaultStyle: 'decimal',
	  styleAliases: {
	    binary:      [ 2,  'bin' ],
	    octal:       [ 8,  'oct' ],
	    decimal:     [ 10, 'dec' ],
	    hexadecimal: [ 16, 'hex' ]
	  }
	});
	return int$2;
}

var float$2;
var hasRequiredFloat;

function requireFloat () {
	if (hasRequiredFloat) return float$2;
	hasRequiredFloat = 1;

	var common = requireCommon();
	var Type   = requireType();

	var YAML_FLOAT_PATTERN = new RegExp(
	  // 2.5e4, 2.5 and integers
	  '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' +
	  // .2e4, .2
	  // special case, seems not from spec
	  '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' +
	  // .inf
	  '|[-+]?\\.(?:inf|Inf|INF)' +
	  // .nan
	  '|\\.(?:nan|NaN|NAN))$');

	function resolveYamlFloat(data) {
	  if (data === null) return false;

	  if (!YAML_FLOAT_PATTERN.test(data) ||
	      // Quick hack to not allow integers end with `_`
	      // Probably should update regexp & check speed
	      data[data.length - 1] === '_') {
	    return false;
	  }

	  return true;
	}

	function constructYamlFloat(data) {
	  var value, sign;

	  value  = data.replace(/_/g, '').toLowerCase();
	  sign   = value[0] === '-' ? -1 : 1;

	  if ('+-'.indexOf(value[0]) >= 0) {
	    value = value.slice(1);
	  }

	  if (value === '.inf') {
	    return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY;

	  } else if (value === '.nan') {
	    return NaN;
	  }
	  return sign * parseFloat(value, 10);
	}


	var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/;

	function representYamlFloat(object, style) {
	  var res;

	  if (isNaN(object)) {
	    switch (style) {
	      case 'lowercase': return '.nan';
	      case 'uppercase': return '.NAN';
	      case 'camelcase': return '.NaN';
	    }
	  } else if (Number.POSITIVE_INFINITY === object) {
	    switch (style) {
	      case 'lowercase': return '.inf';
	      case 'uppercase': return '.INF';
	      case 'camelcase': return '.Inf';
	    }
	  } else if (Number.NEGATIVE_INFINITY === object) {
	    switch (style) {
	      case 'lowercase': return '-.inf';
	      case 'uppercase': return '-.INF';
	      case 'camelcase': return '-.Inf';
	    }
	  } else if (common.isNegativeZero(object)) {
	    return '-0.0';
	  }

	  res = object.toString(10);

	  // JS stringifier can build scientific format without dots: 5e-100,
	  // while YAML requres dot: 5.e-100. Fix it with simple hack

	  return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res;
	}

	function isFloat(object) {
	  return (Object.prototype.toString.call(object) === '[object Number]') &&
	         (object % 1 !== 0 || common.isNegativeZero(object));
	}

	float$2 = new Type('tag:yaml.org,2002:float', {
	  kind: 'scalar',
	  resolve: resolveYamlFloat,
	  construct: constructYamlFloat,
	  predicate: isFloat,
	  represent: representYamlFloat,
	  defaultStyle: 'lowercase'
	});
	return float$2;
}

var json;
var hasRequiredJson;

function requireJson () {
	if (hasRequiredJson) return json;
	hasRequiredJson = 1;


	json = requireFailsafe().extend({
	  implicit: [
	    require_null(),
	    requireBool(),
	    requireInt(),
	    requireFloat()
	  ]
	});
	return json;
}

var core;
var hasRequiredCore;

function requireCore () {
	if (hasRequiredCore) return core;
	hasRequiredCore = 1;


	core = requireJson();
	return core;
}

var timestamp$1;
var hasRequiredTimestamp;

function requireTimestamp () {
	if (hasRequiredTimestamp) return timestamp$1;
	hasRequiredTimestamp = 1;

	var Type = requireType();

	var YAML_DATE_REGEXP = new RegExp(
	  '^([0-9][0-9][0-9][0-9])'          + // [1] year
	  '-([0-9][0-9])'                    + // [2] month
	  '-([0-9][0-9])$');                   // [3] day

	var YAML_TIMESTAMP_REGEXP = new RegExp(
	  '^([0-9][0-9][0-9][0-9])'          + // [1] year
	  '-([0-9][0-9]?)'                   + // [2] month
	  '-([0-9][0-9]?)'                   + // [3] day
	  '(?:[Tt]|[ \\t]+)'                 + // ...
	  '([0-9][0-9]?)'                    + // [4] hour
	  ':([0-9][0-9])'                    + // [5] minute
	  ':([0-9][0-9])'                    + // [6] second
	  '(?:\\.([0-9]*))?'                 + // [7] fraction
	  '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour
	  '(?::([0-9][0-9]))?))?$');           // [11] tz_minute

	function resolveYamlTimestamp(data) {
	  if (data === null) return false;
	  if (YAML_DATE_REGEXP.exec(data) !== null) return true;
	  if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true;
	  return false;
	}

	function constructYamlTimestamp(data) {
	  var match, year, month, day, hour, minute, second, fraction = 0,
	      delta = null, tz_hour, tz_minute, date;

	  match = YAML_DATE_REGEXP.exec(data);
	  if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data);

	  if (match === null) throw new Error('Date resolve error');

	  // match: [1] year [2] month [3] day

	  year = +(match[1]);
	  month = +(match[2]) - 1; // JS month starts with 0
	  day = +(match[3]);

	  if (!match[4]) { // no hour
	    return new Date(Date.UTC(year, month, day));
	  }

	  // match: [4] hour [5] minute [6] second [7] fraction

	  hour = +(match[4]);
	  minute = +(match[5]);
	  second = +(match[6]);

	  if (match[7]) {
	    fraction = match[7].slice(0, 3);
	    while (fraction.length < 3) { // milli-seconds
	      fraction += '0';
	    }
	    fraction = +fraction;
	  }

	  // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute

	  if (match[9]) {
	    tz_hour = +(match[10]);
	    tz_minute = +(match[11] || 0);
	    delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds
	    if (match[9] === '-') delta = -delta;
	  }

	  date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction));

	  if (delta) date.setTime(date.getTime() - delta);

	  return date;
	}

	function representYamlTimestamp(object /*, style*/) {
	  return object.toISOString();
	}

	timestamp$1 = new Type('tag:yaml.org,2002:timestamp', {
	  kind: 'scalar',
	  resolve: resolveYamlTimestamp,
	  construct: constructYamlTimestamp,
	  instanceOf: Date,
	  represent: representYamlTimestamp
	});
	return timestamp$1;
}

var merge$1;
var hasRequiredMerge;

function requireMerge () {
	if (hasRequiredMerge) return merge$1;
	hasRequiredMerge = 1;

	var Type = requireType();

	function resolveYamlMerge(data) {
	  return data === '<<' || data === null;
	}

	merge$1 = new Type('tag:yaml.org,2002:merge', {
	  kind: 'scalar',
	  resolve: resolveYamlMerge
	});
	return merge$1;
}

var binary$2;
var hasRequiredBinary$1;

function requireBinary$1 () {
	if (hasRequiredBinary$1) return binary$2;
	hasRequiredBinary$1 = 1;

	/*eslint-disable no-bitwise*/


	var Type = requireType();


	// [ 64, 65, 66 ] -> [ padding, CR, LF ]
	var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r';


	function resolveYamlBinary(data) {
	  if (data === null) return false;

	  var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP;

	  // Convert one by one.
	  for (idx = 0; idx < max; idx++) {
	    code = map.indexOf(data.charAt(idx));

	    // Skip CR/LF
	    if (code > 64) continue;

	    // Fail on illegal characters
	    if (code < 0) return false;

	    bitlen += 6;
	  }

	  // If there are any bits left, source was corrupted
	  return (bitlen % 8) === 0;
	}

	function constructYamlBinary(data) {
	  var idx, tailbits,
	      input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan
	      max = input.length,
	      map = BASE64_MAP,
	      bits = 0,
	      result = [];

	  // Collect by 6*4 bits (3 bytes)

	  for (idx = 0; idx < max; idx++) {
	    if ((idx % 4 === 0) && idx) {
	      result.push((bits >> 16) & 0xFF);
	      result.push((bits >> 8) & 0xFF);
	      result.push(bits & 0xFF);
	    }

	    bits = (bits << 6) | map.indexOf(input.charAt(idx));
	  }

	  // Dump tail

	  tailbits = (max % 4) * 6;

	  if (tailbits === 0) {
	    result.push((bits >> 16) & 0xFF);
	    result.push((bits >> 8) & 0xFF);
	    result.push(bits & 0xFF);
	  } else if (tailbits === 18) {
	    result.push((bits >> 10) & 0xFF);
	    result.push((bits >> 2) & 0xFF);
	  } else if (tailbits === 12) {
	    result.push((bits >> 4) & 0xFF);
	  }

	  return new Uint8Array(result);
	}

	function representYamlBinary(object /*, style*/) {
	  var result = '', bits = 0, idx, tail,
	      max = object.length,
	      map = BASE64_MAP;

	  // Convert every three bytes to 4 ASCII characters.

	  for (idx = 0; idx < max; idx++) {
	    if ((idx % 3 === 0) && idx) {
	      result += map[(bits >> 18) & 0x3F];
	      result += map[(bits >> 12) & 0x3F];
	      result += map[(bits >> 6) & 0x3F];
	      result += map[bits & 0x3F];
	    }

	    bits = (bits << 8) + object[idx];
	  }

	  // Dump tail

	  tail = max % 3;

	  if (tail === 0) {
	    result += map[(bits >> 18) & 0x3F];
	    result += map[(bits >> 12) & 0x3F];
	    result += map[(bits >> 6) & 0x3F];
	    result += map[bits & 0x3F];
	  } else if (tail === 2) {
	    result += map[(bits >> 10) & 0x3F];
	    result += map[(bits >> 4) & 0x3F];
	    result += map[(bits << 2) & 0x3F];
	    result += map[64];
	  } else if (tail === 1) {
	    result += map[(bits >> 2) & 0x3F];
	    result += map[(bits << 4) & 0x3F];
	    result += map[64];
	    result += map[64];
	  }

	  return result;
	}

	function isBinary(obj) {
	  return Object.prototype.toString.call(obj) ===  '[object Uint8Array]';
	}

	binary$2 = new Type('tag:yaml.org,2002:binary', {
	  kind: 'scalar',
	  resolve: resolveYamlBinary,
	  construct: constructYamlBinary,
	  predicate: isBinary,
	  represent: representYamlBinary
	});
	return binary$2;
}

var omap$1;
var hasRequiredOmap;

function requireOmap () {
	if (hasRequiredOmap) return omap$1;
	hasRequiredOmap = 1;

	var Type = requireType();

	var _hasOwnProperty = Object.prototype.hasOwnProperty;
	var _toString       = Object.prototype.toString;

	function resolveYamlOmap(data) {
	  if (data === null) return true;

	  var objectKeys = [], index, length, pair, pairKey, pairHasKey,
	      object = data;

	  for (index = 0, length = object.length; index < length; index += 1) {
	    pair = object[index];
	    pairHasKey = false;

	    if (_toString.call(pair) !== '[object Object]') return false;

	    for (pairKey in pair) {
	      if (_hasOwnProperty.call(pair, pairKey)) {
	        if (!pairHasKey) pairHasKey = true;
	        else return false;
	      }
	    }

	    if (!pairHasKey) return false;

	    if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey);
	    else return false;
	  }

	  return true;
	}

	function constructYamlOmap(data) {
	  return data !== null ? data : [];
	}

	omap$1 = new Type('tag:yaml.org,2002:omap', {
	  kind: 'sequence',
	  resolve: resolveYamlOmap,
	  construct: constructYamlOmap
	});
	return omap$1;
}

var pairs$1;
var hasRequiredPairs;

function requirePairs () {
	if (hasRequiredPairs) return pairs$1;
	hasRequiredPairs = 1;

	var Type = requireType();

	var _toString = Object.prototype.toString;

	function resolveYamlPairs(data) {
	  if (data === null) return true;

	  var index, length, pair, keys, result,
	      object = data;

	  result = new Array(object.length);

	  for (index = 0, length = object.length; index < length; index += 1) {
	    pair = object[index];

	    if (_toString.call(pair) !== '[object Object]') return false;

	    keys = Object.keys(pair);

	    if (keys.length !== 1) return false;

	    result[index] = [ keys[0], pair[keys[0]] ];
	  }

	  return true;
	}

	function constructYamlPairs(data) {
	  if (data === null) return [];

	  var index, length, pair, keys, result,
	      object = data;

	  result = new Array(object.length);

	  for (index = 0, length = object.length; index < length; index += 1) {
	    pair = object[index];

	    keys = Object.keys(pair);

	    result[index] = [ keys[0], pair[keys[0]] ];
	  }

	  return result;
	}

	pairs$1 = new Type('tag:yaml.org,2002:pairs', {
	  kind: 'sequence',
	  resolve: resolveYamlPairs,
	  construct: constructYamlPairs
	});
	return pairs$1;
}

var set$1;
var hasRequiredSet;

function requireSet () {
	if (hasRequiredSet) return set$1;
	hasRequiredSet = 1;

	var Type = requireType();

	var _hasOwnProperty = Object.prototype.hasOwnProperty;

	function resolveYamlSet(data) {
	  if (data === null) return true;

	  var key, object = data;

	  for (key in object) {
	    if (_hasOwnProperty.call(object, key)) {
	      if (object[key] !== null) return false;
	    }
	  }

	  return true;
	}

	function constructYamlSet(data) {
	  return data !== null ? data : {};
	}

	set$1 = new Type('tag:yaml.org,2002:set', {
	  kind: 'mapping',
	  resolve: resolveYamlSet,
	  construct: constructYamlSet
	});
	return set$1;
}

var _default;
var hasRequired_default;

function require_default () {
	if (hasRequired_default) return _default;
	hasRequired_default = 1;


	_default = requireCore().extend({
	  implicit: [
	    requireTimestamp(),
	    requireMerge()
	  ],
	  explicit: [
	    requireBinary$1(),
	    requireOmap(),
	    requirePairs(),
	    requireSet()
	  ]
	});
	return _default;
}

var hasRequiredLoader;

function requireLoader () {
	if (hasRequiredLoader) return loader;
	hasRequiredLoader = 1;

	/*eslint-disable max-len,no-use-before-define*/

	var common              = requireCommon();
	var YAMLException       = requireException();
	var makeSnippet         = requireSnippet();
	var DEFAULT_SCHEMA      = require_default();


	var _hasOwnProperty = Object.prototype.hasOwnProperty;


	var CONTEXT_FLOW_IN   = 1;
	var CONTEXT_FLOW_OUT  = 2;
	var CONTEXT_BLOCK_IN  = 3;
	var CONTEXT_BLOCK_OUT = 4;


	var CHOMPING_CLIP  = 1;
	var CHOMPING_STRIP = 2;
	var CHOMPING_KEEP  = 3;


	var PATTERN_NON_PRINTABLE         = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
	var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/;
	var PATTERN_FLOW_INDICATORS       = /[,\[\]\{\}]/;
	var PATTERN_TAG_HANDLE            = /^(?:!|!!|![a-z\-]+!)$/i;
	var PATTERN_TAG_URI               = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;


	function _class(obj) { return Object.prototype.toString.call(obj); }

	function is_EOL(c) {
	  return (c === 0x0A/* LF */) || (c === 0x0D/* CR */);
	}

	function is_WHITE_SPACE(c) {
	  return (c === 0x09/* Tab */) || (c === 0x20/* Space */);
	}

	function is_WS_OR_EOL(c) {
	  return (c === 0x09/* Tab */) ||
	         (c === 0x20/* Space */) ||
	         (c === 0x0A/* LF */) ||
	         (c === 0x0D/* CR */);
	}

	function is_FLOW_INDICATOR(c) {
	  return c === 0x2C/* , */ ||
	         c === 0x5B/* [ */ ||
	         c === 0x5D/* ] */ ||
	         c === 0x7B/* { */ ||
	         c === 0x7D/* } */;
	}

	function fromHexCode(c) {
	  var lc;

	  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
	    return c - 0x30;
	  }

	  /*eslint-disable no-bitwise*/
	  lc = c | 0x20;

	  if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) {
	    return lc - 0x61 + 10;
	  }

	  return -1;
	}

	function escapedHexLen(c) {
	  if (c === 0x78/* x */) { return 2; }
	  if (c === 0x75/* u */) { return 4; }
	  if (c === 0x55/* U */) { return 8; }
	  return 0;
	}

	function fromDecimalCode(c) {
	  if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) {
	    return c - 0x30;
	  }

	  return -1;
	}

	function simpleEscapeSequence(c) {
	  /* eslint-disable indent */
	  return (c === 0x30/* 0 */) ? '\x00' :
	        (c === 0x61/* a */) ? '\x07' :
	        (c === 0x62/* b */) ? '\x08' :
	        (c === 0x74/* t */) ? '\x09' :
	        (c === 0x09/* Tab */) ? '\x09' :
	        (c === 0x6E/* n */) ? '\x0A' :
	        (c === 0x76/* v */) ? '\x0B' :
	        (c === 0x66/* f */) ? '\x0C' :
	        (c === 0x72/* r */) ? '\x0D' :
	        (c === 0x65/* e */) ? '\x1B' :
	        (c === 0x20/* Space */) ? ' ' :
	        (c === 0x22/* " */) ? '\x22' :
	        (c === 0x2F/* / */) ? '/' :
	        (c === 0x5C/* \ */) ? '\x5C' :
	        (c === 0x4E/* N */) ? '\x85' :
	        (c === 0x5F/* _ */) ? '\xA0' :
	        (c === 0x4C/* L */) ? '\u2028' :
	        (c === 0x50/* P */) ? '\u2029' : '';
	}

	function charFromCodepoint(c) {
	  if (c <= 0xFFFF) {
	    return String.fromCharCode(c);
	  }
	  // Encode UTF-16 surrogate pair
	  // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF
	  return String.fromCharCode(
	    ((c - 0x010000) >> 10) + 0xD800,
	    ((c - 0x010000) & 0x03FF) + 0xDC00
	  );
	}

	var simpleEscapeCheck = new Array(256); // integer, for fast access
	var simpleEscapeMap = new Array(256);
	for (var i = 0; i < 256; i++) {
	  simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0;
	  simpleEscapeMap[i] = simpleEscapeSequence(i);
	}


	function State(input, options) {
	  this.input = input;

	  this.filename  = options['filename']  || null;
	  this.schema    = options['schema']    || DEFAULT_SCHEMA;
	  this.onWarning = options['onWarning'] || null;
	  // (Hidden) Remove? makes the loader to expect YAML 1.1 documents
	  // if such documents have no explicit %YAML directive
	  this.legacy    = options['legacy']    || false;

	  this.json      = options['json']      || false;
	  this.listener  = options['listener']  || null;

	  this.implicitTypes = this.schema.compiledImplicit;
	  this.typeMap       = this.schema.compiledTypeMap;

	  this.length     = input.length;
	  this.position   = 0;
	  this.line       = 0;
	  this.lineStart  = 0;
	  this.lineIndent = 0;

	  // position of first leading tab in the current line,
	  // used to make sure there are no tabs in the indentation
	  this.firstTabInLine = -1;

	  this.documents = [];

	  /*
	  this.version;
	  this.checkLineBreaks;
	  this.tagMap;
	  this.anchorMap;
	  this.tag;
	  this.anchor;
	  this.kind;
	  this.result;*/

	}


	function generateError(state, message) {
	  var mark = {
	    name:     state.filename,
	    buffer:   state.input.slice(0, -1), // omit trailing \0
	    position: state.position,
	    line:     state.line,
	    column:   state.position - state.lineStart
	  };

	  mark.snippet = makeSnippet(mark);

	  return new YAMLException(message, mark);
	}

	function throwError(state, message) {
	  throw generateError(state, message);
	}

	function throwWarning(state, message) {
	  if (state.onWarning) {
	    state.onWarning.call(null, generateError(state, message));
	  }
	}


	var directiveHandlers = {

	  YAML: function handleYamlDirective(state, name, args) {

	    var match, major, minor;

	    if (state.version !== null) {
	      throwError(state, 'duplication of %YAML directive');
	    }

	    if (args.length !== 1) {
	      throwError(state, 'YAML directive accepts exactly one argument');
	    }

	    match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]);

	    if (match === null) {
	      throwError(state, 'ill-formed argument of the YAML directive');
	    }

	    major = parseInt(match[1], 10);
	    minor = parseInt(match[2], 10);

	    if (major !== 1) {
	      throwError(state, 'unacceptable YAML version of the document');
	    }

	    state.version = args[0];
	    state.checkLineBreaks = (minor < 2);

	    if (minor !== 1 && minor !== 2) {
	      throwWarning(state, 'unsupported YAML version of the document');
	    }
	  },

	  TAG: function handleTagDirective(state, name, args) {

	    var handle, prefix;

	    if (args.length !== 2) {
	      throwError(state, 'TAG directive accepts exactly two arguments');
	    }

	    handle = args[0];
	    prefix = args[1];

	    if (!PATTERN_TAG_HANDLE.test(handle)) {
	      throwError(state, 'ill-formed tag handle (first argument) of the TAG directive');
	    }

	    if (_hasOwnProperty.call(state.tagMap, handle)) {
	      throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle');
	    }

	    if (!PATTERN_TAG_URI.test(prefix)) {
	      throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive');
	    }

	    try {
	      prefix = decodeURIComponent(prefix);
	    } catch (err) {
	      throwError(state, 'tag prefix is malformed: ' + prefix);
	    }

	    state.tagMap[handle] = prefix;
	  }
	};


	function captureSegment(state, start, end, checkJson) {
	  var _position, _length, _character, _result;

	  if (start < end) {
	    _result = state.input.slice(start, end);

	    if (checkJson) {
	      for (_position = 0, _length = _result.length; _position < _length; _position += 1) {
	        _character = _result.charCodeAt(_position);
	        if (!(_character === 0x09 ||
	              (0x20 <= _character && _character <= 0x10FFFF))) {
	          throwError(state, 'expected valid JSON character');
	        }
	      }
	    } else if (PATTERN_NON_PRINTABLE.test(_result)) {
	      throwError(state, 'the stream contains non-printable characters');
	    }

	    state.result += _result;
	  }
	}

	function mergeMappings(state, destination, source, overridableKeys) {
	  var sourceKeys, key, index, quantity;

	  if (!common.isObject(source)) {
	    throwError(state, 'cannot merge mappings; the provided source object is unacceptable');
	  }

	  sourceKeys = Object.keys(source);

	  for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) {
	    key = sourceKeys[index];

	    if (!_hasOwnProperty.call(destination, key)) {
	      destination[key] = source[key];
	      overridableKeys[key] = true;
	    }
	  }
	}

	function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode,
	  startLine, startLineStart, startPos) {

	  var index, quantity;

	  // The output is a plain object here, so keys can only be strings.
	  // We need to convert keyNode to a string, but doing so can hang the process
	  // (deeply nested arrays that explode exponentially using aliases).
	  if (Array.isArray(keyNode)) {
	    keyNode = Array.prototype.slice.call(keyNode);

	    for (index = 0, quantity = keyNode.length; index < quantity; index += 1) {
	      if (Array.isArray(keyNode[index])) {
	        throwError(state, 'nested arrays are not supported inside keys');
	      }

	      if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') {
	        keyNode[index] = '[object Object]';
	      }
	    }
	  }

	  // Avoid code execution in load() via toString property
	  // (still use its own toString for arrays, timestamps,
	  // and whatever user schema extensions happen to have @@toStringTag)
	  if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') {
	    keyNode = '[object Object]';
	  }


	  keyNode = String(keyNode);

	  if (_result === null) {
	    _result = {};
	  }

	  if (keyTag === 'tag:yaml.org,2002:merge') {
	    if (Array.isArray(valueNode)) {
	      for (index = 0, quantity = valueNode.length; index < quantity; index += 1) {
	        mergeMappings(state, _result, valueNode[index], overridableKeys);
	      }
	    } else {
	      mergeMappings(state, _result, valueNode, overridableKeys);
	    }
	  } else {
	    if (!state.json &&
	        !_hasOwnProperty.call(overridableKeys, keyNode) &&
	        _hasOwnProperty.call(_result, keyNode)) {
	      state.line = startLine || state.line;
	      state.lineStart = startLineStart || state.lineStart;
	      state.position = startPos || state.position;
	      throwError(state, 'duplicated mapping key');
	    }

	    // used for this specific key only because Object.defineProperty is slow
	    if (keyNode === '__proto__') {
	      Object.defineProperty(_result, keyNode, {
	        configurable: true,
	        enumerable: true,
	        writable: true,
	        value: valueNode
	      });
	    } else {
	      _result[keyNode] = valueNode;
	    }
	    delete overridableKeys[keyNode];
	  }

	  return _result;
	}

	function readLineBreak(state) {
	  var ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch === 0x0A/* LF */) {
	    state.position++;
	  } else if (ch === 0x0D/* CR */) {
	    state.position++;
	    if (state.input.charCodeAt(state.position) === 0x0A/* LF */) {
	      state.position++;
	    }
	  } else {
	    throwError(state, 'a line break is expected');
	  }

	  state.line += 1;
	  state.lineStart = state.position;
	  state.firstTabInLine = -1;
	}

	function skipSeparationSpace(state, allowComments, checkIndent) {
	  var lineBreaks = 0,
	      ch = state.input.charCodeAt(state.position);

	  while (ch !== 0) {
	    while (is_WHITE_SPACE(ch)) {
	      if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) {
	        state.firstTabInLine = state.position;
	      }
	      ch = state.input.charCodeAt(++state.position);
	    }

	    if (allowComments && ch === 0x23/* # */) {
	      do {
	        ch = state.input.charCodeAt(++state.position);
	      } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0);
	    }

	    if (is_EOL(ch)) {
	      readLineBreak(state);

	      ch = state.input.charCodeAt(state.position);
	      lineBreaks++;
	      state.lineIndent = 0;

	      while (ch === 0x20/* Space */) {
	        state.lineIndent++;
	        ch = state.input.charCodeAt(++state.position);
	      }
	    } else {
	      break;
	    }
	  }

	  if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) {
	    throwWarning(state, 'deficient indentation');
	  }

	  return lineBreaks;
	}

	function testDocumentSeparator(state) {
	  var _position = state.position,
	      ch;

	  ch = state.input.charCodeAt(_position);

	  // Condition state.position === state.lineStart is tested
	  // in parent on each call, for efficiency. No needs to test here again.
	  if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) &&
	      ch === state.input.charCodeAt(_position + 1) &&
	      ch === state.input.charCodeAt(_position + 2)) {

	    _position += 3;

	    ch = state.input.charCodeAt(_position);

	    if (ch === 0 || is_WS_OR_EOL(ch)) {
	      return true;
	    }
	  }

	  return false;
	}

	function writeFoldedLines(state, count) {
	  if (count === 1) {
	    state.result += ' ';
	  } else if (count > 1) {
	    state.result += common.repeat('\n', count - 1);
	  }
	}


	function readPlainScalar(state, nodeIndent, withinFlowCollection) {
	  var preceding,
	      following,
	      captureStart,
	      captureEnd,
	      hasPendingContent,
	      _line,
	      _lineStart,
	      _lineIndent,
	      _kind = state.kind,
	      _result = state.result,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (is_WS_OR_EOL(ch)      ||
	      is_FLOW_INDICATOR(ch) ||
	      ch === 0x23/* # */    ||
	      ch === 0x26/* & */    ||
	      ch === 0x2A/* * */    ||
	      ch === 0x21/* ! */    ||
	      ch === 0x7C/* | */    ||
	      ch === 0x3E/* > */    ||
	      ch === 0x27/* ' */    ||
	      ch === 0x22/* " */    ||
	      ch === 0x25/* % */    ||
	      ch === 0x40/* @ */    ||
	      ch === 0x60/* ` */) {
	    return false;
	  }

	  if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) {
	    following = state.input.charCodeAt(state.position + 1);

	    if (is_WS_OR_EOL(following) ||
	        withinFlowCollection && is_FLOW_INDICATOR(following)) {
	      return false;
	    }
	  }

	  state.kind = 'scalar';
	  state.result = '';
	  captureStart = captureEnd = state.position;
	  hasPendingContent = false;

	  while (ch !== 0) {
	    if (ch === 0x3A/* : */) {
	      following = state.input.charCodeAt(state.position + 1);

	      if (is_WS_OR_EOL(following) ||
	          withinFlowCollection && is_FLOW_INDICATOR(following)) {
	        break;
	      }

	    } else if (ch === 0x23/* # */) {
	      preceding = state.input.charCodeAt(state.position - 1);

	      if (is_WS_OR_EOL(preceding)) {
	        break;
	      }

	    } else if ((state.position === state.lineStart && testDocumentSeparator(state)) ||
	               withinFlowCollection && is_FLOW_INDICATOR(ch)) {
	      break;

	    } else if (is_EOL(ch)) {
	      _line = state.line;
	      _lineStart = state.lineStart;
	      _lineIndent = state.lineIndent;
	      skipSeparationSpace(state, false, -1);

	      if (state.lineIndent >= nodeIndent) {
	        hasPendingContent = true;
	        ch = state.input.charCodeAt(state.position);
	        continue;
	      } else {
	        state.position = captureEnd;
	        state.line = _line;
	        state.lineStart = _lineStart;
	        state.lineIndent = _lineIndent;
	        break;
	      }
	    }

	    if (hasPendingContent) {
	      captureSegment(state, captureStart, captureEnd, false);
	      writeFoldedLines(state, state.line - _line);
	      captureStart = captureEnd = state.position;
	      hasPendingContent = false;
	    }

	    if (!is_WHITE_SPACE(ch)) {
	      captureEnd = state.position + 1;
	    }

	    ch = state.input.charCodeAt(++state.position);
	  }

	  captureSegment(state, captureStart, captureEnd, false);

	  if (state.result) {
	    return true;
	  }

	  state.kind = _kind;
	  state.result = _result;
	  return false;
	}

	function readSingleQuotedScalar(state, nodeIndent) {
	  var ch,
	      captureStart, captureEnd;

	  ch = state.input.charCodeAt(state.position);

	  if (ch !== 0x27/* ' */) {
	    return false;
	  }

	  state.kind = 'scalar';
	  state.result = '';
	  state.position++;
	  captureStart = captureEnd = state.position;

	  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
	    if (ch === 0x27/* ' */) {
	      captureSegment(state, captureStart, state.position, true);
	      ch = state.input.charCodeAt(++state.position);

	      if (ch === 0x27/* ' */) {
	        captureStart = state.position;
	        state.position++;
	        captureEnd = state.position;
	      } else {
	        return true;
	      }

	    } else if (is_EOL(ch)) {
	      captureSegment(state, captureStart, captureEnd, true);
	      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
	      captureStart = captureEnd = state.position;

	    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
	      throwError(state, 'unexpected end of the document within a single quoted scalar');

	    } else {
	      state.position++;
	      captureEnd = state.position;
	    }
	  }

	  throwError(state, 'unexpected end of the stream within a single quoted scalar');
	}

	function readDoubleQuotedScalar(state, nodeIndent) {
	  var captureStart,
	      captureEnd,
	      hexLength,
	      hexResult,
	      tmp,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch !== 0x22/* " */) {
	    return false;
	  }

	  state.kind = 'scalar';
	  state.result = '';
	  state.position++;
	  captureStart = captureEnd = state.position;

	  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
	    if (ch === 0x22/* " */) {
	      captureSegment(state, captureStart, state.position, true);
	      state.position++;
	      return true;

	    } else if (ch === 0x5C/* \ */) {
	      captureSegment(state, captureStart, state.position, true);
	      ch = state.input.charCodeAt(++state.position);

	      if (is_EOL(ch)) {
	        skipSeparationSpace(state, false, nodeIndent);

	        // TODO: rework to inline fn with no type cast?
	      } else if (ch < 256 && simpleEscapeCheck[ch]) {
	        state.result += simpleEscapeMap[ch];
	        state.position++;

	      } else if ((tmp = escapedHexLen(ch)) > 0) {
	        hexLength = tmp;
	        hexResult = 0;

	        for (; hexLength > 0; hexLength--) {
	          ch = state.input.charCodeAt(++state.position);

	          if ((tmp = fromHexCode(ch)) >= 0) {
	            hexResult = (hexResult << 4) + tmp;

	          } else {
	            throwError(state, 'expected hexadecimal character');
	          }
	        }

	        state.result += charFromCodepoint(hexResult);

	        state.position++;

	      } else {
	        throwError(state, 'unknown escape sequence');
	      }

	      captureStart = captureEnd = state.position;

	    } else if (is_EOL(ch)) {
	      captureSegment(state, captureStart, captureEnd, true);
	      writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent));
	      captureStart = captureEnd = state.position;

	    } else if (state.position === state.lineStart && testDocumentSeparator(state)) {
	      throwError(state, 'unexpected end of the document within a double quoted scalar');

	    } else {
	      state.position++;
	      captureEnd = state.position;
	    }
	  }

	  throwError(state, 'unexpected end of the stream within a double quoted scalar');
	}

	function readFlowCollection(state, nodeIndent) {
	  var readNext = true,
	      _line,
	      _lineStart,
	      _pos,
	      _tag     = state.tag,
	      _result,
	      _anchor  = state.anchor,
	      following,
	      terminator,
	      isPair,
	      isExplicitPair,
	      isMapping,
	      overridableKeys = Object.create(null),
	      keyNode,
	      keyTag,
	      valueNode,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch === 0x5B/* [ */) {
	    terminator = 0x5D;/* ] */
	    isMapping = false;
	    _result = [];
	  } else if (ch === 0x7B/* { */) {
	    terminator = 0x7D;/* } */
	    isMapping = true;
	    _result = {};
	  } else {
	    return false;
	  }

	  if (state.anchor !== null) {
	    state.anchorMap[state.anchor] = _result;
	  }

	  ch = state.input.charCodeAt(++state.position);

	  while (ch !== 0) {
	    skipSeparationSpace(state, true, nodeIndent);

	    ch = state.input.charCodeAt(state.position);

	    if (ch === terminator) {
	      state.position++;
	      state.tag = _tag;
	      state.anchor = _anchor;
	      state.kind = isMapping ? 'mapping' : 'sequence';
	      state.result = _result;
	      return true;
	    } else if (!readNext) {
	      throwError(state, 'missed comma between flow collection entries');
	    } else if (ch === 0x2C/* , */) {
	      // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4
	      throwError(state, "expected the node content, but found ','");
	    }

	    keyTag = keyNode = valueNode = null;
	    isPair = isExplicitPair = false;

	    if (ch === 0x3F/* ? */) {
	      following = state.input.charCodeAt(state.position + 1);

	      if (is_WS_OR_EOL(following)) {
	        isPair = isExplicitPair = true;
	        state.position++;
	        skipSeparationSpace(state, true, nodeIndent);
	      }
	    }

	    _line = state.line; // Save the current line.
	    _lineStart = state.lineStart;
	    _pos = state.position;
	    composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
	    keyTag = state.tag;
	    keyNode = state.result;
	    skipSeparationSpace(state, true, nodeIndent);

	    ch = state.input.charCodeAt(state.position);

	    if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) {
	      isPair = true;
	      ch = state.input.charCodeAt(++state.position);
	      skipSeparationSpace(state, true, nodeIndent);
	      composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true);
	      valueNode = state.result;
	    }

	    if (isMapping) {
	      storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos);
	    } else if (isPair) {
	      _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos));
	    } else {
	      _result.push(keyNode);
	    }

	    skipSeparationSpace(state, true, nodeIndent);

	    ch = state.input.charCodeAt(state.position);

	    if (ch === 0x2C/* , */) {
	      readNext = true;
	      ch = state.input.charCodeAt(++state.position);
	    } else {
	      readNext = false;
	    }
	  }

	  throwError(state, 'unexpected end of the stream within a flow collection');
	}

	function readBlockScalar(state, nodeIndent) {
	  var captureStart,
	      folding,
	      chomping       = CHOMPING_CLIP,
	      didReadContent = false,
	      detectedIndent = false,
	      textIndent     = nodeIndent,
	      emptyLines     = 0,
	      atMoreIndented = false,
	      tmp,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch === 0x7C/* | */) {
	    folding = false;
	  } else if (ch === 0x3E/* > */) {
	    folding = true;
	  } else {
	    return false;
	  }

	  state.kind = 'scalar';
	  state.result = '';

	  while (ch !== 0) {
	    ch = state.input.charCodeAt(++state.position);

	    if (ch === 0x2B/* + */ || ch === 0x2D/* - */) {
	      if (CHOMPING_CLIP === chomping) {
	        chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP;
	      } else {
	        throwError(state, 'repeat of a chomping mode identifier');
	      }

	    } else if ((tmp = fromDecimalCode(ch)) >= 0) {
	      if (tmp === 0) {
	        throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one');
	      } else if (!detectedIndent) {
	        textIndent = nodeIndent + tmp - 1;
	        detectedIndent = true;
	      } else {
	        throwError(state, 'repeat of an indentation width identifier');
	      }

	    } else {
	      break;
	    }
	  }

	  if (is_WHITE_SPACE(ch)) {
	    do { ch = state.input.charCodeAt(++state.position); }
	    while (is_WHITE_SPACE(ch));

	    if (ch === 0x23/* # */) {
	      do { ch = state.input.charCodeAt(++state.position); }
	      while (!is_EOL(ch) && (ch !== 0));
	    }
	  }

	  while (ch !== 0) {
	    readLineBreak(state);
	    state.lineIndent = 0;

	    ch = state.input.charCodeAt(state.position);

	    while ((!detectedIndent || state.lineIndent < textIndent) &&
	           (ch === 0x20/* Space */)) {
	      state.lineIndent++;
	      ch = state.input.charCodeAt(++state.position);
	    }

	    if (!detectedIndent && state.lineIndent > textIndent) {
	      textIndent = state.lineIndent;
	    }

	    if (is_EOL(ch)) {
	      emptyLines++;
	      continue;
	    }

	    // End of the scalar.
	    if (state.lineIndent < textIndent) {

	      // Perform the chomping.
	      if (chomping === CHOMPING_KEEP) {
	        state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
	      } else if (chomping === CHOMPING_CLIP) {
	        if (didReadContent) { // i.e. only if the scalar is not empty.
	          state.result += '\n';
	        }
	      }

	      // Break this `while` cycle and go to the funciton's epilogue.
	      break;
	    }

	    // Folded style: use fancy rules to handle line breaks.
	    if (folding) {

	      // Lines starting with white space characters (more-indented lines) are not folded.
	      if (is_WHITE_SPACE(ch)) {
	        atMoreIndented = true;
	        // except for the first content line (cf. Example 8.1)
	        state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);

	      // End of more-indented block.
	      } else if (atMoreIndented) {
	        atMoreIndented = false;
	        state.result += common.repeat('\n', emptyLines + 1);

	      // Just one line break - perceive as the same line.
	      } else if (emptyLines === 0) {
	        if (didReadContent) { // i.e. only if we have already read some scalar content.
	          state.result += ' ';
	        }

	      // Several line breaks - perceive as different lines.
	      } else {
	        state.result += common.repeat('\n', emptyLines);
	      }

	    // Literal style: just add exact number of line breaks between content lines.
	    } else {
	      // Keep all line breaks except the header line break.
	      state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines);
	    }

	    didReadContent = true;
	    detectedIndent = true;
	    emptyLines = 0;
	    captureStart = state.position;

	    while (!is_EOL(ch) && (ch !== 0)) {
	      ch = state.input.charCodeAt(++state.position);
	    }

	    captureSegment(state, captureStart, state.position, false);
	  }

	  return true;
	}

	function readBlockSequence(state, nodeIndent) {
	  var _line,
	      _tag      = state.tag,
	      _anchor   = state.anchor,
	      _result   = [],
	      following,
	      detected  = false,
	      ch;

	  // there is a leading tab before this token, so it can't be a block sequence/mapping;
	  // it can still be flow sequence/mapping or a scalar
	  if (state.firstTabInLine !== -1) return false;

	  if (state.anchor !== null) {
	    state.anchorMap[state.anchor] = _result;
	  }

	  ch = state.input.charCodeAt(state.position);

	  while (ch !== 0) {
	    if (state.firstTabInLine !== -1) {
	      state.position = state.firstTabInLine;
	      throwError(state, 'tab characters must not be used in indentation');
	    }

	    if (ch !== 0x2D/* - */) {
	      break;
	    }

	    following = state.input.charCodeAt(state.position + 1);

	    if (!is_WS_OR_EOL(following)) {
	      break;
	    }

	    detected = true;
	    state.position++;

	    if (skipSeparationSpace(state, true, -1)) {
	      if (state.lineIndent <= nodeIndent) {
	        _result.push(null);
	        ch = state.input.charCodeAt(state.position);
	        continue;
	      }
	    }

	    _line = state.line;
	    composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true);
	    _result.push(state.result);
	    skipSeparationSpace(state, true, -1);

	    ch = state.input.charCodeAt(state.position);

	    if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
	      throwError(state, 'bad indentation of a sequence entry');
	    } else if (state.lineIndent < nodeIndent) {
	      break;
	    }
	  }

	  if (detected) {
	    state.tag = _tag;
	    state.anchor = _anchor;
	    state.kind = 'sequence';
	    state.result = _result;
	    return true;
	  }
	  return false;
	}

	function readBlockMapping(state, nodeIndent, flowIndent) {
	  var following,
	      allowCompact,
	      _line,
	      _keyLine,
	      _keyLineStart,
	      _keyPos,
	      _tag          = state.tag,
	      _anchor       = state.anchor,
	      _result       = {},
	      overridableKeys = Object.create(null),
	      keyTag        = null,
	      keyNode       = null,
	      valueNode     = null,
	      atExplicitKey = false,
	      detected      = false,
	      ch;

	  // there is a leading tab before this token, so it can't be a block sequence/mapping;
	  // it can still be flow sequence/mapping or a scalar
	  if (state.firstTabInLine !== -1) return false;

	  if (state.anchor !== null) {
	    state.anchorMap[state.anchor] = _result;
	  }

	  ch = state.input.charCodeAt(state.position);

	  while (ch !== 0) {
	    if (!atExplicitKey && state.firstTabInLine !== -1) {
	      state.position = state.firstTabInLine;
	      throwError(state, 'tab characters must not be used in indentation');
	    }

	    following = state.input.charCodeAt(state.position + 1);
	    _line = state.line; // Save the current line.

	    //
	    // Explicit notation case. There are two separate blocks:
	    // first for the key (denoted by "?") and second for the value (denoted by ":")
	    //
	    if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) {

	      if (ch === 0x3F/* ? */) {
	        if (atExplicitKey) {
	          storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
	          keyTag = keyNode = valueNode = null;
	        }

	        detected = true;
	        atExplicitKey = true;
	        allowCompact = true;

	      } else if (atExplicitKey) {
	        // i.e. 0x3A/* : */ === character after the explicit key.
	        atExplicitKey = false;
	        allowCompact = true;

	      } else {
	        throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line');
	      }

	      state.position += 1;
	      ch = following;

	    //
	    // Implicit notation case. Flow-style node as the key first, then ":", and the value.
	    //
	    } else {
	      _keyLine = state.line;
	      _keyLineStart = state.lineStart;
	      _keyPos = state.position;

	      if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) {
	        // Neither implicit nor explicit notation.
	        // Reading is done. Go to the epilogue.
	        break;
	      }

	      if (state.line === _line) {
	        ch = state.input.charCodeAt(state.position);

	        while (is_WHITE_SPACE(ch)) {
	          ch = state.input.charCodeAt(++state.position);
	        }

	        if (ch === 0x3A/* : */) {
	          ch = state.input.charCodeAt(++state.position);

	          if (!is_WS_OR_EOL(ch)) {
	            throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping');
	          }

	          if (atExplicitKey) {
	            storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
	            keyTag = keyNode = valueNode = null;
	          }

	          detected = true;
	          atExplicitKey = false;
	          allowCompact = false;
	          keyTag = state.tag;
	          keyNode = state.result;

	        } else if (detected) {
	          throwError(state, 'can not read an implicit mapping pair; a colon is missed');

	        } else {
	          state.tag = _tag;
	          state.anchor = _anchor;
	          return true; // Keep the result of `composeNode`.
	        }

	      } else if (detected) {
	        throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key');

	      } else {
	        state.tag = _tag;
	        state.anchor = _anchor;
	        return true; // Keep the result of `composeNode`.
	      }
	    }

	    //
	    // Common reading code for both explicit and implicit notations.
	    //
	    if (state.line === _line || state.lineIndent > nodeIndent) {
	      if (atExplicitKey) {
	        _keyLine = state.line;
	        _keyLineStart = state.lineStart;
	        _keyPos = state.position;
	      }

	      if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) {
	        if (atExplicitKey) {
	          keyNode = state.result;
	        } else {
	          valueNode = state.result;
	        }
	      }

	      if (!atExplicitKey) {
	        storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos);
	        keyTag = keyNode = valueNode = null;
	      }

	      skipSeparationSpace(state, true, -1);
	      ch = state.input.charCodeAt(state.position);
	    }

	    if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) {
	      throwError(state, 'bad indentation of a mapping entry');
	    } else if (state.lineIndent < nodeIndent) {
	      break;
	    }
	  }

	  //
	  // Epilogue.
	  //

	  // Special case: last mapping's node contains only the key in explicit notation.
	  if (atExplicitKey) {
	    storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos);
	  }

	  // Expose the resulting mapping.
	  if (detected) {
	    state.tag = _tag;
	    state.anchor = _anchor;
	    state.kind = 'mapping';
	    state.result = _result;
	  }

	  return detected;
	}

	function readTagProperty(state) {
	  var _position,
	      isVerbatim = false,
	      isNamed    = false,
	      tagHandle,
	      tagName,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch !== 0x21/* ! */) return false;

	  if (state.tag !== null) {
	    throwError(state, 'duplication of a tag property');
	  }

	  ch = state.input.charCodeAt(++state.position);

	  if (ch === 0x3C/* < */) {
	    isVerbatim = true;
	    ch = state.input.charCodeAt(++state.position);

	  } else if (ch === 0x21/* ! */) {
	    isNamed = true;
	    tagHandle = '!!';
	    ch = state.input.charCodeAt(++state.position);

	  } else {
	    tagHandle = '!';
	  }

	  _position = state.position;

	  if (isVerbatim) {
	    do { ch = state.input.charCodeAt(++state.position); }
	    while (ch !== 0 && ch !== 0x3E/* > */);

	    if (state.position < state.length) {
	      tagName = state.input.slice(_position, state.position);
	      ch = state.input.charCodeAt(++state.position);
	    } else {
	      throwError(state, 'unexpected end of the stream within a verbatim tag');
	    }
	  } else {
	    while (ch !== 0 && !is_WS_OR_EOL(ch)) {

	      if (ch === 0x21/* ! */) {
	        if (!isNamed) {
	          tagHandle = state.input.slice(_position - 1, state.position + 1);

	          if (!PATTERN_TAG_HANDLE.test(tagHandle)) {
	            throwError(state, 'named tag handle cannot contain such characters');
	          }

	          isNamed = true;
	          _position = state.position + 1;
	        } else {
	          throwError(state, 'tag suffix cannot contain exclamation marks');
	        }
	      }

	      ch = state.input.charCodeAt(++state.position);
	    }

	    tagName = state.input.slice(_position, state.position);

	    if (PATTERN_FLOW_INDICATORS.test(tagName)) {
	      throwError(state, 'tag suffix cannot contain flow indicator characters');
	    }
	  }

	  if (tagName && !PATTERN_TAG_URI.test(tagName)) {
	    throwError(state, 'tag name cannot contain such characters: ' + tagName);
	  }

	  try {
	    tagName = decodeURIComponent(tagName);
	  } catch (err) {
	    throwError(state, 'tag name is malformed: ' + tagName);
	  }

	  if (isVerbatim) {
	    state.tag = tagName;

	  } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) {
	    state.tag = state.tagMap[tagHandle] + tagName;

	  } else if (tagHandle === '!') {
	    state.tag = '!' + tagName;

	  } else if (tagHandle === '!!') {
	    state.tag = 'tag:yaml.org,2002:' + tagName;

	  } else {
	    throwError(state, 'undeclared tag handle "' + tagHandle + '"');
	  }

	  return true;
	}

	function readAnchorProperty(state) {
	  var _position,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch !== 0x26/* & */) return false;

	  if (state.anchor !== null) {
	    throwError(state, 'duplication of an anchor property');
	  }

	  ch = state.input.charCodeAt(++state.position);
	  _position = state.position;

	  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
	    ch = state.input.charCodeAt(++state.position);
	  }

	  if (state.position === _position) {
	    throwError(state, 'name of an anchor node must contain at least one character');
	  }

	  state.anchor = state.input.slice(_position, state.position);
	  return true;
	}

	function readAlias(state) {
	  var _position, alias,
	      ch;

	  ch = state.input.charCodeAt(state.position);

	  if (ch !== 0x2A/* * */) return false;

	  ch = state.input.charCodeAt(++state.position);
	  _position = state.position;

	  while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) {
	    ch = state.input.charCodeAt(++state.position);
	  }

	  if (state.position === _position) {
	    throwError(state, 'name of an alias node must contain at least one character');
	  }

	  alias = state.input.slice(_position, state.position);

	  if (!_hasOwnProperty.call(state.anchorMap, alias)) {
	    throwError(state, 'unidentified alias "' + alias + '"');
	  }

	  state.result = state.anchorMap[alias];
	  skipSeparationSpace(state, true, -1);
	  return true;
	}

	function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) {
	  var allowBlockStyles,
	      allowBlockScalars,
	      allowBlockCollections,
	      indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this<parent
	      atNewLine  = false,
	      hasContent = false,
	      typeIndex,
	      typeQuantity,
	      typeList,
	      type,
	      flowIndent,
	      blockIndent;

	  if (state.listener !== null) {
	    state.listener('open', state);
	  }

	  state.tag    = null;
	  state.anchor = null;
	  state.kind   = null;
	  state.result = null;

	  allowBlockStyles = allowBlockScalars = allowBlockCollections =
	    CONTEXT_BLOCK_OUT === nodeContext ||
	    CONTEXT_BLOCK_IN  === nodeContext;

	  if (allowToSeek) {
	    if (skipSeparationSpace(state, true, -1)) {
	      atNewLine = true;

	      if (state.lineIndent > parentIndent) {
	        indentStatus = 1;
	      } else if (state.lineIndent === parentIndent) {
	        indentStatus = 0;
	      } else if (state.lineIndent < parentIndent) {
	        indentStatus = -1;
	      }
	    }
	  }

	  if (indentStatus === 1) {
	    while (readTagProperty(state) || readAnchorProperty(state)) {
	      if (skipSeparationSpace(state, true, -1)) {
	        atNewLine = true;
	        allowBlockCollections = allowBlockStyles;

	        if (state.lineIndent > parentIndent) {
	          indentStatus = 1;
	        } else if (state.lineIndent === parentIndent) {
	          indentStatus = 0;
	        } else if (state.lineIndent < parentIndent) {
	          indentStatus = -1;
	        }
	      } else {
	        allowBlockCollections = false;
	      }
	    }
	  }

	  if (allowBlockCollections) {
	    allowBlockCollections = atNewLine || allowCompact;
	  }

	  if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) {
	    if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) {
	      flowIndent = parentIndent;
	    } else {
	      flowIndent = parentIndent + 1;
	    }

	    blockIndent = state.position - state.lineStart;

	    if (indentStatus === 1) {
	      if (allowBlockCollections &&
	          (readBlockSequence(state, blockIndent) ||
	           readBlockMapping(state, blockIndent, flowIndent)) ||
	          readFlowCollection(state, flowIndent)) {
	        hasContent = true;
	      } else {
	        if ((allowBlockScalars && readBlockScalar(state, flowIndent)) ||
	            readSingleQuotedScalar(state, flowIndent) ||
	            readDoubleQuotedScalar(state, flowIndent)) {
	          hasContent = true;

	        } else if (readAlias(state)) {
	          hasContent = true;

	          if (state.tag !== null || state.anchor !== null) {
	            throwError(state, 'alias node should not have any properties');
	          }

	        } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) {
	          hasContent = true;

	          if (state.tag === null) {
	            state.tag = '?';
	          }
	        }

	        if (state.anchor !== null) {
	          state.anchorMap[state.anchor] = state.result;
	        }
	      }
	    } else if (indentStatus === 0) {
	      // Special case: block sequences are allowed to have same indentation level as the parent.
	      // http://www.yaml.org/spec/1.2/spec.html#id2799784
	      hasContent = allowBlockCollections && readBlockSequence(state, blockIndent);
	    }
	  }

	  if (state.tag === null) {
	    if (state.anchor !== null) {
	      state.anchorMap[state.anchor] = state.result;
	    }

	  } else if (state.tag === '?') {
	    // Implicit resolving is not allowed for non-scalar types, and '?'
	    // non-specific tag is only automatically assigned to plain scalars.
	    //
	    // We only need to check kind conformity in case user explicitly assigns '?'
	    // tag, for example like this: "!<?> [0]"
	    //
	    if (state.result !== null && state.kind !== 'scalar') {
	      throwError(state, 'unacceptable node kind for !<?> tag; it should be "scalar", not "' + state.kind + '"');
	    }

	    for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) {
	      type = state.implicitTypes[typeIndex];

	      if (type.resolve(state.result)) { // `state.result` updated in resolver if matched
	        state.result = type.construct(state.result);
	        state.tag = type.tag;
	        if (state.anchor !== null) {
	          state.anchorMap[state.anchor] = state.result;
	        }
	        break;
	      }
	    }
	  } else if (state.tag !== '!') {
	    if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) {
	      type = state.typeMap[state.kind || 'fallback'][state.tag];
	    } else {
	      // looking for multi type
	      type = null;
	      typeList = state.typeMap.multi[state.kind || 'fallback'];

	      for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) {
	        if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) {
	          type = typeList[typeIndex];
	          break;
	        }
	      }
	    }

	    if (!type) {
	      throwError(state, 'unknown tag !<' + state.tag + '>');
	    }

	    if (state.result !== null && type.kind !== state.kind) {
	      throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"');
	    }

	    if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched
	      throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag');
	    } else {
	      state.result = type.construct(state.result, state.tag);
	      if (state.anchor !== null) {
	        state.anchorMap[state.anchor] = state.result;
	      }
	    }
	  }

	  if (state.listener !== null) {
	    state.listener('close', state);
	  }
	  return state.tag !== null ||  state.anchor !== null || hasContent;
	}

	function readDocument(state) {
	  var documentStart = state.position,
	      _position,
	      directiveName,
	      directiveArgs,
	      hasDirectives = false,
	      ch;

	  state.version = null;
	  state.checkLineBreaks = state.legacy;
	  state.tagMap = Object.create(null);
	  state.anchorMap = Object.create(null);

	  while ((ch = state.input.charCodeAt(state.position)) !== 0) {
	    skipSeparationSpace(state, true, -1);

	    ch = state.input.charCodeAt(state.position);

	    if (state.lineIndent > 0 || ch !== 0x25/* % */) {
	      break;
	    }

	    hasDirectives = true;
	    ch = state.input.charCodeAt(++state.position);
	    _position = state.position;

	    while (ch !== 0 && !is_WS_OR_EOL(ch)) {
	      ch = state.input.charCodeAt(++state.position);
	    }

	    directiveName = state.input.slice(_position, state.position);
	    directiveArgs = [];

	    if (directiveName.length < 1) {
	      throwError(state, 'directive name must not be less than one character in length');
	    }

	    while (ch !== 0) {
	      while (is_WHITE_SPACE(ch)) {
	        ch = state.input.charCodeAt(++state.position);
	      }

	      if (ch === 0x23/* # */) {
	        do { ch = state.input.charCodeAt(++state.position); }
	        while (ch !== 0 && !is_EOL(ch));
	        break;
	      }

	      if (is_EOL(ch)) break;

	      _position = state.position;

	      while (ch !== 0 && !is_WS_OR_EOL(ch)) {
	        ch = state.input.charCodeAt(++state.position);
	      }

	      directiveArgs.push(state.input.slice(_position, state.position));
	    }

	    if (ch !== 0) readLineBreak(state);

	    if (_hasOwnProperty.call(directiveHandlers, directiveName)) {
	      directiveHandlers[directiveName](state, directiveName, directiveArgs);
	    } else {
	      throwWarning(state, 'unknown document directive "' + directiveName + '"');
	    }
	  }

	  skipSeparationSpace(state, true, -1);

	  if (state.lineIndent === 0 &&
	      state.input.charCodeAt(state.position)     === 0x2D/* - */ &&
	      state.input.charCodeAt(state.position + 1) === 0x2D/* - */ &&
	      state.input.charCodeAt(state.position + 2) === 0x2D/* - */) {
	    state.position += 3;
	    skipSeparationSpace(state, true, -1);

	  } else if (hasDirectives) {
	    throwError(state, 'directives end mark is expected');
	  }

	  composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true);
	  skipSeparationSpace(state, true, -1);

	  if (state.checkLineBreaks &&
	      PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) {
	    throwWarning(state, 'non-ASCII line breaks are interpreted as content');
	  }

	  state.documents.push(state.result);

	  if (state.position === state.lineStart && testDocumentSeparator(state)) {

	    if (state.input.charCodeAt(state.position) === 0x2E/* . */) {
	      state.position += 3;
	      skipSeparationSpace(state, true, -1);
	    }
	    return;
	  }

	  if (state.position < (state.length - 1)) {
	    throwError(state, 'end of the stream or a document separator is expected');
	  } else {
	    return;
	  }
	}


	function loadDocuments(input, options) {
	  input = String(input);
	  options = options || {};

	  if (input.length !== 0) {

	    // Add tailing `\n` if not exists
	    if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ &&
	        input.charCodeAt(input.length - 1) !== 0x0D/* CR */) {
	      input += '\n';
	    }

	    // Strip BOM
	    if (input.charCodeAt(0) === 0xFEFF) {
	      input = input.slice(1);
	    }
	  }

	  var state = new State(input, options);

	  var nullpos = input.indexOf('\0');

	  if (nullpos !== -1) {
	    state.position = nullpos;
	    throwError(state, 'null byte is not allowed in input');
	  }

	  // Use 0 as string terminator. That significantly simplifies bounds check.
	  state.input += '\0';

	  while (state.input.charCodeAt(state.position) === 0x20/* Space */) {
	    state.lineIndent += 1;
	    state.position += 1;
	  }

	  while (state.position < (state.length - 1)) {
	    readDocument(state);
	  }

	  return state.documents;
	}


	function loadAll(input, iterator, options) {
	  if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') {
	    options = iterator;
	    iterator = null;
	  }

	  var documents = loadDocuments(input, options);

	  if (typeof iterator !== 'function') {
	    return documents;
	  }

	  for (var index = 0, length = documents.length; index < length; index += 1) {
	    iterator(documents[index]);
	  }
	}


	function load(input, options) {
	  var documents = loadDocuments(input, options);

	  if (documents.length === 0) {
	    /*eslint-disable no-undefined*/
	    return undefined;
	  } else if (documents.length === 1) {
	    return documents[0];
	  }
	  throw new YAMLException('expected a single document in the stream, but found more');
	}


	loader.loadAll = loadAll;
	loader.load    = load;
	return loader;
}

var dumper = {};

var hasRequiredDumper;

function requireDumper () {
	if (hasRequiredDumper) return dumper;
	hasRequiredDumper = 1;

	/*eslint-disable no-use-before-define*/

	var common              = requireCommon();
	var YAMLException       = requireException();
	var DEFAULT_SCHEMA      = require_default();

	var _toString       = Object.prototype.toString;
	var _hasOwnProperty = Object.prototype.hasOwnProperty;

	var CHAR_BOM                  = 0xFEFF;
	var CHAR_TAB                  = 0x09; /* Tab */
	var CHAR_LINE_FEED            = 0x0A; /* LF */
	var CHAR_CARRIAGE_RETURN      = 0x0D; /* CR */
	var CHAR_SPACE                = 0x20; /* Space */
	var CHAR_EXCLAMATION          = 0x21; /* ! */
	var CHAR_DOUBLE_QUOTE         = 0x22; /* " */
	var CHAR_SHARP                = 0x23; /* # */
	var CHAR_PERCENT              = 0x25; /* % */
	var CHAR_AMPERSAND            = 0x26; /* & */
	var CHAR_SINGLE_QUOTE         = 0x27; /* ' */
	var CHAR_ASTERISK             = 0x2A; /* * */
	var CHAR_COMMA                = 0x2C; /* , */
	var CHAR_MINUS                = 0x2D; /* - */
	var CHAR_COLON                = 0x3A; /* : */
	var CHAR_EQUALS               = 0x3D; /* = */
	var CHAR_GREATER_THAN         = 0x3E; /* > */
	var CHAR_QUESTION             = 0x3F; /* ? */
	var CHAR_COMMERCIAL_AT        = 0x40; /* @ */
	var CHAR_LEFT_SQUARE_BRACKET  = 0x5B; /* [ */
	var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */
	var CHAR_GRAVE_ACCENT         = 0x60; /* ` */
	var CHAR_LEFT_CURLY_BRACKET   = 0x7B; /* { */
	var CHAR_VERTICAL_LINE        = 0x7C; /* | */
	var CHAR_RIGHT_CURLY_BRACKET  = 0x7D; /* } */

	var ESCAPE_SEQUENCES = {};

	ESCAPE_SEQUENCES[0x00]   = '\\0';
	ESCAPE_SEQUENCES[0x07]   = '\\a';
	ESCAPE_SEQUENCES[0x08]   = '\\b';
	ESCAPE_SEQUENCES[0x09]   = '\\t';
	ESCAPE_SEQUENCES[0x0A]   = '\\n';
	ESCAPE_SEQUENCES[0x0B]   = '\\v';
	ESCAPE_SEQUENCES[0x0C]   = '\\f';
	ESCAPE_SEQUENCES[0x0D]   = '\\r';
	ESCAPE_SEQUENCES[0x1B]   = '\\e';
	ESCAPE_SEQUENCES[0x22]   = '\\"';
	ESCAPE_SEQUENCES[0x5C]   = '\\\\';
	ESCAPE_SEQUENCES[0x85]   = '\\N';
	ESCAPE_SEQUENCES[0xA0]   = '\\_';
	ESCAPE_SEQUENCES[0x2028] = '\\L';
	ESCAPE_SEQUENCES[0x2029] = '\\P';

	var DEPRECATED_BOOLEANS_SYNTAX = [
	  'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON',
	  'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF'
	];

	var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;

	function compileStyleMap(schema, map) {
	  var result, keys, index, length, tag, style, type;

	  if (map === null) return {};

	  result = {};
	  keys = Object.keys(map);

	  for (index = 0, length = keys.length; index < length; index += 1) {
	    tag = keys[index];
	    style = String(map[tag]);

	    if (tag.slice(0, 2) === '!!') {
	      tag = 'tag:yaml.org,2002:' + tag.slice(2);
	    }
	    type = schema.compiledTypeMap['fallback'][tag];

	    if (type && _hasOwnProperty.call(type.styleAliases, style)) {
	      style = type.styleAliases[style];
	    }

	    result[tag] = style;
	  }

	  return result;
	}

	function encodeHex(character) {
	  var string, handle, length;

	  string = character.toString(16).toUpperCase();

	  if (character <= 0xFF) {
	    handle = 'x';
	    length = 2;
	  } else if (character <= 0xFFFF) {
	    handle = 'u';
	    length = 4;
	  } else if (character <= 0xFFFFFFFF) {
	    handle = 'U';
	    length = 8;
	  } else {
	    throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF');
	  }

	  return '\\' + handle + common.repeat('0', length - string.length) + string;
	}


	var QUOTING_TYPE_SINGLE = 1,
	    QUOTING_TYPE_DOUBLE = 2;

	function State(options) {
	  this.schema        = options['schema'] || DEFAULT_SCHEMA;
	  this.indent        = Math.max(1, (options['indent'] || 2));
	  this.noArrayIndent = options['noArrayIndent'] || false;
	  this.skipInvalid   = options['skipInvalid'] || false;
	  this.flowLevel     = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']);
	  this.styleMap      = compileStyleMap(this.schema, options['styles'] || null);
	  this.sortKeys      = options['sortKeys'] || false;
	  this.lineWidth     = options['lineWidth'] || 80;
	  this.noRefs        = options['noRefs'] || false;
	  this.noCompatMode  = options['noCompatMode'] || false;
	  this.condenseFlow  = options['condenseFlow'] || false;
	  this.quotingType   = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE;
	  this.forceQuotes   = options['forceQuotes'] || false;
	  this.replacer      = typeof options['replacer'] === 'function' ? options['replacer'] : null;

	  this.implicitTypes = this.schema.compiledImplicit;
	  this.explicitTypes = this.schema.compiledExplicit;

	  this.tag = null;
	  this.result = '';

	  this.duplicates = [];
	  this.usedDuplicates = null;
	}

	// Indents every line in a string. Empty lines (\n only) are not indented.
	function indentString(string, spaces) {
	  var ind = common.repeat(' ', spaces),
	      position = 0,
	      next = -1,
	      result = '',
	      line,
	      length = string.length;

	  while (position < length) {
	    next = string.indexOf('\n', position);
	    if (next === -1) {
	      line = string.slice(position);
	      position = length;
	    } else {
	      line = string.slice(position, next + 1);
	      position = next + 1;
	    }

	    if (line.length && line !== '\n') result += ind;

	    result += line;
	  }

	  return result;
	}

	function generateNextLine(state, level) {
	  return '\n' + common.repeat(' ', state.indent * level);
	}

	function testImplicitResolving(state, str) {
	  var index, length, type;

	  for (index = 0, length = state.implicitTypes.length; index < length; index += 1) {
	    type = state.implicitTypes[index];

	    if (type.resolve(str)) {
	      return true;
	    }
	  }

	  return false;
	}

	// [33] s-white ::= s-space | s-tab
	function isWhitespace(c) {
	  return c === CHAR_SPACE || c === CHAR_TAB;
	}

	// Returns true if the character can be printed without escaping.
	// From YAML 1.2: "any allowed characters known to be non-printable
	// should also be escaped. [However,] This isn’t mandatory"
	// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029.
	function isPrintable(c) {
	  return  (0x00020 <= c && c <= 0x00007E)
	      || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029)
	      || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM)
	      ||  (0x10000 <= c && c <= 0x10FFFF);
	}

	// [34] ns-char ::= nb-char - s-white
	// [27] nb-char ::= c-printable - b-char - c-byte-order-mark
	// [26] b-char  ::= b-line-feed | b-carriage-return
	// Including s-white (for some reason, examples doesn't match specs in this aspect)
	// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark
	function isNsCharOrWhitespace(c) {
	  return isPrintable(c)
	    && c !== CHAR_BOM
	    // - b-char
	    && c !== CHAR_CARRIAGE_RETURN
	    && c !== CHAR_LINE_FEED;
	}

	// [127]  ns-plain-safe(c) ::= c = flow-out  ⇒ ns-plain-safe-out
	//                             c = flow-in   ⇒ ns-plain-safe-in
	//                             c = block-key ⇒ ns-plain-safe-out
	//                             c = flow-key  ⇒ ns-plain-safe-in
	// [128] ns-plain-safe-out ::= ns-char
	// [129]  ns-plain-safe-in ::= ns-char - c-flow-indicator
	// [130]  ns-plain-char(c) ::=  ( ns-plain-safe(c) - “:” - “#” )
	//                            | ( /* An ns-char preceding */ “#” )
	//                            | ( “:” /* Followed by an ns-plain-safe(c) */ )
	function isPlainSafe(c, prev, inblock) {
	  var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c);
	  var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c);
	  return (
	    // ns-plain-safe
	    inblock ? // c = flow-in
	      cIsNsCharOrWhitespace
	      : cIsNsCharOrWhitespace
	        // - c-flow-indicator
	        && c !== CHAR_COMMA
	        && c !== CHAR_LEFT_SQUARE_BRACKET
	        && c !== CHAR_RIGHT_SQUARE_BRACKET
	        && c !== CHAR_LEFT_CURLY_BRACKET
	        && c !== CHAR_RIGHT_CURLY_BRACKET
	  )
	    // ns-plain-char
	    && c !== CHAR_SHARP // false on '#'
	    && !(prev === CHAR_COLON && !cIsNsChar) // false on ': '
	    || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#'
	    || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]'
	}

	// Simplified test for values allowed as the first character in plain style.
	function isPlainSafeFirst(c) {
	  // Uses a subset of ns-char - c-indicator
	  // where ns-char = nb-char - s-white.
	  // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part
	  return isPrintable(c) && c !== CHAR_BOM
	    && !isWhitespace(c) // - s-white
	    // - (c-indicator ::=
	    // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}”
	    && c !== CHAR_MINUS
	    && c !== CHAR_QUESTION
	    && c !== CHAR_COLON
	    && c !== CHAR_COMMA
	    && c !== CHAR_LEFT_SQUARE_BRACKET
	    && c !== CHAR_RIGHT_SQUARE_BRACKET
	    && c !== CHAR_LEFT_CURLY_BRACKET
	    && c !== CHAR_RIGHT_CURLY_BRACKET
	    // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"”
	    && c !== CHAR_SHARP
	    && c !== CHAR_AMPERSAND
	    && c !== CHAR_ASTERISK
	    && c !== CHAR_EXCLAMATION
	    && c !== CHAR_VERTICAL_LINE
	    && c !== CHAR_EQUALS
	    && c !== CHAR_GREATER_THAN
	    && c !== CHAR_SINGLE_QUOTE
	    && c !== CHAR_DOUBLE_QUOTE
	    // | “%” | “@” | “`”)
	    && c !== CHAR_PERCENT
	    && c !== CHAR_COMMERCIAL_AT
	    && c !== CHAR_GRAVE_ACCENT;
	}

	// Simplified test for values allowed as the last character in plain style.
	function isPlainSafeLast(c) {
	  // just not whitespace or colon, it will be checked to be plain character later
	  return !isWhitespace(c) && c !== CHAR_COLON;
	}

	// Same as 'string'.codePointAt(pos), but works in older browsers.
	function codePointAt(string, pos) {
	  var first = string.charCodeAt(pos), second;
	  if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) {
	    second = string.charCodeAt(pos + 1);
	    if (second >= 0xDC00 && second <= 0xDFFF) {
	      // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
	      return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
	    }
	  }
	  return first;
	}

	// Determines whether block indentation indicator is required.
	function needIndentIndicator(string) {
	  var leadingSpaceRe = /^\n* /;
	  return leadingSpaceRe.test(string);
	}

	var STYLE_PLAIN   = 1,
	    STYLE_SINGLE  = 2,
	    STYLE_LITERAL = 3,
	    STYLE_FOLDED  = 4,
	    STYLE_DOUBLE  = 5;

	// Determines which scalar styles are possible and returns the preferred style.
	// lineWidth = -1 => no limit.
	// Pre-conditions: str.length > 0.
	// Post-conditions:
	//    STYLE_PLAIN or STYLE_SINGLE => no \n are in the string.
	//    STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1).
	//    STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1).
	function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth,
	  testAmbiguousType, quotingType, forceQuotes, inblock) {

	  var i;
	  var char = 0;
	  var prevChar = null;
	  var hasLineBreak = false;
	  var hasFoldableLine = false; // only checked if shouldTrackWidth
	  var shouldTrackWidth = lineWidth !== -1;
	  var previousLineBreak = -1; // count the first line correctly
	  var plain = isPlainSafeFirst(codePointAt(string, 0))
	          && isPlainSafeLast(codePointAt(string, string.length - 1));

	  if (singleLineOnly || forceQuotes) {
	    // Case: no block styles.
	    // Check for disallowed characters to rule out plain and single.
	    for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
	      char = codePointAt(string, i);
	      if (!isPrintable(char)) {
	        return STYLE_DOUBLE;
	      }
	      plain = plain && isPlainSafe(char, prevChar, inblock);
	      prevChar = char;
	    }
	  } else {
	    // Case: block styles permitted.
	    for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
	      char = codePointAt(string, i);
	      if (char === CHAR_LINE_FEED) {
	        hasLineBreak = true;
	        // Check if any line can be folded.
	        if (shouldTrackWidth) {
	          hasFoldableLine = hasFoldableLine ||
	            // Foldable line = too long, and not more-indented.
	            (i - previousLineBreak - 1 > lineWidth &&
	             string[previousLineBreak + 1] !== ' ');
	          previousLineBreak = i;
	        }
	      } else if (!isPrintable(char)) {
	        return STYLE_DOUBLE;
	      }
	      plain = plain && isPlainSafe(char, prevChar, inblock);
	      prevChar = char;
	    }
	    // in case the end is missing a \n
	    hasFoldableLine = hasFoldableLine || (shouldTrackWidth &&
	      (i - previousLineBreak - 1 > lineWidth &&
	       string[previousLineBreak + 1] !== ' '));
	  }
	  // Although every style can represent \n without escaping, prefer block styles
	  // for multiline, since they're more readable and they don't add empty lines.
	  // Also prefer folding a super-long line.
	  if (!hasLineBreak && !hasFoldableLine) {
	    // Strings interpretable as another type have to be quoted;
	    // e.g. the string 'true' vs. the boolean true.
	    if (plain && !forceQuotes && !testAmbiguousType(string)) {
	      return STYLE_PLAIN;
	    }
	    return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
	  }
	  // Edge case: block indentation indicator can only have one digit.
	  if (indentPerLevel > 9 && needIndentIndicator(string)) {
	    return STYLE_DOUBLE;
	  }
	  // At this point we know block styles are valid.
	  // Prefer literal style unless we want to fold.
	  if (!forceQuotes) {
	    return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL;
	  }
	  return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE;
	}

	// Note: line breaking/folding is implemented for only the folded style.
	// NB. We drop the last trailing newline (if any) of a returned block scalar
	//  since the dumper adds its own newline. This always works:
	//    • No ending newline => unaffected; already using strip "-" chomping.
	//    • Ending newline    => removed then restored.
	//  Importantly, this keeps the "+" chomp indicator from gaining an extra line.
	function writeScalar(state, string, level, iskey, inblock) {
	  state.dump = (function () {
	    if (string.length === 0) {
	      return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''";
	    }
	    if (!state.noCompatMode) {
	      if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) {
	        return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'");
	      }
	    }

	    var indent = state.indent * Math.max(1, level); // no 0-indent scalars
	    // As indentation gets deeper, let the width decrease monotonically
	    // to the lower bound min(state.lineWidth, 40).
	    // Note that this implies
	    //  state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound.
	    //  state.lineWidth > 40 + state.indent: width decreases until the lower bound.
	    // This behaves better than a constant minimum width which disallows narrower options,
	    // or an indent threshold which causes the width to suddenly increase.
	    var lineWidth = state.lineWidth === -1
	      ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent);

	    // Without knowing if keys are implicit/explicit, assume implicit for safety.
	    var singleLineOnly = iskey
	      // No block styles in flow mode.
	      || (state.flowLevel > -1 && level >= state.flowLevel);
	    function testAmbiguity(string) {
	      return testImplicitResolving(state, string);
	    }

	    switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth,
	      testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) {

	      case STYLE_PLAIN:
	        return string;
	      case STYLE_SINGLE:
	        return "'" + string.replace(/'/g, "''") + "'";
	      case STYLE_LITERAL:
	        return '|' + blockHeader(string, state.indent)
	          + dropEndingNewline(indentString(string, indent));
	      case STYLE_FOLDED:
	        return '>' + blockHeader(string, state.indent)
	          + dropEndingNewline(indentString(foldString(string, lineWidth), indent));
	      case STYLE_DOUBLE:
	        return '"' + escapeString(string) + '"';
	      default:
	        throw new YAMLException('impossible error: invalid scalar style');
	    }
	  }());
	}

	// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9.
	function blockHeader(string, indentPerLevel) {
	  var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : '';

	  // note the special case: the string '\n' counts as a "trailing" empty line.
	  var clip =          string[string.length - 1] === '\n';
	  var keep = clip && (string[string.length - 2] === '\n' || string === '\n');
	  var chomp = keep ? '+' : (clip ? '' : '-');

	  return indentIndicator + chomp + '\n';
	}

	// (See the note for writeScalar.)
	function dropEndingNewline(string) {
	  return string[string.length - 1] === '\n' ? string.slice(0, -1) : string;
	}

	// Note: a long line without a suitable break point will exceed the width limit.
	// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0.
	function foldString(string, width) {
	  // In folded style, $k$ consecutive newlines output as $k+1$ newlines—
	  // unless they're before or after a more-indented line, or at the very
	  // beginning or end, in which case $k$ maps to $k$.
	  // Therefore, parse each chunk as newline(s) followed by a content line.
	  var lineRe = /(\n+)([^\n]*)/g;

	  // first line (possibly an empty line)
	  var result = (function () {
	    var nextLF = string.indexOf('\n');
	    nextLF = nextLF !== -1 ? nextLF : string.length;
	    lineRe.lastIndex = nextLF;
	    return foldLine(string.slice(0, nextLF), width);
	  }());
	  // If we haven't reached the first content line yet, don't add an extra \n.
	  var prevMoreIndented = string[0] === '\n' || string[0] === ' ';
	  var moreIndented;

	  // rest of the lines
	  var match;
	  while ((match = lineRe.exec(string))) {
	    var prefix = match[1], line = match[2];
	    moreIndented = (line[0] === ' ');
	    result += prefix
	      + (!prevMoreIndented && !moreIndented && line !== ''
	        ? '\n' : '')
	      + foldLine(line, width);
	    prevMoreIndented = moreIndented;
	  }

	  return result;
	}

	// Greedy line breaking.
	// Picks the longest line under the limit each time,
	// otherwise settles for the shortest line over the limit.
	// NB. More-indented lines *cannot* be folded, as that would add an extra \n.
	function foldLine(line, width) {
	  if (line === '' || line[0] === ' ') return line;

	  // Since a more-indented line adds a \n, breaks can't be followed by a space.
	  var breakRe = / [^ ]/g; // note: the match index will always be <= length-2.
	  var match;
	  // start is an inclusive index. end, curr, and next are exclusive.
	  var start = 0, end, curr = 0, next = 0;
	  var result = '';

	  // Invariants: 0 <= start <= length-1.
	  //   0 <= curr <= next <= max(0, length-2). curr - start <= width.
	  // Inside the loop:
	  //   A match implies length >= 2, so curr and next are <= length-2.
	  while ((match = breakRe.exec(line))) {
	    next = match.index;
	    // maintain invariant: curr - start <= width
	    if (next - start > width) {
	      end = (curr > start) ? curr : next; // derive end <= length-2
	      result += '\n' + line.slice(start, end);
	      // skip the space that was output as \n
	      start = end + 1;                    // derive start <= length-1
	    }
	    curr = next;
	  }

	  // By the invariants, start <= length-1, so there is something left over.
	  // It is either the whole string or a part starting from non-whitespace.
	  result += '\n';
	  // Insert a break if the remainder is too long and there is a break available.
	  if (line.length - start > width && curr > start) {
	    result += line.slice(start, curr) + '\n' + line.slice(curr + 1);
	  } else {
	    result += line.slice(start);
	  }

	  return result.slice(1); // drop extra \n joiner
	}

	// Escapes a double-quoted string.
	function escapeString(string) {
	  var result = '';
	  var char = 0;
	  var escapeSeq;

	  for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) {
	    char = codePointAt(string, i);
	    escapeSeq = ESCAPE_SEQUENCES[char];

	    if (!escapeSeq && isPrintable(char)) {
	      result += string[i];
	      if (char >= 0x10000) result += string[i + 1];
	    } else {
	      result += escapeSeq || encodeHex(char);
	    }
	  }

	  return result;
	}

	function writeFlowSequence(state, level, object) {
	  var _result = '',
	      _tag    = state.tag,
	      index,
	      length,
	      value;

	  for (index = 0, length = object.length; index < length; index += 1) {
	    value = object[index];

	    if (state.replacer) {
	      value = state.replacer.call(object, String(index), value);
	    }

	    // Write only valid elements, put null instead of invalid elements.
	    if (writeNode(state, level, value, false, false) ||
	        (typeof value === 'undefined' &&
	         writeNode(state, level, null, false, false))) {

	      if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : '');
	      _result += state.dump;
	    }
	  }

	  state.tag = _tag;
	  state.dump = '[' + _result + ']';
	}

	function writeBlockSequence(state, level, object, compact) {
	  var _result = '',
	      _tag    = state.tag,
	      index,
	      length,
	      value;

	  for (index = 0, length = object.length; index < length; index += 1) {
	    value = object[index];

	    if (state.replacer) {
	      value = state.replacer.call(object, String(index), value);
	    }

	    // Write only valid elements, put null instead of invalid elements.
	    if (writeNode(state, level + 1, value, true, true, false, true) ||
	        (typeof value === 'undefined' &&
	         writeNode(state, level + 1, null, true, true, false, true))) {

	      if (!compact || _result !== '') {
	        _result += generateNextLine(state, level);
	      }

	      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
	        _result += '-';
	      } else {
	        _result += '- ';
	      }

	      _result += state.dump;
	    }
	  }

	  state.tag = _tag;
	  state.dump = _result || '[]'; // Empty sequence if no valid values.
	}

	function writeFlowMapping(state, level, object) {
	  var _result       = '',
	      _tag          = state.tag,
	      objectKeyList = Object.keys(object),
	      index,
	      length,
	      objectKey,
	      objectValue,
	      pairBuffer;

	  for (index = 0, length = objectKeyList.length; index < length; index += 1) {

	    pairBuffer = '';
	    if (_result !== '') pairBuffer += ', ';

	    if (state.condenseFlow) pairBuffer += '"';

	    objectKey = objectKeyList[index];
	    objectValue = object[objectKey];

	    if (state.replacer) {
	      objectValue = state.replacer.call(object, objectKey, objectValue);
	    }

	    if (!writeNode(state, level, objectKey, false, false)) {
	      continue; // Skip this pair because of invalid key;
	    }

	    if (state.dump.length > 1024) pairBuffer += '? ';

	    pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' ');

	    if (!writeNode(state, level, objectValue, false, false)) {
	      continue; // Skip this pair because of invalid value.
	    }

	    pairBuffer += state.dump;

	    // Both key and value are valid.
	    _result += pairBuffer;
	  }

	  state.tag = _tag;
	  state.dump = '{' + _result + '}';
	}

	function writeBlockMapping(state, level, object, compact) {
	  var _result       = '',
	      _tag          = state.tag,
	      objectKeyList = Object.keys(object),
	      index,
	      length,
	      objectKey,
	      objectValue,
	      explicitPair,
	      pairBuffer;

	  // Allow sorting keys so that the output file is deterministic
	  if (state.sortKeys === true) {
	    // Default sorting
	    objectKeyList.sort();
	  } else if (typeof state.sortKeys === 'function') {
	    // Custom sort function
	    objectKeyList.sort(state.sortKeys);
	  } else if (state.sortKeys) {
	    // Something is wrong
	    throw new YAMLException('sortKeys must be a boolean or a function');
	  }

	  for (index = 0, length = objectKeyList.length; index < length; index += 1) {
	    pairBuffer = '';

	    if (!compact || _result !== '') {
	      pairBuffer += generateNextLine(state, level);
	    }

	    objectKey = objectKeyList[index];
	    objectValue = object[objectKey];

	    if (state.replacer) {
	      objectValue = state.replacer.call(object, objectKey, objectValue);
	    }

	    if (!writeNode(state, level + 1, objectKey, true, true, true)) {
	      continue; // Skip this pair because of invalid key.
	    }

	    explicitPair = (state.tag !== null && state.tag !== '?') ||
	                   (state.dump && state.dump.length > 1024);

	    if (explicitPair) {
	      if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
	        pairBuffer += '?';
	      } else {
	        pairBuffer += '? ';
	      }
	    }

	    pairBuffer += state.dump;

	    if (explicitPair) {
	      pairBuffer += generateNextLine(state, level);
	    }

	    if (!writeNode(state, level + 1, objectValue, true, explicitPair)) {
	      continue; // Skip this pair because of invalid value.
	    }

	    if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) {
	      pairBuffer += ':';
	    } else {
	      pairBuffer += ': ';
	    }

	    pairBuffer += state.dump;

	    // Both key and value are valid.
	    _result += pairBuffer;
	  }

	  state.tag = _tag;
	  state.dump = _result || '{}'; // Empty mapping if no valid pairs.
	}

	function detectType(state, object, explicit) {
	  var _result, typeList, index, length, type, style;

	  typeList = explicit ? state.explicitTypes : state.implicitTypes;

	  for (index = 0, length = typeList.length; index < length; index += 1) {
	    type = typeList[index];

	    if ((type.instanceOf  || type.predicate) &&
	        (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) &&
	        (!type.predicate  || type.predicate(object))) {

	      if (explicit) {
	        if (type.multi && type.representName) {
	          state.tag = type.representName(object);
	        } else {
	          state.tag = type.tag;
	        }
	      } else {
	        state.tag = '?';
	      }

	      if (type.represent) {
	        style = state.styleMap[type.tag] || type.defaultStyle;

	        if (_toString.call(type.represent) === '[object Function]') {
	          _result = type.represent(object, style);
	        } else if (_hasOwnProperty.call(type.represent, style)) {
	          _result = type.represent[style](object, style);
	        } else {
	          throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style');
	        }

	        state.dump = _result;
	      }

	      return true;
	    }
	  }

	  return false;
	}

	// Serializes `object` and writes it to global `result`.
	// Returns true on success, or false on invalid object.
	//
	function writeNode(state, level, object, block, compact, iskey, isblockseq) {
	  state.tag = null;
	  state.dump = object;

	  if (!detectType(state, object, false)) {
	    detectType(state, object, true);
	  }

	  var type = _toString.call(state.dump);
	  var inblock = block;
	  var tagStr;

	  if (block) {
	    block = (state.flowLevel < 0 || state.flowLevel > level);
	  }

	  var objectOrArray = type === '[object Object]' || type === '[object Array]',
	      duplicateIndex,
	      duplicate;

	  if (objectOrArray) {
	    duplicateIndex = state.duplicates.indexOf(object);
	    duplicate = duplicateIndex !== -1;
	  }

	  if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) {
	    compact = false;
	  }

	  if (duplicate && state.usedDuplicates[duplicateIndex]) {
	    state.dump = '*ref_' + duplicateIndex;
	  } else {
	    if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) {
	      state.usedDuplicates[duplicateIndex] = true;
	    }
	    if (type === '[object Object]') {
	      if (block && (Object.keys(state.dump).length !== 0)) {
	        writeBlockMapping(state, level, state.dump, compact);
	        if (duplicate) {
	          state.dump = '&ref_' + duplicateIndex + state.dump;
	        }
	      } else {
	        writeFlowMapping(state, level, state.dump);
	        if (duplicate) {
	          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
	        }
	      }
	    } else if (type === '[object Array]') {
	      if (block && (state.dump.length !== 0)) {
	        if (state.noArrayIndent && !isblockseq && level > 0) {
	          writeBlockSequence(state, level - 1, state.dump, compact);
	        } else {
	          writeBlockSequence(state, level, state.dump, compact);
	        }
	        if (duplicate) {
	          state.dump = '&ref_' + duplicateIndex + state.dump;
	        }
	      } else {
	        writeFlowSequence(state, level, state.dump);
	        if (duplicate) {
	          state.dump = '&ref_' + duplicateIndex + ' ' + state.dump;
	        }
	      }
	    } else if (type === '[object String]') {
	      if (state.tag !== '?') {
	        writeScalar(state, state.dump, level, iskey, inblock);
	      }
	    } else if (type === '[object Undefined]') {
	      return false;
	    } else {
	      if (state.skipInvalid) return false;
	      throw new YAMLException('unacceptable kind of an object to dump ' + type);
	    }

	    if (state.tag !== null && state.tag !== '?') {
	      // Need to encode all characters except those allowed by the spec:
	      //
	      // [35] ns-dec-digit    ::=  [#x30-#x39] /* 0-9 */
	      // [36] ns-hex-digit    ::=  ns-dec-digit
	      //                         | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */
	      // [37] ns-ascii-letter ::=  [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */
	      // [38] ns-word-char    ::=  ns-dec-digit | ns-ascii-letter | “-”
	      // [39] ns-uri-char     ::=  “%” ns-hex-digit ns-hex-digit | ns-word-char | “#”
	      //                         | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,”
	      //                         | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]”
	      //
	      // Also need to encode '!' because it has special meaning (end of tag prefix).
	      //
	      tagStr = encodeURI(
	        state.tag[0] === '!' ? state.tag.slice(1) : state.tag
	      ).replace(/!/g, '%21');

	      if (state.tag[0] === '!') {
	        tagStr = '!' + tagStr;
	      } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') {
	        tagStr = '!!' + tagStr.slice(18);
	      } else {
	        tagStr = '!<' + tagStr + '>';
	      }

	      state.dump = tagStr + ' ' + state.dump;
	    }
	  }

	  return true;
	}

	function getDuplicateReferences(object, state) {
	  var objects = [],
	      duplicatesIndexes = [],
	      index,
	      length;

	  inspectNode(object, objects, duplicatesIndexes);

	  for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) {
	    state.duplicates.push(objects[duplicatesIndexes[index]]);
	  }
	  state.usedDuplicates = new Array(length);
	}

	function inspectNode(object, objects, duplicatesIndexes) {
	  var objectKeyList,
	      index,
	      length;

	  if (object !== null && typeof object === 'object') {
	    index = objects.indexOf(object);
	    if (index !== -1) {
	      if (duplicatesIndexes.indexOf(index) === -1) {
	        duplicatesIndexes.push(index);
	      }
	    } else {
	      objects.push(object);

	      if (Array.isArray(object)) {
	        for (index = 0, length = object.length; index < length; index += 1) {
	          inspectNode(object[index], objects, duplicatesIndexes);
	        }
	      } else {
	        objectKeyList = Object.keys(object);

	        for (index = 0, length = objectKeyList.length; index < length; index += 1) {
	          inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes);
	        }
	      }
	    }
	  }
	}

	function dump(input, options) {
	  options = options || {};

	  var state = new State(options);

	  if (!state.noRefs) getDuplicateReferences(input, state);

	  var value = input;

	  if (state.replacer) {
	    value = state.replacer.call({ '': value }, '', value);
	  }

	  if (writeNode(state, 0, value, true, true)) return state.dump + '\n';

	  return '';
	}

	dumper.dump = dump;
	return dumper;
}

var hasRequiredJsYaml;

function requireJsYaml () {
	if (hasRequiredJsYaml) return jsYaml;
	hasRequiredJsYaml = 1;


	var loader = requireLoader();
	var dumper = requireDumper();


	function renamed(from, to) {
	  return function () {
	    throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' +
	      'Use yaml.' + to + ' instead, which is now safe by default.');
	  };
	}


	jsYaml.Type                = requireType();
	jsYaml.Schema              = requireSchema();
	jsYaml.FAILSAFE_SCHEMA     = requireFailsafe();
	jsYaml.JSON_SCHEMA         = requireJson();
	jsYaml.CORE_SCHEMA         = requireCore();
	jsYaml.DEFAULT_SCHEMA      = require_default();
	jsYaml.load                = loader.load;
	jsYaml.loadAll             = loader.loadAll;
	jsYaml.dump                = dumper.dump;
	jsYaml.YAMLException       = requireException();

	// Re-export all types in case user wants to create custom schema
	jsYaml.types = {
	  binary:    requireBinary$1(),
	  float:     requireFloat(),
	  map:       requireMap(),
	  null:      require_null(),
	  pairs:     requirePairs(),
	  set:       requireSet(),
	  timestamp: requireTimestamp(),
	  bool:      requireBool(),
	  int:       requireInt(),
	  merge:     requireMerge(),
	  omap:      requireOmap(),
	  seq:       requireSeq(),
	  str:       requireStr()
	};

	// Removed functions from JS-YAML 3.0.x
	jsYaml.safeLoad            = renamed('safeLoad', 'load');
	jsYaml.safeLoadAll         = renamed('safeLoadAll', 'loadAll');
	jsYaml.safeDump            = renamed('safeDump', 'dump');
	return jsYaml;
}

var hasRequiredYaml;

function requireYaml () {
	if (hasRequiredYaml) return yaml;
	hasRequiredYaml = 1;
	var __importDefault = (yaml.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(yaml, "__esModule", { value: true });
	const errors_js_1 = requireErrors();
	const js_yaml_1 = __importDefault(requireJsYaml());
	const js_yaml_2 = requireJsYaml();
	yaml.default = {
	    /**
	     * The order that this parser will run, in relation to other parsers.
	     */
	    order: 200,
	    /**
	     * Whether to allow "empty" files. This includes zero-byte files, as well as empty JSON objects.
	     */
	    allowEmpty: true,
	    /**
	     * Determines whether this parser can parse a given file reference.
	     * Parsers that match will be tried, in order, until one successfully parses the file.
	     * Parsers that don't match will be skipped, UNLESS none of the parsers match, in which case
	     * every parser will be tried.
	     */
	    canParse: [".yaml", ".yml", ".json"], // JSON is valid YAML
	    /**
	     * Parses the given file as YAML
	     *
	     * @param file           - An object containing information about the referenced file
	     * @param file.url       - The full URL of the referenced file
	     * @param file.extension - The lowercased file extension (e.g. ".txt", ".html", etc.)
	     * @param file.data      - The file contents. This will be whatever data type was returned by the resolver
	     * @returns
	     */
	    async parse(file) {
	        let data = file.data;
	        if (Buffer.isBuffer(data)) {
	            data = data.toString();
	        }
	        if (typeof data === "string") {
	            try {
	                return js_yaml_1.default.load(data, { schema: js_yaml_2.JSON_SCHEMA });
	            }
	            catch (e) {
	                throw new errors_js_1.ParserError(e?.message || "Parser Error", file.url);
	            }
	        }
	        else {
	            // data is already a JavaScript value (object, array, number, null, NaN, etc.)
	            return data;
	        }
	    },
	};
	return yaml;
}

var text = {};

var hasRequiredText;

function requireText () {
	if (hasRequiredText) return text;
	hasRequiredText = 1;
	Object.defineProperty(text, "__esModule", { value: true });
	const errors_js_1 = requireErrors();
	const TEXT_REGEXP = /\.(txt|htm|html|md|xml|js|min|map|css|scss|less|svg)$/i;
	text.default = {
	    /**
	     * The order that this parser will run, in relation to other parsers.
	     */
	    order: 300,
	    /**
	     * Whether to allow "empty" files (zero bytes).
	     */
	    allowEmpty: true,
	    /**
	     * The encoding that the text is expected to be in.
	     */
	    encoding: "utf8",
	    /**
	     * Determines whether this parser can parse a given file reference.
	     * Parsers that return true will be tried, in order, until one successfully parses the file.
	     * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
	     * every parser will be tried.
	     */
	    canParse(file) {
	        // Use this parser if the file is a string or Buffer, and has a known text-based extension
	        return (typeof file.data === "string" || Buffer.isBuffer(file.data)) && TEXT_REGEXP.test(file.url);
	    },
	    /**
	     * Parses the given file as text
	     */
	    parse(file) {
	        if (typeof file.data === "string") {
	            return file.data;
	        }
	        else if (Buffer.isBuffer(file.data)) {
	            return file.data.toString(this.encoding);
	        }
	        else {
	            throw new errors_js_1.ParserError("data is not text", file.url);
	        }
	    },
	};
	return text;
}

var binary$1 = {};

var hasRequiredBinary;

function requireBinary () {
	if (hasRequiredBinary) return binary$1;
	hasRequiredBinary = 1;
	Object.defineProperty(binary$1, "__esModule", { value: true });
	const BINARY_REGEXP = /\.(jpeg|jpg|gif|png|bmp|ico)$/i;
	binary$1.default = {
	    /**
	     * The order that this parser will run, in relation to other parsers.
	     */
	    order: 400,
	    /**
	     * Whether to allow "empty" files (zero bytes).
	     */
	    allowEmpty: true,
	    /**
	     * Determines whether this parser can parse a given file reference.
	     * Parsers that return true will be tried, in order, until one successfully parses the file.
	     * Parsers that return false will be skipped, UNLESS all parsers returned false, in which case
	     * every parser will be tried.
	     */
	    canParse(file) {
	        // Use this parser if the file is a Buffer, and has a known binary extension
	        return Buffer.isBuffer(file.data) && BINARY_REGEXP.test(file.url);
	    },
	    /**
	     * Parses the given data as a Buffer (byte array).
	     */
	    parse(file) {
	        if (Buffer.isBuffer(file.data)) {
	            return file.data;
	        }
	        else {
	            // This will reject if data is anything other than a string or typed array
	            return Buffer.from(file.data);
	        }
	    },
	};
	return binary$1;
}

var file = {};

var empty = null;

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

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

var hasRequiredFile;

function requireFile () {
	if (hasRequiredFile) return file;
	hasRequiredFile = 1;
	var __createBinding = (file.__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 = (file.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (file.__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 = (file.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(file, "__esModule", { value: true });
	const fs_1 = __importDefault(require$$0);
	const ono_1 = require$$6$1;
	const url = __importStar(requireUrl());
	const errors_js_1 = requireErrors();
	file.default = {
	    /**
	     * The order that this resolver will run, in relation to other resolvers.
	     */
	    order: 100,
	    /**
	     * Determines whether this resolver can read a given file reference.
	     * Resolvers that return true will be tried, in order, until one successfully resolves the file.
	     * Resolvers that return false will not be given a chance to resolve the file.
	     */
	    canRead(file) {
	        return url.isFileSystemPath(file.url);
	    },
	    /**
	     * Reads the given file and returns its raw contents as a Buffer.
	     */
	    async read(file) {
	        let path;
	        try {
	            path = url.toFileSystemPath(file.url);
	        }
	        catch (err) {
	            throw new errors_js_1.ResolverError(ono_1.ono.uri(err, `Malformed URI: ${file.url}`), file.url);
	        }
	        try {
	            return await fs_1.default.promises.readFile(path);
	        }
	        catch (err) {
	            throw new errors_js_1.ResolverError((0, ono_1.ono)(err, `Error opening file "${path}"`), path);
	        }
	    },
	};
	return file;
}

var http = {};

var hasRequiredHttp;

function requireHttp () {
	if (hasRequiredHttp) return http;
	hasRequiredHttp = 1;
	var __createBinding = (http.__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 = (http.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (http.__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(http, "__esModule", { value: true });
	const ono_1 = require$$6$1;
	const url = __importStar(requireUrl());
	const errors_js_1 = requireErrors();
	http.default = {
	    /**
	     * The order that this resolver will run, in relation to other resolvers.
	     */
	    order: 200,
	    /**
	     * HTTP headers to send when downloading files.
	     *
	     * @example:
	     * {
	     *   "User-Agent": "JSON Schema $Ref Parser",
	     *   Accept: "application/json"
	     * }
	     */
	    headers: null,
	    /**
	     * HTTP request timeout (in milliseconds).
	     */
	    timeout: 60000, // 60 seconds
	    /**
	     * The maximum number of HTTP redirects to follow.
	     * To disable automatic following of redirects, set this to zero.
	     */
	    redirects: 5,
	    /**
	     * The `withCredentials` option of XMLHttpRequest.
	     * Set this to `true` if you're downloading files from a CORS-enabled server that requires authentication
	     */
	    withCredentials: false,
	    /**
	     * Determines whether this resolver can read a given file reference.
	     * Resolvers that return true will be tried in order, until one successfully resolves the file.
	     * Resolvers that return false will not be given a chance to resolve the file.
	     */
	    canRead(file) {
	        return url.isHttp(file.url);
	    },
	    /**
	     * Reads the given URL and returns its raw contents as a Buffer.
	     */
	    read(file) {
	        const u = url.parse(file.url);
	        if (typeof window !== "undefined" && !u.protocol) {
	            // Use the protocol of the current page
	            u.protocol = url.parse(location.href).protocol;
	        }
	        return download(u, this);
	    },
	};
	/**
	 * Downloads the given file.
	 * @returns
	 * The promise resolves with the raw downloaded data, or rejects if there is an HTTP error.
	 */
	async function download(u, httpOptions, _redirects) {
	    u = url.parse(u);
	    const redirects = _redirects || [];
	    redirects.push(u.href);
	    try {
	        const res = await get(u, httpOptions);
	        if (res.status >= 400) {
	            throw (0, ono_1.ono)({ status: res.status }, `HTTP ERROR ${res.status}`);
	        }
	        else if (res.status >= 300) {
	            if (!Number.isNaN(httpOptions.redirects) && redirects.length > httpOptions.redirects) {
	                throw new errors_js_1.ResolverError((0, ono_1.ono)({ status: res.status }, `Error downloading ${redirects[0]}. \nToo many redirects: \n  ${redirects.join(" \n  ")}`));
	            }
	            else if (!("location" in res.headers) || !res.headers.location) {
	                throw (0, ono_1.ono)({ status: res.status }, `HTTP ${res.status} redirect with no location header`);
	            }
	            else {
	                const redirectTo = url.resolve(u.href, res.headers.location);
	                return download(redirectTo, httpOptions, redirects);
	            }
	        }
	        else {
	            if (res.body) {
	                const buf = await res.arrayBuffer();
	                return Buffer.from(buf);
	            }
	            return Buffer.alloc(0);
	        }
	    }
	    catch (err) {
	        throw new errors_js_1.ResolverError((0, ono_1.ono)(err, `Error downloading ${u.href}`), u.href);
	    }
	}
	/**
	 * Sends an HTTP GET request.
	 * The promise resolves with the HTTP Response object.
	 */
	async function get(u, httpOptions) {
	    let controller;
	    let timeoutId;
	    if (httpOptions.timeout) {
	        controller = new AbortController();
	        timeoutId = setTimeout(() => controller.abort(), httpOptions.timeout);
	    }
	    const response = await fetch(u, {
	        method: "GET",
	        headers: httpOptions.headers || {},
	        credentials: httpOptions.withCredentials ? "include" : "same-origin",
	        signal: controller ? controller.signal : null,
	    });
	    if (timeoutId) {
	        clearTimeout(timeoutId);
	    }
	    return response;
	}
	return http;
}

var hasRequiredOptions$1;

function requireOptions$1 () {
	if (hasRequiredOptions$1) return options$1;
	hasRequiredOptions$1 = 1;
	(function (exports) {
		var __importDefault = (options$1.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.getNewOptions = exports.getJsonSchemaRefParserDefaultOptions = undefined;
		const json_js_1 = __importDefault(requireJson$1());
		const yaml_js_1 = __importDefault(requireYaml());
		const text_js_1 = __importDefault(requireText());
		const binary_js_1 = __importDefault(requireBinary());
		const file_js_1 = __importDefault(requireFile());
		const http_js_1 = __importDefault(requireHttp());
		const getJsonSchemaRefParserDefaultOptions = () => {
		    const defaults = {
		        /**
		         * Determines how different types of files will be parsed.
		         *
		         * You can add additional parsers of your own, replace an existing one with
		         * your own implementation, or disable any parser by setting it to false.
		         */
		        parse: {
		            json: { ...json_js_1.default },
		            yaml: { ...yaml_js_1.default },
		            text: { ...text_js_1.default },
		            binary: { ...binary_js_1.default },
		        },
		        /**
		         * Determines how JSON References will be resolved.
		         *
		         * You can add additional resolvers of your own, replace an existing one with
		         * your own implementation, or disable any resolver by setting it to false.
		         */
		        resolve: {
		            file: { ...file_js_1.default },
		            http: { ...http_js_1.default },
		            /**
		             * Determines whether external $ref pointers will be resolved.
		             * If this option is disabled, then none of above resolvers will be called.
		             * Instead, external $ref pointers will simply be ignored.
		             *
		             * @type {boolean}
		             */
		            external: true,
		        },
		        /**
		         * By default, JSON Schema $Ref Parser throws the first error it encounters. Setting `continueOnError` to `true`
		         * causes it to keep processing as much as possible and then throw a single error that contains all errors
		         * that were encountered.
		         */
		        continueOnError: false,
		        /**
		         * Determines the types of JSON references that are allowed.
		         */
		        dereference: {
		            /**
		             * Dereference circular (recursive) JSON references?
		             * If false, then a {@link ReferenceError} will be thrown if a circular reference is found.
		             * If "ignore", then circular references will not be dereferenced.
		             *
		             * @type {boolean|string}
		             */
		            circular: true,
		            /**
		             * A function, called for each path, which can return true to stop this path and all
		             * subpaths from being dereferenced further. This is useful in schemas where some
		             * subpaths contain literal $ref keys that should not be dereferenced.
		             *
		             * @type {function}
		             */
		            excludedPathMatcher: () => false,
		            referenceResolution: "relative",
		        },
		        mutateInputSchema: true,
		    };
		    return defaults;
		};
		exports.getJsonSchemaRefParserDefaultOptions = getJsonSchemaRefParserDefaultOptions;
		const getNewOptions = (options) => {
		    const newOptions = (0, exports.getJsonSchemaRefParserDefaultOptions)();
		    if (options) {
		        merge(newOptions, options);
		    }
		    return newOptions;
		};
		exports.getNewOptions = getNewOptions;
		/**
		 * Merges the properties of the source object into the target object.
		 *
		 * @param target - The object that we're populating
		 * @param source - The options that are being merged
		 * @returns
		 */
		function merge(target, source) {
		    if (isMergeable(source)) {
		        // prevent prototype pollution
		        const keys = Object.keys(source).filter((key) => !["__proto__", "constructor", "prototype"].includes(key));
		        for (let i = 0; i < keys.length; i++) {
		            const key = keys[i];
		            const sourceSetting = source[key];
		            const targetSetting = target[key];
		            if (isMergeable(sourceSetting)) {
		                // It's a nested object, so merge it recursively
		                target[key] = merge(targetSetting || {}, sourceSetting);
		            }
		            else if (sourceSetting !== undefined) {
		                // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.
		                target[key] = sourceSetting;
		            }
		        }
		    }
		    return target;
		}
		/**
		 * Determines whether the given value can be merged,
		 * or if it is a scalar value that should just override the target value.
		 *
		 * @param val
		 * @returns
		 */
		function isMergeable(val) {
		    return val && typeof val === "object" && !Array.isArray(val) && !(val instanceof RegExp) && !(val instanceof Date);
		} 
	} (options$1));
	return options$1;
}

var hasRequiredNormalizeArgs;

function requireNormalizeArgs () {
	if (hasRequiredNormalizeArgs) return normalizeArgs;
	hasRequiredNormalizeArgs = 1;
	Object.defineProperty(normalizeArgs, "__esModule", { value: true });
	normalizeArgs.normalizeArgs = normalizeArgs$1;
	const options_js_1 = requireOptions$1();
	/**
	 * Normalizes the given arguments, accounting for optional args.
	 */
	function normalizeArgs$1(_args) {
	    let path;
	    let schema;
	    let options;
	    let callback;
	    const args = Array.prototype.slice.call(_args);
	    if (typeof args[args.length - 1] === "function") {
	        // The last parameter is a callback function
	        callback = args.pop();
	    }
	    if (typeof args[0] === "string") {
	        // The first parameter is the path
	        path = args[0];
	        if (typeof args[2] === "object") {
	            // The second parameter is the schema, and the third parameter is the options
	            schema = args[1];
	            options = args[2];
	        }
	        else {
	            // The second parameter is the options
	            schema = undefined;
	            options = args[1];
	        }
	    }
	    else {
	        // The first parameter is the schema
	        path = "";
	        schema = args[0];
	        options = args[1];
	    }
	    try {
	        options = (0, options_js_1.getNewOptions)(options);
	    }
	    catch (e) {
	        console.error(`JSON Schema Ref Parser: Error normalizing options: ${e}`);
	    }
	    if (!options.mutateInputSchema && typeof schema === "object") {
	        // Make a deep clone of the schema, so that we don't alter the original object
	        schema = JSON.parse(JSON.stringify(schema));
	    }
	    return {
	        path,
	        schema,
	        options,
	        callback,
	    };
	}
	normalizeArgs.default = normalizeArgs$1;
	return normalizeArgs;
}

var resolveExternal = {};

var hasRequiredResolveExternal;

function requireResolveExternal () {
	if (hasRequiredResolveExternal) return resolveExternal;
	hasRequiredResolveExternal = 1;
	var __createBinding = (resolveExternal.__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 = (resolveExternal.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (resolveExternal.__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 = (resolveExternal.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(resolveExternal, "__esModule", { value: true });
	const ref_js_1 = __importDefault(requireRef());
	const pointer_js_1 = __importDefault(requirePointer());
	const parse_js_1 = __importDefault(requireParse());
	const url = __importStar(requireUrl());
	const errors_js_1 = requireErrors();
	/**
	 * Crawls the JSON schema, finds all external JSON references, and resolves their values.
	 * This method does not mutate the JSON schema. The resolved values are added to {@link $RefParser#$refs}.
	 *
	 * NOTE: We only care about EXTERNAL references here. INTERNAL references are only relevant when dereferencing.
	 *
	 * @returns
	 * The promise resolves once all JSON references in the schema have been resolved,
	 * including nested references that are contained in externally-referenced files.
	 */
	function resolveExternal$1(parser, options) {
	    if (!options.resolve?.external) {
	        // Nothing to resolve, so exit early
	        return Promise.resolve();
	    }
	    try {
	        // console.log('Resolving $ref pointers in %s', parser.$refs._root$Ref.path);
	        const promises = crawl(parser.schema, parser.$refs._root$Ref.path + "#", parser.$refs, options);
	        return Promise.all(promises);
	    }
	    catch (e) {
	        return Promise.reject(e);
	    }
	}
	/**
	 * Recursively crawls the given value, and resolves any external JSON references.
	 *
	 * @param obj - The value to crawl. If it's not an object or array, it will be ignored.
	 * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash
	 * @param {boolean} external - Whether `obj` was found in an external document.
	 * @param $refs
	 * @param options
	 * @param seen - Internal.
	 *
	 * @returns
	 * Returns an array of promises. There will be one promise for each JSON reference in `obj`.
	 * If `obj` does not contain any JSON references, then the array will be empty.
	 * If any of the JSON references point to files that contain additional JSON references,
	 * then the corresponding promise will internally reference an array of promises.
	 */
	function crawl(obj, path, $refs, options, seen, external) {
	    seen || (seen = new Set());
	    let promises = [];
	    if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !seen.has(obj)) {
	        seen.add(obj); // Track previously seen objects to avoid infinite recursion
	        if (ref_js_1.default.isExternal$Ref(obj)) {
	            promises.push(resolve$Ref(obj, path, $refs, options));
	        }
	        const keys = Object.keys(obj);
	        for (const key of keys) {
	            const keyPath = pointer_js_1.default.join(path, key);
	            const value = obj[key];
	            promises = promises.concat(crawl(value, keyPath, $refs, options, seen));
	        }
	    }
	    return promises;
	}
	/**
	 * Resolves the given JSON Reference, and then crawls the resulting value.
	 *
	 * @param $ref - The JSON Reference to resolve
	 * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash
	 * @param $refs
	 * @param options
	 *
	 * @returns
	 * The promise resolves once all JSON references in the object have been resolved,
	 * including nested references that are contained in externally-referenced files.
	 */
	async function resolve$Ref($ref, path, $refs, options) {
	    const shouldResolveOnCwd = options.dereference?.externalReferenceResolution === "root";
	    const resolvedPath = url.resolve(shouldResolveOnCwd ? url.cwd() : path, $ref.$ref);
	    const withoutHash = url.stripHash(resolvedPath);
	    // $ref.$ref = url.relative($refs._root$Ref.path, resolvedPath);
	    // Do we already have this $ref?
	    const ref = $refs._$refs[withoutHash];
	    if (ref) {
	        // We've already parsed this $ref, so use the existing value
	        return Promise.resolve(ref.value);
	    }
	    // Parse the $referenced file/url
	    try {
	        const result = await (0, parse_js_1.default)(resolvedPath, $refs, options);
	        // Crawl the parsed value
	        // console.log('Resolving $ref pointers in %s', withoutHash);
	        const promises = crawl(result, withoutHash + "#", $refs, options, new Set(), true);
	        return Promise.all(promises);
	    }
	    catch (err) {
	        if (!options?.continueOnError || !(0, errors_js_1.isHandledError)(err)) {
	            throw err;
	        }
	        if ($refs._$refs[withoutHash]) {
	            err.source = decodeURI(url.stripHash(path));
	            err.path = url.safePointerToPath(url.getHash(path));
	        }
	        return [];
	    }
	}
	resolveExternal.default = resolveExternal$1;
	return resolveExternal;
}

var bundle = {};

var hasRequiredBundle;

function requireBundle () {
	if (hasRequiredBundle) return bundle;
	hasRequiredBundle = 1;
	var __createBinding = (bundle.__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 = (bundle.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (bundle.__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 = (bundle.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(bundle, "__esModule", { value: true });
	const ref_js_1 = __importDefault(requireRef());
	const pointer_js_1 = __importDefault(requirePointer());
	const url = __importStar(requireUrl());
	/**
	 * Bundles all external JSON references into the main JSON schema, thus resulting in a schema that
	 * only has *internal* references, not any *external* references.
	 * This method mutates the JSON schema object, adding new references and re-mapping existing ones.
	 *
	 * @param parser
	 * @param options
	 */
	function bundle$1(parser, options) {
	    // console.log('Bundling $ref pointers in %s', parser.$refs._root$Ref.path);
	    // Build an inventory of all $ref pointers in the JSON Schema
	    const inventory = [];
	    crawl(parser, "schema", parser.$refs._root$Ref.path + "#", "#", 0, inventory, parser.$refs, options);
	    // Remap all $ref pointers
	    remap(inventory);
	}
	/**
	 * Recursively crawls the given value, and inventories all JSON references.
	 *
	 * @param parent - The object containing the value to crawl. If the value is not an object or array, it will be ignored.
	 * @param key - The property key of `parent` to be crawled
	 * @param path - The full path of the property being crawled, possibly with a JSON Pointer in the hash
	 * @param pathFromRoot - The path of the property being crawled, from the schema root
	 * @param indirections
	 * @param inventory - An array of already-inventoried $ref pointers
	 * @param $refs
	 * @param options
	 */
	function crawl(parent, key, path, pathFromRoot, indirections, inventory, $refs, options) {
	    const obj = key === null ? parent : parent[key];
	    if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj)) {
	        if (ref_js_1.default.isAllowed$Ref(obj)) {
	            inventory$Ref(parent, key, path, pathFromRoot, indirections, inventory, $refs, options);
	        }
	        else {
	            // Crawl the object in a specific order that's optimized for bundling.
	            // This is important because it determines how `pathFromRoot` gets built,
	            // which later determines which keys get dereferenced and which ones get remapped
	            const keys = Object.keys(obj).sort((a, b) => {
	                // Most people will expect references to be bundled into the the "definitions" property,
	                // so we always crawl that property first, if it exists.
	                if (a === "definitions") {
	                    return -1;
	                }
	                else if (b === "definitions") {
	                    return 1;
	                }
	                else {
	                    // Otherwise, crawl the keys based on their length.
	                    // This produces the shortest possible bundled references
	                    return a.length - b.length;
	                }
	            });
	            for (const key of keys) {
	                const keyPath = pointer_js_1.default.join(path, key);
	                const keyPathFromRoot = pointer_js_1.default.join(pathFromRoot, key);
	                const value = obj[key];
	                if (ref_js_1.default.isAllowed$Ref(value)) {
	                    inventory$Ref(obj, key, path, keyPathFromRoot, indirections, inventory, $refs, options);
	                }
	                else {
	                    crawl(obj, key, keyPath, keyPathFromRoot, indirections, inventory, $refs, options);
	                }
	            }
	        }
	    }
	}
	/**
	 * Inventories the given JSON Reference (i.e. records detailed information about it so we can
	 * optimize all $refs in the schema), and then crawls the resolved value.
	 *
	 * @param $refParent - The object that contains a JSON Reference as one of its keys
	 * @param $refKey - The key in `$refParent` that is a JSON Reference
	 * @param path - The full path of the JSON Reference at `$refKey`, possibly with a JSON Pointer in the hash
	 * @param indirections - unknown
	 * @param pathFromRoot - The path of the JSON Reference at `$refKey`, from the schema root
	 * @param inventory - An array of already-inventoried $ref pointers
	 * @param $refs
	 * @param options
	 */
	function inventory$Ref($refParent, $refKey, path, pathFromRoot, indirections, inventory, $refs, options) {
	    const $ref = $refKey === null ? $refParent : $refParent[$refKey];
	    const $refPath = url.resolve(path, $ref.$ref);
	    const pointer = $refs._resolve($refPath, pathFromRoot, options);
	    if (pointer === null) {
	        return;
	    }
	    const parsed = pointer_js_1.default.parse(pathFromRoot);
	    const depth = parsed.length;
	    const file = url.stripHash(pointer.path);
	    const hash = url.getHash(pointer.path);
	    const external = file !== $refs._root$Ref.path;
	    const extended = ref_js_1.default.isExtended$Ref($ref);
	    indirections += pointer.indirections;
	    const existingEntry = findInInventory(inventory, $refParent, $refKey);
	    if (existingEntry) {
	        // This $Ref has already been inventoried, so we don't need to process it again
	        if (depth < existingEntry.depth || indirections < existingEntry.indirections) {
	            removeFromInventory(inventory, existingEntry);
	        }
	        else {
	            return;
	        }
	    }
	    inventory.push({
	        $ref, // The JSON Reference (e.g. {$ref: string})
	        parent: $refParent, // The object that contains this $ref pointer
	        key: $refKey, // The key in `parent` that is the $ref pointer
	        pathFromRoot, // The path to the $ref pointer, from the JSON Schema root
	        depth, // How far from the JSON Schema root is this $ref pointer?
	        file, // The file that the $ref pointer resolves to
	        hash, // The hash within `file` that the $ref pointer resolves to
	        value: pointer.value, // The resolved value of the $ref pointer
	        circular: pointer.circular, // Is this $ref pointer DIRECTLY circular? (i.e. it references itself)
	        extended, // Does this $ref extend its resolved value? (i.e. it has extra properties, in addition to "$ref")
	        external, // Does this $ref pointer point to a file other than the main JSON Schema file?
	        indirections, // The number of indirect references that were traversed to resolve the value
	    });
	    // Recursively crawl the resolved value
	    if (!existingEntry || external) {
	        crawl(pointer.value, null, pointer.path, pathFromRoot, indirections + 1, inventory, $refs, options);
	    }
	}
	/**
	 * Re-maps every $ref pointer, so that they're all relative to the root of the JSON Schema.
	 * Each referenced value is dereferenced EXACTLY ONCE.  All subsequent references to the same
	 * value are re-mapped to point to the first reference.
	 *
	 * @example: {
	 *    first: { $ref: somefile.json#/some/part },
	 *    second: { $ref: somefile.json#/another/part },
	 *    third: { $ref: somefile.json },
	 *    fourth: { $ref: somefile.json#/some/part/sub/part }
	 *  }
	 *
	 * In this example, there are four references to the same file, but since the third reference points
	 * to the ENTIRE file, that's the only one we need to dereference.  The other three can just be
	 * remapped to point inside the third one.
	 *
	 * On the other hand, if the third reference DIDN'T exist, then the first and second would both need
	 * to be dereferenced, since they point to different parts of the file. The fourth reference does NOT
	 * need to be dereferenced, because it can be remapped to point inside the first one.
	 *
	 * @param inventory
	 */
	function remap(inventory) {
	    // Group & sort all the $ref pointers, so they're in the order that we need to dereference/remap them
	    inventory.sort((a, b) => {
	        if (a.file !== b.file) {
	            // Group all the $refs that point to the same file
	            return a.file < b.file ? -1 : 1;
	        }
	        else if (a.hash !== b.hash) {
	            // Group all the $refs that point to the same part of the file
	            return a.hash < b.hash ? -1 : 1;
	        }
	        else if (a.circular !== b.circular) {
	            // If the $ref points to itself, then sort it higher than other $refs that point to this $ref
	            return a.circular ? -1 : 1;
	        }
	        else if (a.extended !== b.extended) {
	            // If the $ref extends the resolved value, then sort it lower than other $refs that don't extend the value
	            return a.extended ? 1 : -1;
	        }
	        else if (a.indirections !== b.indirections) {
	            // Sort direct references higher than indirect references
	            return a.indirections - b.indirections;
	        }
	        else if (a.depth !== b.depth) {
	            // Sort $refs by how close they are to the JSON Schema root
	            return a.depth - b.depth;
	        }
	        else {
	            // Determine how far each $ref is from the "definitions" property.
	            // Most people will expect references to be bundled into the the "definitions" property if possible.
	            const aDefinitionsIndex = a.pathFromRoot.lastIndexOf("/definitions");
	            const bDefinitionsIndex = b.pathFromRoot.lastIndexOf("/definitions");
	            if (aDefinitionsIndex !== bDefinitionsIndex) {
	                // Give higher priority to the $ref that's closer to the "definitions" property
	                return bDefinitionsIndex - aDefinitionsIndex;
	            }
	            else {
	                // All else is equal, so use the shorter path, which will produce the shortest possible reference
	                return a.pathFromRoot.length - b.pathFromRoot.length;
	            }
	        }
	    });
	    let file, hash, pathFromRoot;
	    for (const entry of inventory) {
	        // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot);
	        if (!entry.external) {
	            // This $ref already resolves to the main JSON Schema file
	            entry.$ref.$ref = entry.hash;
	        }
	        else if (entry.file === file && entry.hash === hash) {
	            // This $ref points to the same value as the prevous $ref, so remap it to the same path
	            entry.$ref.$ref = pathFromRoot;
	        }
	        else if (entry.file === file && entry.hash.indexOf(hash + "/") === 0) {
	            // This $ref points to a sub-value of the prevous $ref, so remap it beneath that path
	            entry.$ref.$ref = pointer_js_1.default.join(pathFromRoot, pointer_js_1.default.parse(entry.hash.replace(hash, "#")));
	        }
	        else {
	            // We've moved to a new file or new hash
	            file = entry.file;
	            hash = entry.hash;
	            pathFromRoot = entry.pathFromRoot;
	            // This is the first $ref to point to this value, so dereference the value.
	            // Any other $refs that point to the same value will point to this $ref instead
	            entry.$ref = entry.parent[entry.key] = ref_js_1.default.dereference(entry.$ref, entry.value);
	            if (entry.circular) {
	                // This $ref points to itself
	                entry.$ref.$ref = entry.pathFromRoot;
	            }
	        }
	    }
	    // we want to ensure that any $refs that point to another $ref are remapped to point to the final value
	    // let hadChange = true;
	    // while (hadChange) {
	    //   hadChange = false;
	    //   for (const entry of inventory) {
	    //     if (entry.$ref && typeof entry.$ref === "object" && "$ref" in entry.$ref) {
	    //       const resolved = inventory.find((e: InventoryEntry) => e.pathFromRoot === entry.$ref.$ref);
	    //       if (resolved) {
	    //         const resolvedPointsToAnotherRef =
	    //           resolved.$ref && typeof resolved.$ref === "object" && "$ref" in resolved.$ref;
	    //         if (resolvedPointsToAnotherRef && entry.$ref.$ref !== resolved.$ref.$ref) {
	    //           // console.log('Re-mapping $ref pointer "%s" at %s', entry.$ref.$ref, entry.pathFromRoot);
	    //           entry.$ref.$ref = resolved.$ref.$ref;
	    //           hadChange = true;
	    //         }
	    //       }
	    //     }
	    //   }
	    // }
	}
	/**
	 * TODO
	 */
	function findInInventory(inventory, $refParent, $refKey) {
	    for (const existingEntry of inventory) {
	        if (existingEntry && existingEntry.parent === $refParent && existingEntry.key === $refKey) {
	            return existingEntry;
	        }
	    }
	    return undefined;
	}
	function removeFromInventory(inventory, entry) {
	    const index = inventory.indexOf(entry);
	    inventory.splice(index, 1);
	}
	bundle.default = bundle$1;
	return bundle;
}

var dereference = {};

var hasRequiredDereference;

function requireDereference () {
	if (hasRequiredDereference) return dereference;
	hasRequiredDereference = 1;
	var __createBinding = (dereference.__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 = (dereference.__setModuleDefault) || (Object.create ? (function(o, v) {
	    Object.defineProperty(o, "default", { enumerable: true, value: v });
	}) : function(o, v) {
	    o["default"] = v;
	});
	var __importStar = (dereference.__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 = (dereference.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(dereference, "__esModule", { value: true });
	const ref_js_1 = __importDefault(requireRef());
	const pointer_js_1 = __importDefault(requirePointer());
	const ono_1 = require$$6$1;
	const url = __importStar(requireUrl());
	const errors_1 = requireErrors();
	dereference.default = dereference$1;
	/**
	 * Crawls the JSON schema, finds all JSON references, and dereferences them.
	 * This method mutates the JSON schema object, replacing JSON references with their resolved value.
	 *
	 * @param parser
	 * @param options
	 */
	function dereference$1(parser, options) {
	    const start = Date.now();
	    // console.log('Dereferencing $ref pointers in %s', parser.$refs._root$Ref.path);
	    const dereferenced = crawl(parser.schema, parser.$refs._root$Ref.path, "#", new Set(), new Set(), new Map(), parser.$refs, options, start);
	    parser.$refs.circular = dereferenced.circular;
	    parser.schema = dereferenced.value;
	}
	/**
	 * Recursively crawls the given value, and dereferences any JSON references.
	 *
	 * @param obj - The value to crawl. If it's not an object or array, it will be ignored.
	 * @param path - The full path of `obj`, possibly with a JSON Pointer in the hash
	 * @param pathFromRoot - The path of `obj` from the schema root
	 * @param parents - An array of the parent objects that have already been dereferenced
	 * @param processedObjects - An array of all the objects that have already been processed
	 * @param dereferencedCache - An map of all the dereferenced objects
	 * @param $refs
	 * @param options
	 * @param startTime - The time when the dereferencing started
	 * @returns
	 */
	function crawl(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime) {
	    let dereferenced;
	    const result = {
	        value: obj,
	        circular: false,
	    };
	    if (options && options.timeoutMs) {
	        if (Date.now() - startTime > options.timeoutMs) {
	            throw new errors_1.TimeoutError(options.timeoutMs);
	        }
	    }
	    const derefOptions = (options.dereference || {});
	    const isExcludedPath = derefOptions.excludedPathMatcher || (() => false);
	    if (derefOptions?.circular === "ignore" || !processedObjects.has(obj)) {
	        if (obj && typeof obj === "object" && !ArrayBuffer.isView(obj) && !isExcludedPath(pathFromRoot)) {
	            parents.add(obj);
	            processedObjects.add(obj);
	            if (ref_js_1.default.isAllowed$Ref(obj, options)) {
	                dereferenced = dereference$Ref(obj, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
	                result.circular = dereferenced.circular;
	                result.value = dereferenced.value;
	            }
	            else {
	                for (const key of Object.keys(obj)) {
	                    const keyPath = pointer_js_1.default.join(path, key);
	                    const keyPathFromRoot = pointer_js_1.default.join(pathFromRoot, key);
	                    if (isExcludedPath(keyPathFromRoot)) {
	                        continue;
	                    }
	                    const value = obj[key];
	                    let circular = false;
	                    if (ref_js_1.default.isAllowed$Ref(value, options)) {
	                        dereferenced = dereference$Ref(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
	                        circular = dereferenced.circular;
	                        // Avoid pointless mutations; breaks frozen objects to no profit
	                        if (obj[key] !== dereferenced.value) {
	                            obj[key] = dereferenced.value;
	                            derefOptions?.onDereference?.(value.$ref, obj[key], obj, key);
	                        }
	                    }
	                    else {
	                        if (!parents.has(value)) {
	                            dereferenced = crawl(value, keyPath, keyPathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
	                            circular = dereferenced.circular;
	                            // Avoid pointless mutations; breaks frozen objects to no profit
	                            if (obj[key] !== dereferenced.value) {
	                                obj[key] = dereferenced.value;
	                            }
	                        }
	                        else {
	                            circular = foundCircularReference(keyPath, $refs, options);
	                        }
	                    }
	                    // Set the "isCircular" flag if this or any other property is circular
	                    result.circular = result.circular || circular;
	                }
	            }
	            parents.delete(obj);
	        }
	    }
	    return result;
	}
	/**
	 * Dereferences the given JSON Reference, and then crawls the resulting value.
	 *
	 * @param $ref - The JSON Reference to resolve
	 * @param path - The full path of `$ref`, possibly with a JSON Pointer in the hash
	 * @param pathFromRoot - The path of `$ref` from the schema root
	 * @param parents - An array of the parent objects that have already been dereferenced
	 * @param processedObjects - An array of all the objects that have already been dereferenced
	 * @param dereferencedCache - An map of all the dereferenced objects
	 * @param $refs
	 * @param options
	 * @returns
	 */
	function dereference$Ref($ref, path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime) {
	    const isExternalRef = ref_js_1.default.isExternal$Ref($ref);
	    const shouldResolveOnCwd = isExternalRef && options?.dereference?.externalReferenceResolution === "root";
	    const $refPath = url.resolve(shouldResolveOnCwd ? url.cwd() : path, $ref.$ref);
	    const cache = dereferencedCache.get($refPath);
	    if (cache && !cache.circular) {
	        const refKeys = Object.keys($ref);
	        if (refKeys.length > 1) {
	            const extraKeys = {};
	            for (const key of refKeys) {
	                if (key !== "$ref" && !(key in cache.value)) {
	                    // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
	                    extraKeys[key] = $ref[key];
	                }
	            }
	            return {
	                circular: cache.circular,
	                value: Object.assign({}, cache.value, extraKeys),
	            };
	        }
	        return cache;
	    }
	    const pointer = $refs._resolve($refPath, path, options);
	    if (pointer === null) {
	        return {
	            circular: false,
	            value: null,
	        };
	    }
	    // Check for circular references
	    const directCircular = pointer.circular;
	    let circular = directCircular || parents.has(pointer.value);
	    if (circular) {
	        foundCircularReference(path, $refs, options);
	    }
	    // Dereference the JSON reference
	    let dereferencedValue = ref_js_1.default.dereference($ref, pointer.value);
	    // Crawl the dereferenced value (unless it's circular)
	    if (!circular) {
	        // Determine if the dereferenced value is circular
	        const dereferenced = crawl(dereferencedValue, pointer.path, pathFromRoot, parents, processedObjects, dereferencedCache, $refs, options, startTime);
	        circular = dereferenced.circular;
	        dereferencedValue = dereferenced.value;
	    }
	    if (circular && !directCircular && options.dereference?.circular === "ignore") {
	        // The user has chosen to "ignore" circular references, so don't change the value
	        dereferencedValue = $ref;
	    }
	    if (directCircular) {
	        // The pointer is a DIRECT circular reference (i.e. it references itself).
	        // So replace the $ref path with the absolute path from the JSON Schema root
	        dereferencedValue.$ref = pathFromRoot;
	    }
	    const dereferencedObject = {
	        circular,
	        value: dereferencedValue,
	    };
	    // only cache if no extra properties than $ref
	    if (Object.keys($ref).length === 1) {
	        dereferencedCache.set($refPath, dereferencedObject);
	    }
	    return dereferencedObject;
	}
	/**
	 * Called when a circular reference is found.
	 * It sets the {@link $Refs#circular} flag, and throws an error if options.dereference.circular is false.
	 *
	 * @param keyPath - The JSON Reference path of the circular reference
	 * @param $refs
	 * @param options
	 * @returns - always returns true, to indicate that a circular reference was found
	 */
	function foundCircularReference(keyPath, $refs, options) {
	    $refs.circular = true;
	    if (!options.dereference.circular) {
	        throw ono_1.ono.reference(`Circular $ref pointer found at ${keyPath}`);
	    }
	    return true;
	}
	return dereference;
}

var maybe$1 = {};

var next$1 = {};

var hasRequiredNext$1;

function requireNext$1 () {
	if (hasRequiredNext$1) return next$1;
	hasRequiredNext$1 = 1;
	Object.defineProperty(next$1, "__esModule", { value: true });
	function makeNext() {
	    if (typeof api === "object" && typeof api.nextTick === "function") {
	        return api.nextTick;
	    }
	    else if (typeof setImmediate === "function") {
	        return setImmediate;
	    }
	    else {
	        return function next(f) {
	            setTimeout(f, 0);
	        };
	    }
	}
	next$1.default = makeNext();
	return next$1;
}

var hasRequiredMaybe$1;

function requireMaybe$1 () {
	if (hasRequiredMaybe$1) return maybe$1;
	hasRequiredMaybe$1 = 1;
	var __importDefault = (maybe$1.__importDefault) || function (mod) {
	    return (mod && mod.__esModule) ? mod : { "default": mod };
	};
	Object.defineProperty(maybe$1, "__esModule", { value: true });
	maybe$1.default = maybe;
	const next_js_1 = __importDefault(requireNext$1());
	function maybe(cb, promise) {
	    if (cb) {
	        promise.then(function (result) {
	            (0, next_js_1.default)(function () {
	                cb(null, result);
	            });
	        }, function (err) {
	            (0, next_js_1.default)(function () {
	                cb(err);
	            });
	        });
	        return undefined;
	    }
	    else {
	        return promise;
	    }
	}
	return maybe$1;
}

var hasRequiredLib$1;

function requireLib$1 () {
	if (hasRequiredLib$1) return lib$1;
	hasRequiredLib$1 = 1;
	(function (exports) {
		var __createBinding = (lib$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 __setModuleDefault = (lib$1.__setModuleDefault) || (Object.create ? (function(o, v) {
		    Object.defineProperty(o, "default", { enumerable: true, value: v });
		}) : function(o, v) {
		    o["default"] = v;
		});
		var __importStar = (lib$1.__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 = (lib$1.__importDefault) || function (mod) {
		    return (mod && mod.__esModule) ? mod : { "default": mod };
		};
		Object.defineProperty(exports, "__esModule", { value: true });
		exports.getJsonSchemaRefParserDefaultOptions = exports.jsonSchemaParserNormalizeArgs = exports.dereferenceInternal = exports.JSONParserErrorGroup = exports.isHandledError = exports.UnmatchedParserError = exports.ParserError = exports.ResolverError = exports.MissingPointerError = exports.InvalidPointerError = exports.JSONParserError = exports.UnmatchedResolverError = exports.dereference = exports.bundle = exports.resolve = exports.parse = exports.$RefParser = undefined;
		const refs_js_1 = __importDefault(requireRefs());
		const parse_js_1 = __importDefault(requireParse());
		const normalize_args_js_1 = __importDefault(requireNormalizeArgs());
		exports.jsonSchemaParserNormalizeArgs = normalize_args_js_1.default;
		const resolve_external_js_1 = __importDefault(requireResolveExternal());
		const bundle_js_1 = __importDefault(requireBundle());
		const dereference_js_1 = __importDefault(requireDereference());
		exports.dereferenceInternal = dereference_js_1.default;
		const url = __importStar(requireUrl());
		const errors_js_1 = requireErrors();
		Object.defineProperty(exports, "JSONParserError", { enumerable: true, get: function () { return errors_js_1.JSONParserError; } });
		Object.defineProperty(exports, "InvalidPointerError", { enumerable: true, get: function () { return errors_js_1.InvalidPointerError; } });
		Object.defineProperty(exports, "MissingPointerError", { enumerable: true, get: function () { return errors_js_1.MissingPointerError; } });
		Object.defineProperty(exports, "ResolverError", { enumerable: true, get: function () { return errors_js_1.ResolverError; } });
		Object.defineProperty(exports, "ParserError", { enumerable: true, get: function () { return errors_js_1.ParserError; } });
		Object.defineProperty(exports, "UnmatchedParserError", { enumerable: true, get: function () { return errors_js_1.UnmatchedParserError; } });
		Object.defineProperty(exports, "UnmatchedResolverError", { enumerable: true, get: function () { return errors_js_1.UnmatchedResolverError; } });
		Object.defineProperty(exports, "isHandledError", { enumerable: true, get: function () { return errors_js_1.isHandledError; } });
		Object.defineProperty(exports, "JSONParserErrorGroup", { enumerable: true, get: function () { return errors_js_1.JSONParserErrorGroup; } });
		const ono_1 = require$$6$1;
		const maybe_js_1 = __importDefault(requireMaybe$1());
		const options_js_1 = requireOptions$1();
		Object.defineProperty(exports, "getJsonSchemaRefParserDefaultOptions", { enumerable: true, get: function () { return options_js_1.getJsonSchemaRefParserDefaultOptions; } });
		/**
		 * This class parses a JSON schema, builds a map of its JSON references and their resolved values,
		 * and provides methods for traversing, manipulating, and dereferencing those references.
		 *
		 * @class
		 */
		class $RefParser {
		    constructor() {
		        /**
		         * The parsed (and possibly dereferenced) JSON schema object
		         *
		         * @type {object}
		         * @readonly
		         */
		        this.schema = null;
		        /**
		         * The resolved JSON references
		         *
		         * @type {$Refs}
		         * @readonly
		         */
		        this.$refs = new refs_js_1.default();
		    }
		    async parse() {
		        const args = (0, normalize_args_js_1.default)(arguments);
		        let promise;
		        if (!args.path && !args.schema) {
		            const err = (0, ono_1.ono)(`Expected a file path, URL, or object. Got ${args.path || args.schema}`);
		            return (0, maybe_js_1.default)(args.callback, Promise.reject(err));
		        }
		        // Reset everything
		        this.schema = null;
		        this.$refs = new refs_js_1.default();
		        // If the path is a filesystem path, then convert it to a URL.
		        // NOTE: According to the JSON Reference spec, these should already be URLs,
		        // but, in practice, many people use local filesystem paths instead.
		        // So we're being generous here and doing the conversion automatically.
		        // This is not intended to be a 100% bulletproof solution.
		        // If it doesn't work for your use-case, then use a URL instead.
		        let pathType = "http";
		        if (url.isFileSystemPath(args.path)) {
		            args.path = url.fromFileSystemPath(args.path);
		            pathType = "file";
		        }
		        else if (!args.path && args.schema && "$id" in args.schema && args.schema.$id) {
		            // when schema id has defined an URL should use that hostname to request the references,
		            // instead of using the current page URL
		            const params = url.parse(args.schema.$id);
		            const port = params.protocol === "https:" ? 443 : 80;
		            args.path = `${params.protocol}//${params.hostname}:${port}`;
		        }
		        // Resolve the absolute path of the schema
		        args.path = url.resolve(url.cwd(), args.path);
		        if (args.schema && typeof args.schema === "object") {
		            // A schema object was passed-in.
		            // So immediately add a new $Ref with the schema object as its value
		            const $ref = this.$refs._add(args.path);
		            $ref.value = args.schema;
		            $ref.pathType = pathType;
		            promise = Promise.resolve(args.schema);
		        }
		        else {
		            // Parse the schema file/url
		            promise = (0, parse_js_1.default)(args.path, this.$refs, args.options);
		        }
		        try {
		            const result = await promise;
		            if (result !== null && typeof result === "object" && !Buffer.isBuffer(result)) {
		                this.schema = result;
		                return (0, maybe_js_1.default)(args.callback, Promise.resolve(this.schema));
		            }
		            else if (args.options.continueOnError) {
		                this.schema = null; // it's already set to null at line 79, but let's set it again for the sake of readability
		                return (0, maybe_js_1.default)(args.callback, Promise.resolve(this.schema));
		            }
		            else {
		                throw ono_1.ono.syntax(`"${this.$refs._root$Ref.path || result}" is not a valid JSON Schema`);
		            }
		        }
		        catch (err) {
		            if (!args.options.continueOnError || !(0, errors_js_1.isHandledError)(err)) {
		                return (0, maybe_js_1.default)(args.callback, Promise.reject(err));
		            }
		            if (this.$refs._$refs[url.stripHash(args.path)]) {
		                this.$refs._$refs[url.stripHash(args.path)].addError(err);
		            }
		            return (0, maybe_js_1.default)(args.callback, Promise.resolve(null));
		        }
		    }
		    static parse() {
		        const parser = new $RefParser();
		        return parser.parse.apply(parser, arguments);
		    }
		    async resolve() {
		        const args = (0, normalize_args_js_1.default)(arguments);
		        try {
		            await this.parse(args.path, args.schema, args.options);
		            await (0, resolve_external_js_1.default)(this, args.options);
		            finalize(this);
		            return (0, maybe_js_1.default)(args.callback, Promise.resolve(this.$refs));
		        }
		        catch (err) {
		            return (0, maybe_js_1.default)(args.callback, Promise.reject(err));
		        }
		    }
		    static resolve() {
		        const instance = new $RefParser();
		        return instance.resolve.apply(instance, arguments);
		    }
		    static bundle() {
		        const instance = new $RefParser();
		        return instance.bundle.apply(instance, arguments);
		    }
		    async bundle() {
		        const args = (0, normalize_args_js_1.default)(arguments);
		        try {
		            await this.resolve(args.path, args.schema, args.options);
		            (0, bundle_js_1.default)(this, args.options);
		            finalize(this);
		            return (0, maybe_js_1.default)(args.callback, Promise.resolve(this.schema));
		        }
		        catch (err) {
		            return (0, maybe_js_1.default)(args.callback, Promise.reject(err));
		        }
		    }
		    static dereference() {
		        const instance = new $RefParser();
		        return instance.dereference.apply(instance, arguments);
		    }
		    async dereference() {
		        const args = (0, normalize_args_js_1.default)(arguments);
		        try {
		            await this.resolve(args.path, args.schema, args.options);
		            (0, dereference_js_1.default)(this, args.options);
		            finalize(this);
		            return (0, maybe_js_1.default)(args.callback, Promise.resolve(this.schema));
		        }
		        catch (err) {
		            return (0, maybe_js_1.default)(args.callback, Promise.reject(err));
		        }
		    }
		}
		exports.$RefParser = $RefParser;
		exports.default = $RefParser;
		function finalize(parser) {
		    const errors = errors_js_1.JSONParserErrorGroup.getParserErrors(parser);
		    if (errors.length > 0) {
		        throw new errors_js_1.JSONParserErrorGroup(parser);
		    }
		}
		exports.parse = $RefParser.parse;
		exports.resolve = $RefParser.resolve;
		exports.bundle = $RefParser.bundle;
		exports.dereference = $RefParser.dereference; 
	} (lib$1));
	return lib$1;
}

var options;
var hasRequiredOptions;

function requireOptions () {
	if (hasRequiredOptions) return options;
	hasRequiredOptions = 1;

	const { getJsonSchemaRefParserDefaultOptions } = requireLib$1();
	const schemaValidator = requireSchema$1();
	const specValidator = requireSpec();

	options = ParserOptions;



	/**
	 * Merges the properties of the source object into the target object.
	 *
	 * @param target - The object that we're populating
	 * @param source - The options that are being merged
	 * @returns
	 */
	function merge (target, source) {
	  if (isMergeable(source)) {
	    // prevent prototype pollution
	    const keys = Object.keys(source).filter((key) => !["__proto__", "constructor", "prototype"].includes(key));
	    for (let i = 0; i < keys.length; i++) {
	      const key = keys[i];
	      const sourceSetting = source[key];
	      const targetSetting = target[key];

	      if (isMergeable(sourceSetting)) {
	        // It's a nested object, so merge it recursively
	        target[key] = merge(targetSetting || {}, sourceSetting);
	      }
	      else if (sourceSetting !== undefined) {
	        // It's a scalar value, function, or array. No merging necessary. Just overwrite the target value.
	        target[key] = sourceSetting;
	      }
	    }
	  }
	  return target;
	}
	/**
	 * Determines whether the given value can be merged,
	 * or if it is a scalar value that should just override the target value.
	 *
	 * @param val
	 * @returns
	 */
	function isMergeable (val) {
	  return val && typeof val === "object" && !Array.isArray(val) && !(val instanceof RegExp) && !(val instanceof Date);
	}

	/**
	 * Options that determine how Swagger APIs are parsed, resolved, dereferenced, and validated.
	 *
	 * @param {object|ParserOptions} [_options] - Overridden options
	 * @class
	 * @augments $RefParserOptions
	 */
	function ParserOptions (_options) {
	  const defaultOptions = getJsonSchemaRefParserDefaultOptions();
	  const options = merge(defaultOptions, ParserOptions.defaults);
	  return merge(options, _options);
	}

	ParserOptions.defaults = {
	  /**
	   * Determines how the API definition will be validated.
	   *
	   * You can add additional validators of your own, replace an existing one with
	   * your own implemenation, or disable any validator by setting it to false.
	   */
	  validate: {
	    schema: schemaValidator,
	    spec: specValidator,
	  },
	};
	return options;
}

var next;
var hasRequiredNext;

function requireNext () {
	if (hasRequiredNext) return next;
	hasRequiredNext = 1;

	function makeNext () {
	  if (typeof api === 'object' && typeof api.nextTick === 'function') {
	    return api.nextTick
	  } else if (typeof setImmediate === 'function') {
	    return setImmediate
	  } else {
	    return function next (f) {
	      setTimeout(f, 0);
	    }
	  }
	}

	next = makeNext();
	return next;
}

var maybe;
var hasRequiredMaybe;

function requireMaybe () {
	if (hasRequiredMaybe) return maybe;
	hasRequiredMaybe = 1;

	var next = requireNext();

	maybe = function maybe (cb, promise) {
	  if (cb) {
	    promise
	      .then(function (result) {
	        next(function () { cb(null, result); });
	      }, function (err) {
	        next(function () { cb(err); });
	      });
	    return undefined
	  }
	  else {
	    return promise
	  }
	};
	return maybe;
}

/* eslint-disable no-unused-vars */

var lib;
var hasRequiredLib;

function requireLib () {
	if (hasRequiredLib) return lib;
	hasRequiredLib = 1;

	const validateSchema = requireSchema$1();
	const validateSpec = requireSpec();
	const { jsonSchemaParserNormalizeArgs: normalizeArgs } = requireLib$1();
	const util = requireUtil$1();
	const Options = requireOptions();
	const maybe = requireMaybe();
	const { ono } = require$$6$1;
	const { $RefParser } = requireLib$1();
	const { dereferenceInternal: dereference } = requireLib$1();

	const supported31Versions = ["3.1.0", "3.1.1"];
	const supported30Versions = ["3.0.0", "3.0.1", "3.0.2", "3.0.3", "3.0.4"];
	const supportedVersions = [...supported31Versions, ...supported30Versions];

	/**
	 * This class parses a Swagger 2.0 or 3.0 API, resolves its JSON references and their resolved values,
	 * and provides methods for traversing, dereferencing, and validating the API.
	 *
	 * @class
	 * @augments $RefParser
	 */
	class SwaggerParser extends $RefParser {

	  /**
	   * Parses the given Swagger API.
	   * This method does not resolve any JSON references.
	   * It just reads a single file in JSON or YAML format, and parse it as a JavaScript object.
	   *
	   * @param {string} [path] - The file path or URL of the JSON schema
	   * @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
	   * @param {ParserOptions} [options] - Options that determine how the API is parsed
	   * @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
	   * @returns {Promise} - The returned promise resolves with the parsed API object.
	   */
	  async parse (path, api, options, callback) {
	    let args = normalizeArgs(arguments);
	    args.options = new Options(args.options);

	    try {
	      let schema = await super.parse(args.path, args.schema, args.options);

	      if (schema.swagger) {
	        // Verify that the parsed object is a Swagger API
	        if (schema.swagger === undefined || schema.info === undefined || schema.paths === undefined) {
	          throw ono.syntax(`${args.path || args.schema} is not a valid Swagger API definition`);
	        }
	        else if (typeof schema.swagger === "number") {
	          // This is a very common mistake, so give a helpful error message
	          throw ono.syntax('Swagger version number must be a string (e.g. "2.0") not a number.');
	        }
	        else if (typeof schema.info.version === "number") {
	          // This is a very common mistake, so give a helpful error message
	          throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.');
	        }
	        else if (schema.swagger !== "2.0") {
	          throw ono.syntax(`Unrecognized Swagger version: ${schema.swagger}. Expected 2.0`);
	        }
	      }
	      else {
	        // Verify that the parsed object is a Openapi API
	        if (schema.openapi === undefined || schema.info === undefined) {
	          throw ono.syntax(`${args.path || args.schema} is not a valid Openapi API definition`);
	        }
	        else if (schema.paths === undefined) {
	          if (supported31Versions.indexOf(schema.openapi) !== -1) {
	            if (schema.webhooks === undefined) {
	              throw ono.syntax(`${args.path || args.schema} is not a valid Openapi API definition`);
	            }
	          }
	          else {
	            throw ono.syntax(`${args.path || args.schema} is not a valid Openapi API definition`);
	          }
	        }
	        else if (typeof schema.openapi === "number") {
	          // This is a very common mistake, so give a helpful error message
	          throw ono.syntax('Openapi version number must be a string (e.g. "3.0.0") not a number.');
	        }
	        else if (typeof schema.info.version === "number") {
	          // This is a very common mistake, so give a helpful error message
	          throw ono.syntax('API version number must be a string (e.g. "1.0.0") not a number.');
	        }
	        else if (supportedVersions.indexOf(schema.openapi) === -1) {
	          throw ono.syntax(
	            `Unsupported OpenAPI version: ${schema.openapi}. ` +
	            `Swagger Parser only supports versions ${supportedVersions.join(", ")}`
	          );
	        }

	        // This is an OpenAPI v3 schema, check if the "servers" have any relative paths and
	        // fix them if the content was pulled from a web resource
	        util.fixOasRelativeServers(schema, args.path);
	      }

	      // Looks good!
	      return maybe(args.callback, Promise.resolve(schema));
	    }
	    catch (err) {
	      return maybe(args.callback, Promise.reject(err));
	    }
	  }

	  /**
	   * Parses, dereferences, and validates the given Swagger API.
	   * Depending on the options, validation can include JSON Schema validation and/or Swagger Spec validation.
	   *
	   * @param {string} [path] - The file path or URL of the JSON schema
	   * @param {object} [api] - The Swagger API object. This object will be used instead of reading from `path`.
	   * @param {ParserOptions} [options] - Options that determine how the API is parsed, dereferenced, and validated
	   * @param {Function} [callback] - An error-first callback. The second parameter is the parsed API object.
	   * @returns {Promise} - The returned promise resolves with the parsed API object.
	   */
	  async validate (path, api, options, callback) {
	    let me = this;
	    let args = normalizeArgs(arguments);
	    args.options = new Options(args.options);

	    // ZSchema doesn't support circular objects, so don't dereference circular $refs yet
	    // (see https://github.com/zaggino/z-schema/issues/137)
	    let circular$RefOption = args.options.dereference.circular;
	    args.options.validate.schema && (args.options.dereference.circular = "ignore");

	    try {
	      await this.dereference(args.path, args.schema, args.options);

	      // Restore the original options, now that we're done dereferencing
	      args.options.dereference.circular = circular$RefOption;

	      if (args.options.validate.schema) {
	        // Validate the API against the Swagger schema
	        // NOTE: This is safe to do, because we haven't dereferenced circular $refs yet
	        validateSchema(me.api);

	        if (me.$refs.circular) {
	          if (circular$RefOption === true) {
	            // The API has circular references,
	            // so we need to do a second-pass to fully-dereference it
	            dereference(me, args.options);
	          }
	          else if (circular$RefOption === false) {
	            // The API has circular references, and they're not allowed, so throw an error
	            throw ono.reference("The API contains circular references");
	          }
	        }
	      }

	      if (args.options.validate.spec) {
	        // Validate the API against the Swagger spec
	        validateSpec(me.api);
	      }

	      return maybe(args.callback, Promise.resolve(me.schema));
	    }
	    catch (err) {
	      return maybe(args.callback, Promise.reject(err));
	    }
	  }
	}


	/**
	 * Alias {@link $RefParser#schema} as {@link SwaggerParser#api}
	 */
	Object.defineProperty(SwaggerParser.prototype, "api", {
	  configurable: true,
	  enumerable: true,
	  get () {
	    return this.schema;
	  }
	});

	/**
	 * The Swagger object
	 * https://github.com/OAI/OpenAPI-Specification/blob/master/versions/2.0.md#swagger-object
	 *
	 * @typedef {{swagger: string, info: {}, paths: {}}} SwaggerObject
	 */

	const defaultExport = SwaggerParser;

	defaultExport.validate = (...args) => {
	  const defaultInstance = new SwaggerParser();
	  return defaultInstance.validate(...args);
	};
	defaultExport.dereference = (...args) => {
	  const defaultInstance = new SwaggerParser();
	  return defaultInstance.dereference(...args);
	};
	defaultExport.bundle = (...args) => {
	  const defaultInstance = new SwaggerParser();
	  return defaultInstance.bundle(...args);
	};
	defaultExport.parse = (...args) => {
	  const defaultInstance = new SwaggerParser();
	  return defaultInstance.parse(...args);
	};
	defaultExport.resolve = (...args) => {
	  const defaultInstance = new SwaggerParser();
	  return defaultInstance.resolve(...args);
	};
	defaultExport.default = defaultExport;
	defaultExport.SwaggerParser = defaultExport;

	lib = defaultExport;
	return lib;
}

var libExports = requireLib();
var OpenAPIParser = /*@__PURE__*/getDefaultExportFromCjs(libExports);

const supportedHttpMethods = new Set([
    "delete",
    "get",
    "head",
    "patch",
    "post",
    "put",
]);

function generateHelpers(context) {
    const helpers = [];
    if (usesDefaultResponse(context)) {
        helpers.push(DEFAULT_RESPONSE_TEMPLATE);
    }
    if (helpers.length) {
        return `namespace GeneratedHelpers {\n${helpers.join("\n")}\n}`;
    }
    return "";
}
const DEFAULT_RESPONSE_TEMPLATE = `
@doc(Description)
@error
model DefaultResponse<Description extends valueof string = "", Body = void, Headers extends {} = {}> {
  @body body: Body;
  ...Headers;
}
`.trim();
function usesDefaultResponse(context) {
    const doc = context.openApi3Doc;
    // Check #/components/responses for status codes
    for (const [statusCode] of Object.keys(doc.components?.responses ?? {})) {
        if (statusCode === "default")
            return true;
    }
    // Check #/paths/{path}/{method}/responses for status codes
    for (const pathItem of Object.values(doc.paths)) {
        for (const method of supportedHttpMethods) {
            const operation = pathItem[method];
            if (!operation)
                continue;
            for (const statusCode of Object.keys(operation.responses ?? {})) {
                if (statusCode === "default")
                    return true;
            }
        }
    }
    return false;
}

const validLocations = ["header", "query", "path"];
const extensionDecoratorName = "extension";
function getExtensions(element) {
    const decorators = [];
    for (const key of Object.keys(element)) {
        if (isExtensionKey(key)) {
            decorators.push({
                name: extensionDecoratorName,
                args: [key, element[key]],
            });
        }
    }
    return decorators;
}
function isExtensionKey(key) {
    return key.startsWith("x-");
}
function getParameterDecorators(parameter) {
    const decorators = [];
    decorators.push(...getExtensions(parameter));
    decorators.push(...getDecoratorsForSchema(parameter.schema));
    const locationDecorator = getLocationDecorator(parameter);
    if (locationDecorator)
        decorators.push(locationDecorator);
    return decorators;
}
function getLocationDecorator(parameter) {
    if (!validLocations.includes(parameter.in))
        return;
    const decorator = {
        name: parameter.in,
        args: [],
    };
    let format;
    let decoratorArgs;
    switch (parameter.in) {
        case "header":
            format = getHeaderFormat(parameter.style);
            break;
        case "query":
            decoratorArgs = getQueryArgs(parameter);
            break;
    }
    if (format) {
        decorator.args.push({ format });
    }
    if (decoratorArgs) {
        decorator.args.push(decoratorArgs);
    }
    return decorator;
}
function getQueryArgs(parameter) {
    const queryOptions = getNormalizedQueryOptions(parameter);
    if (Object.keys(queryOptions).length) {
        return {
            __kind: "value",
            value: `#{${Object.entries(queryOptions)
                .map(([key, value]) => {
                return `${key}: ${JSON.stringify(value)}`;
            })
                .join(", ")}}`,
        };
    }
    return;
}
function getNormalizedQueryOptions({ explode, style = "", }) {
    const queryOptions = {};
    // In OpenAPI 3, default style is 'form', and explode is true when 'form' is the style
    if (typeof explode !== "boolean") {
        if (style === "form" || !style) {
            explode = true;
        }
        else {
            explode = false;
        }
    }
    // Format only emits additional data if set to one of the following:
    // ssv (spaceDelimited), pipes (pipeDelimited)
    if (style === "spaceDelimited") {
        queryOptions.format = "ssv";
    }
    else if (style === "pipeDelimited") {
        queryOptions.format = "pipes";
    }
    // In TypeSpec, default explode is "false"
    if (!explode && queryOptions.format) {
        queryOptions.explode = false;
    }
    else if (explode) {
        queryOptions.explode = true;
    }
    return queryOptions;
}
function getHeaderFormat(style) {
    return style === "simple" ? "simple" : undefined;
}
function getDecoratorsForSchema(schema) {
    const decorators = [];
    if ("$ref" in schema) {
        return decorators;
    }
    decorators.push(...getExtensions(schema));
    switch (schema.type) {
        case "array":
            decorators.push(...getArraySchemaDecorators(schema));
            break;
        case "integer":
        case "number":
            decorators.push(...getNumberSchemaDecorators(schema));
            break;
        case "string":
            decorators.push(...getStringSchemaDecorators(schema));
            break;
    }
    if (schema.title) {
        decorators.push({ name: "summary", args: [schema.title] });
    }
    if (schema.discriminator) {
        decorators.push({ name: "discriminator", args: [schema.discriminator.propertyName] });
    }
    if (schema.oneOf) {
        decorators.push(...getOneOfSchemaDecorators());
    }
    return decorators;
}
function getOneOfSchemaDecorators(schema) {
    return [{ name: "oneOf", args: [] }];
}
function getArraySchemaDecorators(schema) {
    const decorators = [];
    if (typeof schema.minItems === "number") {
        decorators.push({ name: "minItems", args: [schema.minItems] });
    }
    if (typeof schema.maxItems === "number") {
        decorators.push({ name: "maxItems", args: [schema.maxItems] });
    }
    return decorators;
}
function getNumberSchemaDecorators(schema) {
    const decorators = [];
    if (typeof schema.minimum === "number") {
        if (schema.exclusiveMinimum) {
            decorators.push({ name: "minValueExclusive", args: [schema.minimum] });
        }
        else {
            decorators.push({ name: "minValue", args: [schema.minimum] });
        }
    }
    if (typeof schema.maximum === "number") {
        if (schema.exclusiveMaximum) {
            decorators.push({ name: "maxValueExclusive", args: [schema.maximum] });
        }
        else {
            decorators.push({ name: "maxValue", args: [schema.maximum] });
        }
    }
    return decorators;
}
const knownStringFormats = new Set([
    "binary",
    "byte",
    "date",
    "date-time",
    "time",
    "duration",
    "uri",
]);
function getStringSchemaDecorators(schema) {
    const decorators = [];
    if (typeof schema.minLength === "number") {
        decorators.push({ name: "minLength", args: [schema.minLength] });
    }
    if (typeof schema.maxLength === "number") {
        decorators.push({ name: "maxLength", args: [schema.maxLength] });
    }
    if (typeof schema.pattern === "string") {
        decorators.push({ name: "pattern", args: [escapeRegex(schema.pattern)] });
    }
    if (typeof schema.format === "string" && !knownStringFormats.has(schema.format)) {
        decorators.push({ name: "format", args: [schema.format] });
    }
    return decorators;
}
function escapeRegex(str) {
    return str.replace(/\\/g, "\\\\");
}

function generateDocs(doc) {
    if (isEmptyDoc(doc)) {
        return ``;
    }
    const split = splitNewlines(doc);
    for (let i = 0; i < split.length; i++) {
        if (split[i].includes("@") || split[i].includes("*/")) {
            if (split.length === 1) {
                return `@doc("${split[0].replace(/\\/g, "\\\\").replace(/"/g, '\\"')}")`;
            }
            return `@doc("""\n${split.join("\n").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}\n""")`;
        }
    }
    return `/**\n* ${split.join("\n* ")}\n*/`;
}
function splitNewlines(doc) {
    let docString = Array.isArray(doc) ? doc.join("\n") : doc;
    docString = docString.replace(/\r\n/g, "\n");
    docString = docString.replace(/\r/g, "\n");
    if (!docString.includes("\n")) {
        return [docString];
    }
    return docString.split("\n");
}
function isEmptyDoc(doc) {
    if (!doc) {
        return true;
    }
    if (Array.isArray(doc) && !doc.length) {
        return true;
    }
    return false;
}

function generateDecorator({ name, args }) {
    const hasArgs = args.length;
    const stringifiedArguments = hasArgs
        ? `(${args.map((a) => (isTSValue(a) ? a.value : JSON.stringify(a))).join(", ")})`
        : "";
    return `@${name}${stringifiedArguments}`;
}
function generateDecorators(decorators) {
    const uniqueDecorators = new Set(decorators.map(generateDecorator));
    return Array.from(uniqueDecorators);
}
function isTSValue(value) {
    return Boolean(value && typeof value === "object" && "__kind" in value && value["__kind"] === "value");
}

function getScopeAndName(originalName) {
    const path = originalName.split(".");
    const name = path.pop();
    return { scope: path.map(printIdentifier), name: printIdentifier(name), rawName: name };
}

class SchemaToExpressionGenerator {
    rootNamespace;
    constructor(rootNamespace) {
        this.rootNamespace = rootNamespace;
    }
    generateTypeFromRefableSchema(schema, callingScope) {
        const hasRef = "$ref" in schema;
        return hasRef
            ? this.getRefName(schema.$ref, callingScope)
            : this.getTypeFromSchema(schema, callingScope);
    }
    generateArrayType(schema, callingScope) {
        const items = schema.items;
        if (!items) {
            return "unknown[]";
        }
        if ("$ref" in items) {
            return `${this.getRefName(items.$ref, callingScope)}[]`;
        }
        // Prettier will get rid of the extra parenthesis for us
        return `(${this.getTypeFromSchema(items, callingScope)})[]`;
    }
    getRefName(ref, callingScope) {
        const { scope, name } = this.getRefScopeAndName(ref, callingScope);
        return [...scope, name].join(".");
    }
    getRefScopeAndName(ref, callingScope) {
        const parts = ref.split("/");
        const name = parts.pop() ?? "";
        const componentType = parts.pop()?.toLowerCase() ?? "";
        const scopeAndName = getScopeAndName(name);
        switch (componentType) {
            case "schemas":
                if (callingScope.length) {
                    /*
                      Since schemas are generated in the file namespace,
                      need to reference them against the file namespace
                      to prevent name collisions.
                      Example:
                        namespace Service;
                        scalar Foo extends string;
                        namespace Parameters {
                          model Foo {
                            @query foo: Service.Foo
                          }
                        }
                    */
                    scopeAndName.scope.unshift(this.rootNamespace);
                }
                break;
            case "parameters":
                scopeAndName.scope.unshift("Parameters");
                break;
        }
        return scopeAndName;
    }
    getTypeFromSchema(schema, callingScope) {
        let type = "unknown";
        if (schema.enum) {
            type = getEnum(schema.enum);
        }
        else if (schema.anyOf) {
            type = this.getAnyOfType(schema, callingScope);
        }
        else if (schema.type === "array") {
            type = this.generateArrayType(schema, callingScope);
        }
        else if (schema.type === "boolean") {
            type = "boolean";
        }
        else if (schema.type === "integer") {
            type = getIntegerType(schema);
        }
        else if (schema.type === "number") {
            type = getNumberType(schema);
        }
        else if (schema.type === "object") {
            type = this.getObjectType(schema, callingScope);
        }
        else if (schema.oneOf) {
            type = this.getOneOfType(schema, callingScope);
        }
        else if (schema.type === "string") {
            type = getStringType(schema);
        }
        if (schema.nullable) {
            type += ` | null`;
        }
        if (schema.default) {
            type += ` = ${JSON.stringify(schema.default)}`;
        }
        return type;
    }
    getAnyOfType(schema, callingScope) {
        const definitions = [];
        for (const item of schema.anyOf ?? []) {
            definitions.push(this.generateTypeFromRefableSchema(item, callingScope));
        }
        return definitions.join(" | ");
    }
    getOneOfType(schema, callingScope) {
        const definitions = [];
        for (const item of schema.oneOf ?? []) {
            definitions.push(this.generateTypeFromRefableSchema(item, callingScope));
        }
        return definitions.join(" | ");
    }
    getObjectType(schema, callingScope) {
        // If we have `additionalProperties`, treat that as an 'indexer' and convert to a record.
        const recordType = typeof schema.additionalProperties === "object"
            ? `Record<${this.generateTypeFromRefableSchema(schema.additionalProperties, callingScope)}>`
            : "";
        if (!schema.properties && recordType) {
            return recordType;
        }
        const requiredProps = schema.required ?? [];
        const props = [];
        if (schema.properties) {
            for (const name of Object.keys(schema.properties)) {
                const decorators = generateDecorators(getDecoratorsForSchema(schema.properties[name]))
                    .map((d) => `${d}\n`)
                    .join("");
                const isOptional = !requiredProps.includes(name) ? "?" : "";
                props.push(`${decorators}${printIdentifier(name)}${isOptional}: ${this.generateTypeFromRefableSchema(schema.properties[name], callingScope)}`);
            }
        }
        const propertyCount = Object.keys(props).length;
        if (recordType && !propertyCount) {
            return recordType;
        }
        else if (recordType && propertyCount) {
            props.push(`...${recordType}`);
        }
        return `{${props.join("; ")}}`;
    }
}
function getTypeSpecPrimitiveFromSchema(schema) {
    if (schema.type === "boolean") {
        return "boolean";
    }
    else if (schema.type === "integer") {
        return getIntegerType(schema);
    }
    else if (schema.type === "number") {
        return getNumberType(schema);
    }
    else if (schema.type === "string") {
        return getStringType(schema);
    }
    return;
}
function getIntegerType(schema) {
    const format = schema.format ?? "";
    switch (format) {
        case "int8":
        case "int16":
        case "int32":
        case "int64":
        case "uint8":
        case "uint16":
        case "uint32":
        case "uint64":
            return format;
        case "double-int":
            return "safeint";
        default:
            return "integer";
    }
}
function getNumberType(schema) {
    const format = schema.format ?? "";
    switch (format) {
        case "decimal":
        case "decimal128":
            return format;
        case "double":
            return "float64";
        case "float":
            return "float32";
        default:
            // Could be either 'float' or 'numeric' - add FIXME?
            return "numeric";
    }
}
function getStringType(schema) {
    const format = schema.format ?? "";
    let type = "string";
    switch (format) {
        case "binary":
        case "byte":
            type = "bytes";
            break;
        case "date":
            type = "plainDate";
            break;
        case "date-time":
            // Can be 'offsetDateTime' or 'utcDateTime' - needs FIXME or union?
            type = "utcDateTime";
            break;
        case "time":
            type = "plainTime";
            break;
        case "duration":
            type = "duration";
            break;
        case "uri":
            type = "url";
            break;
    }
    return type;
}
function getEnum(schemaEnum) {
    return schemaEnum.map((e) => JSON.stringify(e)).join(" | ");
}

function generateDataType(type, context) {
    switch (type.kind) {
        case "alias":
            return generateAlias(type, context);
        case "enum":
            return generateEnum(type);
        case "model":
            return generateModel(type, context);
        case "scalar":
            return generateScalar(type, context);
        case "union":
            return generateUnion(type, context);
    }
}
function generateAlias(alias, context) {
    // Since aliases are not represented in the TypeGraph,
    // generate a model so that the model name is present in emitted OpenAPI3.
    // May revisit to allow emitting actual alias.
    const sourceModel = context.getRefName(alias.ref, alias.scope);
    return `model ${alias.name} is ${sourceModel};`;
}
function generateEnum(tsEnum) {
    const definitions = [];
    if (tsEnum.doc) {
        definitions.push(generateDocs(tsEnum.doc));
    }
    definitions.push(...generateDecorators(tsEnum.decorators));
    definitions.push(`enum ${tsEnum.name} {`);
    const schema = tsEnum.schema;
    if (schema.enum) {
        definitions.push(...schema.enum.map((e) => `${JSON.stringify(e)},`));
    }
    definitions.push("}");
    return definitions.join("\n");
}
function generateScalar(scalar, context) {
    const definitions = [];
    if (scalar.doc) {
        definitions.push(generateDocs(scalar.doc));
    }
    definitions.push(...generateDecorators(scalar.decorators));
    const type = context.generateTypeFromRefableSchema(scalar.schema, scalar.scope);
    if (type === "unknown") {
        definitions.push(`scalar ${scalar.name};`);
    }
    else {
        definitions.push(`scalar ${scalar.name} extends ${type};`);
    }
    return definitions.join("\n");
}
function generateUnion(union, context) {
    const definitions = [];
    if (union.doc) {
        definitions.push(generateDocs(union.doc));
    }
    definitions.push(...generateDecorators(union.decorators));
    definitions.push(`union ${union.name} {`);
    const schema = union.schema;
    if (schema.enum) {
        definitions.push(...schema.enum.map((e) => `${JSON.stringify(e)},`));
    }
    else if (schema.oneOf) {
        definitions.push(...schema.oneOf.map((member) => context.generateTypeFromRefableSchema(member, union.scope)));
    }
    else if (schema.anyOf) {
        definitions.push(...schema.anyOf.map((member) => context.generateTypeFromRefableSchema(member, union.scope)));
    }
    else {
        // check if it's a primitive type
        const primitiveType = getTypeSpecPrimitiveFromSchema(schema);
        if (primitiveType) {
            definitions.push(`${primitiveType},`);
        }
    }
    if (schema.nullable) {
        definitions.push("null,");
    }
    definitions.push("}");
    return definitions.join("\n");
}
function generateModel(model, context) {
    const definitions = [];
    const modelDeclaration = generateModelDeclaration(model);
    if (model.doc) {
        definitions.push(generateDocs(model.doc));
    }
    definitions.push(...generateDecorators(model.decorators));
    definitions.push(modelDeclaration.open);
    if (model.spread?.length) {
        definitions.push(...model.spread.map((spread) => `...${spread};`));
    }
    definitions.push(...model.properties.map((prop) => generateModelProperty(prop, model.scope, context)));
    if (model.additionalProperties) {
        definitions.push(`...Record<${context.generateTypeFromRefableSchema(model.additionalProperties, model.scope)}>;`);
    }
    if (modelDeclaration.close)
        definitions.push(modelDeclaration.close);
    return definitions.join("\n");
}
function generateModelProperty(prop, containerScope, context) {
    // Decorators will be a combination of top-level (parameters) and
    // schema-level decorators.
    const decorators = generateDecorators([
        ...prop.decorators,
        ...getDecoratorsForSchema(prop.schema),
    ]).join(" ");
    const doc = prop.doc ? generateDocs(prop.doc) : "";
    return `${doc}${decorators} ${prop.name}${prop.isOptional ? "?" : ""}: ${context.generateTypeFromRefableSchema(prop.schema, containerScope)};`;
}
function generateModelExpression(props, containerScope, context) {
    return `{ ${props.map((prop) => generateModelProperty(prop, containerScope, context)).join(" ")} }`;
}
function generateModelDeclaration(model) {
    const modelName = model.name;
    if (model.is) {
        return { open: `model ${modelName} is ${model.is};` };
    }
    if (model.extends) {
        return { open: `model ${modelName} extends ${model.extends} {`, close: "}" };
    }
    return { open: `model ${modelName} {`, close: "}" };
}

function convertHeaderName(s) {
    return s
        .split("-")
        .map((s, idx) => (idx === 0 ? s : s.substring(0, 1).toUpperCase() + s.substring(1)))
        .join("");
}

/**
 * Generates a union expression of all possible responses for an operation
 */
function generateOperationReturnType(operation, context) {
    const expressions = [];
    for (const [statusCode, response] of Object.entries(operation.responses)) {
        expressions.push(...generateReturnTypeForStatusCode({
            statusCode,
            response,
            context,
            operationScope: operation.scope,
        }));
    }
    return expressions.join(" | ");
}
function generateReturnTypeForStatusCode(props) {
    const { statusCode, context } = props;
    const response = "$ref" in props.response
        ? context.getByRef(props.response.$ref)
        : props.response;
    if (!response) {
        return [];
    }
    const description = props.response.description ?? response.description;
    // collect headers
    const headerProperties = Object.entries(response.headers ?? {})
        .map(([name, header]) => {
        return convertHeaderToProperty({ name, header, context });
    })
        .filter((h) => !!h);
    const contentEntries = Object.entries(response.content ?? {});
    return generateResponseExpressions({
        statusCode,
        description,
        headers: headerProperties,
        contents: contentEntries,
        operationScope: props.operationScope,
        context,
    });
}
function getStatusCodeMetadata(statusCode) {
    const isDefault = statusCode === "default";
    if (isDefault) {
        return { statusCode, isDefault };
    }
    const metadata = {
        statusCode,
        isDefault,
        modelProperty: convertStatusCodeToProperty(statusCode),
    };
    if (isValidLiteralStatusCode(statusCode)) {
        metadata.literalStatusCode = parseInt(statusCode, 10);
        metadata.httpLibModel = statusCodeToResponse.get(metadata.literalStatusCode);
    }
    return metadata;
}
function handleDefaultResponse({ contents, context, headers, operationScope, description, }) {
    if (!contents.length) {
        return [
            generateDefaultResponse({
                context,
                headers,
                operationScope,
                description,
            }),
        ];
    }
    return contents.map(([mediaType, content]) => {
        const bodySchema = content.schema;
        const headerProps = [...headers];
        // application/json is default contentType so can ignore it
        if (mediaType !== "application/json") {
            headerProps.push({
                name: "contentType",
                decorators: [{ name: "header", args: [] }],
                isOptional: false,
                schema: { type: "string", enum: [mediaType] },
            });
        }
        return generateDefaultResponse({
            context,
            headers: headerProps,
            operationScope,
            body: bodySchema && context.generateTypeFromRefableSchema(bodySchema, operationScope),
            description,
        });
    });
}
function generateResponseExpressions({ statusCode, contents, context, headers, operationScope, description, }) {
    const hasContents = contents.length > 0;
    const statusCodeMetadata = getStatusCodeMetadata(statusCode);
    if (statusCodeMetadata.isDefault) {
        return handleDefaultResponse({ headers, contents, operationScope, context, description });
    }
    // Scenario 1 - only have a mapped status code - use it directly
    // Example: OkResponse
    if (statusCodeMetadata.httpLibModel && !hasContents && !headers.length) {
        return [statusCodeMetadata.httpLibModel];
    }
    // 200 statusCode is default, we can ignore it since we know we have headers or body to fill out response
    if (statusCodeMetadata.literalStatusCode === 200) {
        statusCodeMetadata.httpLibModel = undefined;
        statusCodeMetadata.modelProperty = undefined;
    }
    // Scenario 2 - have a status code and headers, but no bodies.
    // Example: CreatedResponse & { @header xFoo: string }
    // Example: { @statusCode statusCode: 203, @header xFoo: string }
    if (!hasContents) {
        if (statusCodeMetadata.httpLibModel) {
            return [
                `${statusCodeMetadata.httpLibModel} & ${generateModelExpression(headers, operationScope, context)}`,
            ];
        }
        const modelProps = [...headers];
        if (statusCodeMetadata.modelProperty) {
            modelProps.push(statusCodeMetadata.modelProperty);
        }
        return [generateModelExpression(modelProps, operationScope, context)];
    }
    return contents.map(([mediaType, content]) => {
        // Attempt to emit just the Body or an intersection of Body & MappedResponse
        // if there aren't any custom headers.
        const bodySchema = content.schema;
        if (bodySchema && mediaType === "application/json" && !headers.length) {
            // Scenario 3 - have a mapped status code and body schema is a ref using application/json - intersection!
            // Example: CreatedResponse & Widget
            if ("$ref" in bodySchema && statusCodeMetadata.httpLibModel) {
                return `${statusCodeMetadata.httpLibModel} & ${context.generateTypeFromRefableSchema(bodySchema, operationScope)}`;
            }
            // Scenario 4 - 200 status code and using application/json - return just the body
            // Example: Widget
            // Example: Body<string>
            if (statusCodeMetadata.literalStatusCode === 200) {
                const body = context.generateTypeFromRefableSchema(bodySchema, operationScope);
                if ("$ref" in bodySchema) {
                    return body;
                }
                return `Body<${body}>`;
            }
        }
        // Scenario 5 - any combination of headers/statusCode/body - common expression
        const modelExpressionProps = [];
        if (statusCodeMetadata.modelProperty) {
            modelExpressionProps.push(statusCodeMetadata.modelProperty);
        }
        modelExpressionProps.push(...headers);
        // application/json is default contentType so can ignore it
        if (mediaType !== "application/json") {
            modelExpressionProps.push({
                name: "contentType",
                decorators: [{ name: "header", args: [] }],
                isOptional: false,
                schema: { type: "string", enum: [mediaType] },
            });
        }
        if (bodySchema) {
            modelExpressionProps.push({
                name: "body",
                isOptional: false,
                decorators: [{ name: "body", args: [] }],
                schema: bodySchema,
            });
        }
        return generateModelExpression(modelExpressionProps, operationScope, context);
    });
}
function generateDefaultResponse({ operationScope, context, ...props }) {
    const hasTemplateParams = !!(props.description || props.headers.length || props.body);
    if (!hasTemplateParams)
        return "GeneratedHelpers.DefaultResponse";
    const description = props.description ? `Description = "${props.description}", ` : "";
    const headers = props.headers.length
        ? `Headers = ${generateModelExpression(props.headers, operationScope, context)}, `
        : "";
    const body = props.body ? `Body = ${props.body}, ` : "";
    return `GeneratedHelpers.DefaultResponse<${description}${headers}${body}>`;
}
function convertStatusCodeToProperty(statusCode) {
    const schema = { type: "integer", format: "int32" };
    if (statusCode === "1XX") {
        schema.minimum = 100;
        schema.maximum = 199;
    }
    else if (statusCode === "2XX") {
        schema.minimum = 200;
        schema.maximum = 299;
    }
    else if (statusCode === "3XX") {
        schema.minimum = 300;
        schema.maximum = 399;
    }
    else if (statusCode === "4XX") {
        schema.minimum = 400;
        schema.maximum = 499;
    }
    else if (statusCode === "5XX") {
        schema.minimum = 500;
        schema.maximum = 599;
    }
    else if (isValidLiteralStatusCode(statusCode)) {
        const literalStatusCode = parseInt(statusCode, 10);
        schema.enum = [literalStatusCode];
    }
    return {
        name: "statusCode",
        schema,
        decorators: [{ name: "statusCode", args: [] }],
        isOptional: false,
    };
}
function isValidLiteralStatusCode(statusCode) {
    if (statusCode === "default" || statusCode.endsWith("X"))
        return false;
    const literalStatusCode = parseInt(statusCode, 10);
    return isFinite(literalStatusCode) && literalStatusCode >= 100 && literalStatusCode <= 599;
}
function convertHeaderToProperty(props) {
    const { name, context } = props;
    const header = "$ref" in props.header ? context.getByRef(props.header.$ref) : props.header;
    if (!header)
        return;
    const normalizedName = convertHeaderName(name);
    // TODO: handle style
    const headerDecorator = { name: "header", args: [] };
    if (normalizedName !== name) {
        headerDecorator.args.push(name);
    }
    return {
        name: normalizedName,
        decorators: [headerDecorator, ...getDecoratorsForSchema(header.schema)],
        doc: props.header.description ?? header.description ?? header.schema.description,
        isOptional: !header.required,
        schema: header.schema,
    };
}
// Map of statusCodes to their Response
const statusCodeToResponse = new Map([
    [200, "OkResponse"],
    [201, "CreatedResponse"],
    [202, "AcceptedResponse"],
    [204, "NoContentResponse"],
    [304, "NotModifiedResponse"],
    [400, "BadRequestResponse"],
    [401, "UnauthorizedResponse"],
    [403, "ForbiddenResponse"],
    [404, "NotFoundResponse"],
    [409, "ConflictResponse"],
]);

function generateOperation(operation, context) {
    const definitions = [];
    if (operation.doc) {
        definitions.push(generateDocs(operation.doc));
    }
    definitions.push(...operation.tags.map((t) => `@tag("${t}")`));
    definitions.push(generateDecorators(operation.decorators).join(" "));
    // generate parameters
    const parameters = [
        ...operation.parameters.map((p) => generateOperationParameter(operation, p, context)),
        ...generateRequestBodyParameters(operation.requestBodies, context),
    ];
    const responses = generateOperationReturnType(operation, context);
    definitions.push(`op ${operation.name}(${parameters.join(", ")}): ${responses};`);
    return definitions.join(" ");
}
function generateOperationParameter(operation, parameter, context) {
    if ("$ref" in parameter) {
        return `...${context.getRefName(parameter.$ref, operation.scope)}`;
    }
    const definitions = [];
    if (parameter.doc) {
        definitions.push(generateDocs(parameter.doc));
    }
    definitions.push(...generateDecorators(parameter.decorators));
    definitions.push(`${parameter.name}${parameter.isOptional ? "?" : ""}: ${context.generateTypeFromRefableSchema(parameter.schema, operation.scope)}`);
    return definitions.join(" ");
}
function generateRequestBodyParameters(requestBodies, context) {
    if (!requestBodies.length) {
        return [];
    }
    const definitions = [];
    // Generate the content-type header if defined content-types is not just 'application/json'
    const contentTypes = requestBodies.map((r) => r.contentType);
    if (!supportsOnlyJson(contentTypes)) {
        definitions.push(`@header contentType: ${contentTypes.map((c) => `"${c}"`).join(" | ")}`);
    }
    // Get the set of referenced types
    const body = Array.from(new Set(requestBodies
        .filter((r) => !!r.schema)
        .map((r) => context.generateTypeFromRefableSchema(r.schema, [])))).join(" | ");
    if (body) {
        let doc = "";
        if (requestBodies[0].doc) {
            doc = generateDocs(requestBodies[0].doc);
        }
        definitions.push(`${doc}@body body: ${body}`);
    }
    return definitions;
}
function supportsOnlyJson(contentTypes) {
    return contentTypes.length === 1 && contentTypes[0] === "application/json";
}

function generateNamespace(name, namespace, context) {
    const definitions = [];
    definitions.push(`namespace ${name} {`);
    definitions.push(...namespace.types.map((t) => generateDataType(t, context)));
    definitions.push(...namespace.operations.map((o) => generateOperation(o, context)));
    for (const [namespaceName, nestedNamespace] of Object.entries(namespace.namespaces)) {
        definitions.push(generateNamespace(namespaceName, nestedNamespace, context));
    }
    definitions.push("}");
    return definitions.join("\n");
}

function generateNamespaceName(name) {
    return name.replaceAll(/[^\w^\d_]+/g, "");
}

function generateServiceInformation(serviceInfo) {
    const definitions = [];
    const { name, doc, ...info } = serviceInfo;
    definitions.push(`
    @service({
      title: "${name}"
    })
    @info(${JSON.stringify(info)})
    `);
    if (doc) {
        definitions.push(generateDocs(doc));
    }
    definitions.push(`namespace ${generateNamespaceName(name)};`);
    return definitions.join("\n");
}

function generateMain(program, context) {
    return `
  import "@typespec/http";
  import "@typespec/openapi";
  import "@typespec/openapi3";

  using Http;
  using OpenAPI;

  ${generateServiceInformation(program.serviceInfo)}

  ${program.types.map((t) => generateDataType(t, context)).join("\n\n")}

  ${program.operations.map((o) => generateOperation(o, context)).join("\n\n")}

  ${Object.entries(program.namespaces)
        .map(([name, namespace]) => generateNamespace(name, namespace, context))
        .join("\n\n")}
  ${generateHelpers(context)}
  `;
}

/**
 * Transforms #/components/parameters into TypeSpec models.
 * Overwrites properties of existing models if an existing model already exists.
 * Populates the provided `models` array in-place.
 * @param models
 * @param parameters
 * @returns
 */
function transformComponentParameters(context, dataTypes) {
    const parameters = context.openApi3Doc.components?.parameters;
    if (!parameters)
        return;
    for (const name of Object.keys(parameters)) {
        const parameter = parameters[name];
        transformComponentParameter(dataTypes, name, parameter);
    }
}
function transformComponentParameter(dataTypes, key, parameter) {
    const { name, scope } = getScopeAndName(key);
    // Parameters should live in the root Parameters namespace
    scope.unshift("Parameters");
    dataTypes.push({
        kind: "model",
        scope,
        name,
        decorators: [],
        properties: [getModelPropertyFromParameter(parameter)],
    });
}
function getModelPropertyFromParameter(parameter) {
    return {
        name: printIdentifier(parameter.name),
        isOptional: !parameter.required,
        doc: parameter.description ?? parameter.schema.description,
        decorators: getParameterDecorators(parameter),
        schema: parameter.schema,
    };
}

/**
 * Transforms #/components/schemas into TypeSpec models.
 * Populates the provided `models` array in-place.
 * @param models
 * @param schemas
 * @returns
 */
function transformComponentSchemas(context, models) {
    const schemas = context.openApi3Doc.components?.schemas;
    if (!schemas)
        return;
    for (const name of Object.keys(schemas)) {
        const schema = schemas[name];
        transformComponentSchema(models, name, schema);
    }
    return;
    function transformComponentSchema(types, name, schema) {
        const kind = getTypeSpecKind(schema);
        switch (kind) {
            case "alias":
                return populateAlias(types, name, schema);
            case "enum":
                return populateEnum(types, name, schema);
            case "model":
                return populateModel(types, name, schema);
            case "union":
                return populateUnion(types, name, schema);
            case "scalar":
                return populateScalar(types, name, schema);
        }
    }
    function populateAlias(types, rawName, schema) {
        if (!("$ref" in schema)) {
            return;
        }
        const { name, scope } = getScopeAndName(rawName);
        types.push({
            kind: "alias",
            name,
            scope,
            doc: schema.description,
            ref: context.getRefName(schema.$ref, scope),
        });
    }
    function populateEnum(types, name, schema) {
        const tsEnum = {
            kind: "enum",
            ...getScopeAndName(name),
            decorators: getDecoratorsForSchema(schema),
            doc: schema.description,
            schema,
        };
        types.push(tsEnum);
    }
    function populateModel(types, rawName, schema) {
        const { name, scope } = getScopeAndName(rawName);
        const allOfDetails = getAllOfDetails(schema, scope);
        const isParent = getModelIs(schema, scope);
        types.push({
            kind: "model",
            name,
            scope,
            decorators: [...getDecoratorsForSchema(schema)],
            doc: schema.description,
            properties: [...getModelPropertiesFromObjectSchema(schema), ...allOfDetails.properties],
            additionalProperties: typeof schema.additionalProperties === "object" ? schema.additionalProperties : undefined,
            extends: allOfDetails.extends,
            is: isParent,
            type: schema.type,
            spread: allOfDetails.spread,
        });
    }
    function populateUnion(types, name, schema) {
        const union = {
            kind: "union",
            ...getScopeAndName(name),
            decorators: getDecoratorsForSchema(schema),
            doc: schema.description,
            schema,
        };
        types.push(union);
    }
    function populateScalar(types, name, schema) {
        types.push({
            kind: "scalar",
            ...getScopeAndName(name),
            decorators: getDecoratorsForSchema(schema),
            doc: schema.description,
            schema,
        });
    }
    function getAllOfDetails(schema, callingScope) {
        const details = {
            spread: [],
            properties: [],
        };
        if (!schema.allOf) {
            return details;
        }
        let foundParentWithDiscriminator = false;
        for (const member of schema.allOf) {
            // inline-schemas treated as normal objects with properties
            if (!("$ref" in member)) {
                details.properties.push(...getModelPropertiesFromObjectSchema(member));
                continue;
            }
            const refSchema = context.getSchemaByRef(member.$ref);
            // Inheritance only supported if parent has a discriminator defined, otherwise prefer
            // composition via spreading.
            if (!refSchema?.discriminator) {
                details.spread.push(context.getRefName(member.$ref, callingScope));
                continue;
            }
            if (!foundParentWithDiscriminator) {
                details.extends = context.getRefName(member.$ref, callingScope);
                foundParentWithDiscriminator = true;
                continue;
            }
            // can only extend once, so if we have multiple potential parents, spread them all
            // user will need to resolve TypeSpec errors (e.g. duplicate fields) manually
            if (details.extends) {
                details.spread.push(details.extends);
                details.extends = undefined;
            }
            details.spread.push(context.getRefName(member.$ref, callingScope));
        }
        return details;
    }
    function getModelIs(schema, callingScope) {
        if (schema.type !== "array") {
            return;
        }
        return context.generateTypeFromRefableSchema(schema, callingScope);
    }
}
function getModelPropertiesFromObjectSchema({ properties, required = [], }) {
    if (!properties)
        return [];
    const modelProperties = [];
    for (const name of Object.keys(properties)) {
        const property = properties[name];
        modelProperties.push({
            name: printIdentifier(name),
            doc: property.description,
            schema: property,
            isOptional: !required.includes(name),
            decorators: [...getDecoratorsForSchema(property)],
        });
    }
    return modelProperties;
}
function getTypeSpecKind(schema) {
    if ("$ref" in schema) {
        return "alias";
    }
    if (schema.enum && schema.type === "string" && !schema.nullable) {
        return "enum";
    }
    else if (schema.anyOf || schema.oneOf || schema.enum || schema.nullable) {
        return "union";
    }
    else if (schema.type === "object" || schema.type === "array" || schema.allOf) {
        return "model";
    }
    return "scalar";
}

function transformNamespaces(types, operations) {
    // There can only be 1 file namespace - so if scopes is empty then entity belongs at root level
    const programDecs = {
        types: [],
        operations: [],
        namespaces: {},
    };
    expandModels(programDecs, types);
    expandOperations(programDecs, operations);
    return programDecs;
}
function expandModels(programDecs, types) {
    for (const type of types) {
        const { scope } = type;
        const namespace = getNamespace(programDecs, scope) ?? createNamespace(programDecs, scope);
        namespace.types.push(type);
    }
}
function expandOperations(programDecs, operations) {
    for (const operation of operations) {
        const { scope } = operation;
        const namespace = getNamespace(programDecs, scope) ?? createNamespace(programDecs, scope);
        namespace.operations.push(operation);
    }
}
function getNamespace(programDecs, scope) {
    if (!scope.length)
        return programDecs;
    let namespace = programDecs;
    for (const fragment of scope) {
        if (!namespace)
            return;
        namespace = namespace.namespaces[fragment];
    }
    return namespace;
}
function createNamespace(programDecs, scope) {
    let namespace = programDecs;
    for (const fragment of scope) {
        if (!namespace.namespaces[fragment]) {
            namespace.namespaces[fragment] = {
                namespaces: {},
                types: [],
                operations: [],
            };
        }
        namespace = namespace.namespaces[fragment];
    }
    return namespace;
}

/**
 * Transforms each operation defined under #/paths/{route}/{httpMethod} into a TypeSpec operation.
 * @params models - The array of models to populate with any new models generated from the operation.
 * @param paths
 * @returns
 */
function transformPaths(paths, context) {
    const operations = [];
    for (const route of Object.keys(paths)) {
        const routeParameters = paths[route].parameters?.map(transformOperationParameter) ?? [];
        const path = paths[route];
        for (const verb of supportedHttpMethods) {
            const operation = path[verb];
            if (!operation)
                continue;
            const parameters = operation.parameters?.map(transformOperationParameter) ?? [];
            const tags = operation.tags?.map((t) => t) ?? [];
            const operationResponses = operation.responses ?? {};
            const decorators = [
                ...getExtensions(operation),
                { name: "route", args: [route] },
                { name: verb, args: [] },
            ];
            if (operation.summary) {
                decorators.push({ name: "summary", args: [operation.summary] });
            }
            operations.push({
                ...getScopeAndName(operation.operationId),
                decorators,
                parameters: dedupeParameters([...routeParameters, ...parameters]),
                doc: operation.description,
                operationId: operation.operationId,
                requestBodies: transformRequestBodies(operation.requestBody, context),
                responses: operationResponses,
                tags: tags,
            });
        }
    }
    return operations;
}
function dedupeParameters(parameters) {
    const seen = new Set();
    const dedupeList = [];
    // iterate in reverse since more specific-scoped parameters are added last
    for (let i = parameters.length - 1; i >= 0; i--) {
        // ignore resolving the $ref for now, unlikely to be able to resolve
        // issues without user intervention if a duplicate is present except in
        // very simple cases.
        const param = parameters[i];
        const identifier = "$ref" in param ? param.$ref : `${param.in}.${param.name}`;
        if (seen.has(identifier))
            continue;
        seen.add(identifier);
        dedupeList.unshift(param);
    }
    return dedupeList;
}
function transformOperationParameter(parameter) {
    if ("$ref" in parameter) {
        return { $ref: parameter.$ref };
    }
    return {
        name: printIdentifier(parameter.name),
        in: parameter.in,
        doc: parameter.description,
        decorators: getParameterDecorators(parameter),
        isOptional: !parameter.required,
        schema: parameter.schema,
    };
}
function transformRequestBodies(requestBodies, context) {
    if (!requestBodies) {
        return [];
    }
    const description = requestBodies.description;
    if ("$ref" in requestBodies) {
        requestBodies = context.getByRef(requestBodies.$ref);
    }
    if (!requestBodies) {
        return [];
    }
    const typespecBodies = [];
    for (const contentType of Object.keys(requestBodies.content)) {
        const contentBody = requestBodies.content[contentType];
        typespecBodies.push({
            contentType,
            isOptional: !requestBodies.required,
            doc: description ?? requestBodies.description,
            encoding: contentBody.encoding,
            schema: contentBody.schema,
        });
    }
    return typespecBodies;
}

function transformServiceInfo(info) {
    return {
        name: info.title,
        doc: info.description,
        version: info.version,
        contact: info.contact,
        license: info.license,
        termsOfService: info.termsOfService,
        summary: info.summary,
    };
}

function transform(context) {
    const openapi = context.openApi3Doc;
    const models = collectDataTypes(context);
    const operations = transformPaths(openapi.paths, context);
    return {
        serviceInfo: transformServiceInfo(openapi.info),
        ...transformNamespaces(models, operations),
        augmentations: [],
    };
}
function collectDataTypes(context) {
    const models = [];
    // get models from `#/components/schema
    transformComponentSchemas(context, models);
    // get models from `#/components/parameters
    transformComponentParameters(context, models);
    return models;
}

function createContext(parser, openApi3Doc) {
    const rootNamespace = generateNamespaceName(openApi3Doc.info.title);
    const schemaExpressionGenerator = new SchemaToExpressionGenerator(rootNamespace);
    const context = {
        openApi3Doc,
        rootNamespace,
        getRefName(ref, callingScope) {
            return schemaExpressionGenerator.getRefName(ref, callingScope);
        },
        generateTypeFromRefableSchema(schema, callingScope) {
            return schemaExpressionGenerator.generateTypeFromRefableSchema(schema, callingScope);
        },
        getSchemaByRef(ref) {
            return this.getByRef(ref);
        },
        getByRef(ref) {
            return parser.$refs.get(ref);
        },
    };
    return context;
}

async function convertOpenAPI3Document(document, { disableExternalRefs } = {}) {
    const parser = new OpenAPIParser();
    const bundleOptions = disableExternalRefs
        ? {
            resolve: { external: false, http: false, file: false },
        }
        : {};
    await parser.bundle(document, bundleOptions);
    const context = createContext(parser, document);
    const program = transform(context);
    const content = generateMain(program, context);
    try {
        return await formatTypeSpec(content, {
            printWidth: 100,
            tabWidth: 2,
        });
    }
    catch {
        return content;
    }
}

const EmitterOptionsSchema = {
    type: "object",
    additionalProperties: false,
    properties: {
        "file-type": {
            type: "string",
            enum: ["yaml", "json"],
            nullable: true,
            description: "If the content should be serialized as YAML or JSON. Default 'yaml', it not specified infer from the `output-file` extension",
        },
        "output-file": {
            type: "string",
            nullable: true,
            description: [
                "Name of the output file.",
                " Output file will interpolate the following values:",
                "  - service-name: Name of the service if multiple",
                "  - version: Version of the service if multiple",
                "",
                ' Default: `{service-name}.{version}.openapi.yaml` or `.json` if `file-type` is `"json"`',
                "",
                " Example Single service no versioning",
                "  - `openapi.yaml`",
                "",
                " Example Multiple services no versioning",
                "  - `openapi.Org1.Service1.yaml`",
                "  - `openapi.Org1.Service2.yaml`",
                "",
                " Example Single service with versioning",
                "  - `openapi.v1.yaml`",
                "  - `openapi.v2.yaml`",
                "",
                " Example Multiple service with versioning",
                "  - `openapi.Org1.Service1.v1.yaml`",
                "  - `openapi.Org1.Service1.v2.yaml`",
                "  - `openapi.Org1.Service2.v1.0.yaml`",
                "  - `openapi.Org1.Service2.v1.1.yaml`    ",
            ].join("\n"),
        },
        "openapi-versions": {
            type: "array",
            items: {
                type: "string",
                enum: ["3.0.0", "3.1.0"],
                nullable: true,
                description: "The versions of OpenAPI to emit. Defaults to `[3.0.0]`",
            },
            nullable: true,
            uniqueItems: true,
            minItems: 1,
        },
        "new-line": {
            type: "string",
            enum: ["crlf", "lf"],
            default: "lf",
            nullable: true,
            description: "Set the newline character for emitting files.",
        },
        "omit-unreachable-types": {
            type: "boolean",
            nullable: true,
            description: "Omit unreachable types.\nBy default all types declared under the service namespace will be included. With this flag on only types references in an operation will be emitted.",
        },
        "include-x-typespec-name": {
            type: "string",
            enum: ["inline-only", "never"],
            nullable: true,
            default: "never",
            description: "If the generated openapi types should have the `x-typespec-name` extension set with the name of the TypeSpec type that created it.\nThis extension is meant for debugging and should not be depended on.",
        },
        "safeint-strategy": {
            type: "string",
            enum: ["double-int", "int64"],
            nullable: true,
            default: "int64",
            description: [
                "How to handle safeint type. Options are:",
                " - `double-int`: Will produce `type: integer, format: double-int`",
                " - `int64`: Will produce `type: integer, format: int64`",
                "",
                "Default: `int64`",
            ].join("\n"),
        },
    },
    required: [],
};
const libDef = {
    name: "@typespec/openapi3",
    diagnostics: {
        "oneof-union": {
            severity: "error",
            messages: {
                default: "@oneOf decorator can only be used on a union or a model property which type is a union.",
            },
        },
        "inconsistent-shared-route-request-visibility": {
            severity: "error",
            messages: {
                default: "All operations with `@sharedRoutes` must have the same `@requestVisibility`.",
            },
        },
        "invalid-server-variable": {
            severity: "error",
            messages: {
                default: paramMessage `Server variable '${"propName"}' must be assignable to 'string'. It must either be a string, enum of string or union of strings.`,
            },
        },
        "invalid-format": {
            severity: "warning",
            messages: {
                default: paramMessage `Collection format '${"value"}' is not supported in OpenAPI3 ${"paramType"} parameters. Defaulting to type 'string'.`,
            },
        },
        "invalid-style": {
            severity: "warning",
            messages: {
                default: paramMessage `Style '${"style"}' is not supported in OpenAPI3 ${"paramType"} parameters. Defaulting to style 'simple'.`,
            },
        },
        "path-reserved-expansion": {
            severity: "warning",
            messages: {
                default: `Reserved expansion of path parameter with '+' operator #{allowReserved: true} is not supported in OpenAPI3.`,
            },
        },
        "resource-namespace": {
            severity: "error",
            messages: {
                default: "Resource goes on namespace",
            },
        },
        "path-query": {
            severity: "error",
            messages: {
                default: `OpenAPI does not allow paths containing a query string.`,
            },
        },
        "duplicate-header": {
            severity: "error",
            messages: {
                default: paramMessage `The header ${"header"} is defined across multiple content types`,
            },
        },
        "status-code-in-default-response": {
            severity: "error",
            messages: {
                default: "a default response should not have an explicit status code",
            },
        },
        "invalid-schema": {
            severity: "error",
            messages: {
                default: paramMessage `Couldn't get schema for type ${"type"}`,
            },
        },
        "union-null": {
            severity: "error",
            messages: {
                default: "Cannot have a union containing only null types.",
            },
        },
        "empty-union": {
            severity: "error",
            messages: {
                default: "Empty unions are not supported for OpenAPI v3 - enums must have at least one value.",
            },
        },
        "empty-enum": {
            severity: "error",
            messages: {
                default: "Empty enums are not supported for OpenAPI v3 - enums must have at least one value.",
            },
        },
        "enum-unique-type": {
            severity: "error",
            messages: {
                default: "Enums are not supported unless all options are literals of the same type.",
            },
        },
        "inline-cycle": {
            severity: "error",
            messages: {
                default: paramMessage `Cycle detected in '${"type"}'. Use @friendlyName decorator to assign an OpenAPI definition name and make it non-inline.`,
            },
        },
        "unsupported-status-code-range": {
            severity: "error",
            messages: {
                default: paramMessage `Status code range '${"start"} to '${"end"}' is not supported. OpenAPI 3.0 can only represent range 1XX, 2XX, 3XX, 4XX and 5XX. Example: \`@minValue(400) @maxValue(499)\` for 4XX.`,
            },
        },
        "invalid-model-property": {
            severity: "error",
            messages: {
                default: paramMessage `'${"type"}' cannot be specified as a model property.`,
            },
        },
        "unsupported-auth": {
            severity: "warning",
            messages: {
                default: paramMessage `Authentication "${"authType"}" is not a known authentication by the openapi3 emitter, it will be ignored.`,
            },
        },
        "xml-attribute-invalid-property-type": {
            severity: "warning",
            messages: {
                default: paramMessage `XML \`@attribute\` can only be primitive types in the OpenAPI 3 emitter, Property '${"name"}' type will be changed to type: string.`,
            },
        },
        "xml-unwrapped-invalid-property-type": {
            severity: "warning",
            messages: {
                default: paramMessage `XML \`@unwrapped\` can only used on array properties or primitive ones in the OpenAPI 3 emitter, Property '${"name"}' will be ignored.`,
            },
        },
        "invalid-component-fixed-field-key": {
            severity: "error",
            messages: {
                default: paramMessage `Invalid key '${"value"}' used in a fixed field of the Component object. Only alphanumerics, dot (.), hyphen (-), and underscore (_) characters are allowed in keys.`,
            },
        },
    },
    emitter: {
        options: EmitterOptionsSchema,
    },
};
const $lib = createTypeSpecLibrary(libDef);
const { createDiagnostic, reportDiagnostic, createStateSymbol } = $lib;

const refTargetsKey = createStateSymbol("refs");
const $useRef = (context, entity, refUrl) => {
    context.program.stateMap(refTargetsKey).set(entity, refUrl);
};
function getRef(program, entity) {
    return program.stateMap(refTargetsKey).get(entity);
}
const oneOfKey = createStateSymbol("oneOf");
const $oneOf = (context, entity) => {
    if (entity.kind === "ModelProperty" && entity.type.kind !== "Union") {
        reportDiagnostic(context.program, {
            code: "oneof-union",
            target: context.decoratorTarget,
        });
    }
    context.program.stateMap(oneOfKey).set(entity, true);
};
function getOneOf(program, entity) {
    return program.stateMap(oneOfKey).get(entity);
}

const ALIAS = Symbol.for('yaml.alias');
const DOC = Symbol.for('yaml.document');
const MAP = Symbol.for('yaml.map');
const PAIR = Symbol.for('yaml.pair');
const SCALAR = Symbol.for('yaml.scalar');
const SEQ = Symbol.for('yaml.seq');
const NODE_TYPE = Symbol.for('yaml.node.type');
const isAlias = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === ALIAS;
const isDocument = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === DOC;
const isMap = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === MAP;
const isPair = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === PAIR;
const isScalar = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SCALAR;
const isSeq = (node) => !!node && typeof node === 'object' && node[NODE_TYPE] === SEQ;
function isCollection(node) {
    if (node && typeof node === 'object')
        switch (node[NODE_TYPE]) {
            case MAP:
            case SEQ:
                return true;
        }
    return false;
}
function isNode(node) {
    if (node && typeof node === 'object')
        switch (node[NODE_TYPE]) {
            case ALIAS:
            case MAP:
            case SCALAR:
            case SEQ:
                return true;
        }
    return false;
}
const hasAnchor = (node) => (isScalar(node) || isCollection(node)) && !!node.anchor;

const BREAK = Symbol('break visit');
const SKIP = Symbol('skip children');
const REMOVE = Symbol('remove node');
/**
 * Apply a visitor to an AST node or document.
 *
 * Walks through the tree (depth-first) starting from `node`, calling a
 * `visitor` function with three arguments:
 *   - `key`: For sequence values and map `Pair`, the node's index in the
 *     collection. Within a `Pair`, `'key'` or `'value'`, correspondingly.
 *     `null` for the root node.
 *   - `node`: The current node.
 *   - `path`: The ancestry of the current node.
 *
 * The return value of the visitor may be used to control the traversal:
 *   - `undefined` (default): Do nothing and continue
 *   - `visit.SKIP`: Do not visit the children of this node, continue with next
 *     sibling
 *   - `visit.BREAK`: Terminate traversal completely
 *   - `visit.REMOVE`: Remove the current node, then continue with the next one
 *   - `Node`: Replace the current node, then continue by visiting it
 *   - `number`: While iterating the items of a sequence or map, set the index
 *     of the next step. This is useful especially if the index of the current
 *     node has changed.
 *
 * If `visitor` is a single function, it will be called with all values
 * encountered in the tree, including e.g. `null` values. Alternatively,
 * separate visitor functions may be defined for each `Map`, `Pair`, `Seq`,
 * `Alias` and `Scalar` node. To define the same visitor function for more than
 * one node type, use the `Collection` (map and seq), `Value` (map, seq & scalar)
 * and `Node` (alias, map, seq & scalar) targets. Of all these, only the most
 * specific defined one will be used for each node.
 */
function visit(node, visitor) {
    const visitor_ = initVisitor(visitor);
    if (isDocument(node)) {
        const cd = visit_(null, node.contents, visitor_, Object.freeze([node]));
        if (cd === REMOVE)
            node.contents = null;
    }
    else
        visit_(null, node, visitor_, Object.freeze([]));
}
// Without the `as symbol` casts, TS declares these in the `visit`
// namespace using `var`, but then complains about that because
// `unique symbol` must be `const`.
/** Terminate visit traversal completely */
visit.BREAK = BREAK;
/** Do not visit the children of the current node */
visit.SKIP = SKIP;
/** Remove the current node */
visit.REMOVE = REMOVE;
function visit_(key, node, visitor, path) {
    const ctrl = callVisitor(key, node, visitor, path);
    if (isNode(ctrl) || isPair(ctrl)) {
        replaceNode(key, path, ctrl);
        return visit_(key, ctrl, visitor, path);
    }
    if (typeof ctrl !== 'symbol') {
        if (isCollection(node)) {
            path = Object.freeze(path.concat(node));
            for (let i = 0; i < node.items.length; ++i) {
                const ci = visit_(i, node.items[i], visitor, path);
                if (typeof ci === 'number')
                    i = ci - 1;
                else if (ci === BREAK)
                    return BREAK;
                else if (ci === REMOVE) {
                    node.items.splice(i, 1);
                    i -= 1;
                }
            }
        }
        else if (isPair(node)) {
            path = Object.freeze(path.concat(node));
            const ck = visit_('key', node.key, visitor, path);
            if (ck === BREAK)
                return BREAK;
            else if (ck === REMOVE)
                node.key = null;
            const cv = visit_('value', node.value, visitor, path);
            if (cv === BREAK)
                return BREAK;
            else if (cv === REMOVE)
                node.value = null;
        }
    }
    return ctrl;
}
function initVisitor(visitor) {
    if (typeof visitor === 'object' &&
        (visitor.Collection || visitor.Node || visitor.Value)) {
        return Object.assign({
            Alias: visitor.Node,
            Map: visitor.Node,
            Scalar: visitor.Node,
            Seq: visitor.Node
        }, visitor.Value && {
            Map: visitor.Value,
            Scalar: visitor.Value,
            Seq: visitor.Value
        }, visitor.Collection && {
            Map: visitor.Collection,
            Seq: visitor.Collection
        }, visitor);
    }
    return visitor;
}
function callVisitor(key, node, visitor, path) {
    if (typeof visitor === 'function')
        return visitor(key, node, path);
    if (isMap(node))
        return visitor.Map?.(key, node, path);
    if (isSeq(node))
        return visitor.Seq?.(key, node, path);
    if (isPair(node))
        return visitor.Pair?.(key, node, path);
    if (isScalar(node))
        return visitor.Scalar?.(key, node, path);
    if (isAlias(node))
        return visitor.Alias?.(key, node, path);
    return undefined;
}
function replaceNode(key, path, node) {
    const parent = path[path.length - 1];
    if (isCollection(parent)) {
        parent.items[key] = node;
    }
    else if (isPair(parent)) {
        if (key === 'key')
            parent.key = node;
        else
            parent.value = node;
    }
    else if (isDocument(parent)) {
        parent.contents = node;
    }
    else {
        const pt = isAlias(parent) ? 'alias' : 'scalar';
        throw new Error(`Cannot replace node with ${pt} parent`);
    }
}

const escapeChars = {
    '!': '%21',
    ',': '%2C',
    '[': '%5B',
    ']': '%5D',
    '{': '%7B',
    '}': '%7D'
};
const escapeTagName = (tn) => tn.replace(/[!,[\]{}]/g, ch => escapeChars[ch]);
class Directives {
    constructor(yaml, tags) {
        /**
         * The directives-end/doc-start marker `---`. If `null`, a marker may still be
         * included in the document's stringified representation.
         */
        this.docStart = null;
        /** The doc-end marker `...`.  */
        this.docEnd = false;
        this.yaml = Object.assign({}, Directives.defaultYaml, yaml);
        this.tags = Object.assign({}, Directives.defaultTags, tags);
    }
    clone() {
        const copy = new Directives(this.yaml, this.tags);
        copy.docStart = this.docStart;
        return copy;
    }
    /**
     * During parsing, get a Directives instance for the current document and
     * update the stream state according to the current version's spec.
     */
    atDocument() {
        const res = new Directives(this.yaml, this.tags);
        switch (this.yaml.version) {
            case '1.1':
                this.atNextDocument = true;
                break;
            case '1.2':
                this.atNextDocument = false;
                this.yaml = {
                    explicit: Directives.defaultYaml.explicit,
                    version: '1.2'
                };
                this.tags = Object.assign({}, Directives.defaultTags);
                break;
        }
        return res;
    }
    /**
     * @param onError - May be called even if the action was successful
     * @returns `true` on success
     */
    add(line, onError) {
        if (this.atNextDocument) {
            this.yaml = { explicit: Directives.defaultYaml.explicit, version: '1.1' };
            this.tags = Object.assign({}, Directives.defaultTags);
            this.atNextDocument = false;
        }
        const parts = line.trim().split(/[ \t]+/);
        const name = parts.shift();
        switch (name) {
            case '%TAG': {
                if (parts.length !== 2) {
                    onError(0, '%TAG directive should contain exactly two parts');
                    if (parts.length < 2)
                        return false;
                }
                const [handle, prefix] = parts;
                this.tags[handle] = prefix;
                return true;
            }
            case '%YAML': {
                this.yaml.explicit = true;
                if (parts.length !== 1) {
                    onError(0, '%YAML directive should contain exactly one part');
                    return false;
                }
                const [version] = parts;
                if (version === '1.1' || version === '1.2') {
                    this.yaml.version = version;
                    return true;
                }
                else {
                    const isValid = /^\d+\.\d+$/.test(version);
                    onError(6, `Unsupported YAML version ${version}`, isValid);
                    return false;
                }
            }
            default:
                onError(0, `Unknown directive ${name}`, true);
                return false;
        }
    }
    /**
     * Resolves a tag, matching handles to those defined in %TAG directives.
     *
     * @returns Resolved tag, which may also be the non-specific tag `'!'` or a
     *   `'!local'` tag, or `null` if unresolvable.
     */
    tagName(source, onError) {
        if (source === '!')
            return '!'; // non-specific tag
        if (source[0] !== '!') {
            onError(`Not a valid tag: ${source}`);
            return null;
        }
        if (source[1] === '<') {
            const verbatim = source.slice(2, -1);
            if (verbatim === '!' || verbatim === '!!') {
                onError(`Verbatim tags aren't resolved, so ${source} is invalid.`);
                return null;
            }
            if (source[source.length - 1] !== '>')
                onError('Verbatim tags must end with a >');
            return verbatim;
        }
        const [, handle, suffix] = source.match(/^(.*!)([^!]*)$/s);
        if (!suffix)
            onError(`The ${source} tag has no suffix`);
        const prefix = this.tags[handle];
        if (prefix) {
            try {
                return prefix + decodeURIComponent(suffix);
            }
            catch (error) {
                onError(String(error));
                return null;
            }
        }
        if (handle === '!')
            return source; // local tag
        onError(`Could not resolve tag: ${source}`);
        return null;
    }
    /**
     * Given a fully resolved tag, returns its printable string form,
     * taking into account current tag prefixes and defaults.
     */
    tagString(tag) {
        for (const [handle, prefix] of Object.entries(this.tags)) {
            if (tag.startsWith(prefix))
                return handle + escapeTagName(tag.substring(prefix.length));
        }
        return tag[0] === '!' ? tag : `!<${tag}>`;
    }
    toString(doc) {
        const lines = this.yaml.explicit
            ? [`%YAML ${this.yaml.version || '1.2'}`]
            : [];
        const tagEntries = Object.entries(this.tags);
        let tagNames;
        if (doc && tagEntries.length > 0 && isNode(doc.contents)) {
            const tags = {};
            visit(doc.contents, (_key, node) => {
                if (isNode(node) && node.tag)
                    tags[node.tag] = true;
            });
            tagNames = Object.keys(tags);
        }
        else
            tagNames = [];
        for (const [handle, prefix] of tagEntries) {
            if (handle === '!!' && prefix === 'tag:yaml.org,2002:')
                continue;
            if (!doc || tagNames.some(tn => tn.startsWith(prefix)))
                lines.push(`%TAG ${handle} ${prefix}`);
        }
        return lines.join('\n');
    }
}
Directives.defaultYaml = { explicit: false, version: '1.2' };
Directives.defaultTags = { '!!': 'tag:yaml.org,2002:' };

/**
 * Verify that the input string is a valid anchor.
 *
 * Will throw on errors.
 */
function anchorIsValid(anchor) {
    if (/[\x00-\x19\s,[\]{}]/.test(anchor)) {
        const sa = JSON.stringify(anchor);
        const msg = `Anchor must not contain whitespace or control characters: ${sa}`;
        throw new Error(msg);
    }
    return true;
}
function anchorNames(root) {
    const anchors = new Set();
    visit(root, {
        Value(_key, node) {
            if (node.anchor)
                anchors.add(node.anchor);
        }
    });
    return anchors;
}
/** Find a new anchor name with the given `prefix` and a one-indexed suffix. */
function findNewAnchor(prefix, exclude) {
    for (let i = 1; true; ++i) {
        const name = `${prefix}${i}`;
        if (!exclude.has(name))
            return name;
    }
}
function createNodeAnchors(doc, prefix) {
    const aliasObjects = [];
    const sourceObjects = new Map();
    let prevAnchors = null;
    return {
        onAnchor: (source) => {
            aliasObjects.push(source);
            if (!prevAnchors)
                prevAnchors = anchorNames(doc);
            const anchor = findNewAnchor(prefix, prevAnchors);
            prevAnchors.add(anchor);
            return anchor;
        },
        /**
         * With circular references, the source node is only resolved after all
         * of its child nodes are. This is why anchors are set only after all of
         * the nodes have been created.
         */
        setAnchors: () => {
            for (const source of aliasObjects) {
                const ref = sourceObjects.get(source);
                if (typeof ref === 'object' &&
                    ref.anchor &&
                    (isScalar(ref.node) || isCollection(ref.node))) {
                    ref.node.anchor = ref.anchor;
                }
                else {
                    const error = new Error('Failed to resolve repeated object (this should not happen)');
                    error.source = source;
                    throw error;
                }
            }
        },
        sourceObjects
    };
}

/**
 * Applies the JSON.parse reviver algorithm as defined in the ECMA-262 spec,
 * in section 24.5.1.1 "Runtime Semantics: InternalizeJSONProperty" of the
 * 2021 edition: https://tc39.es/ecma262/#sec-json.parse
 *
 * Includes extensions for handling Map and Set objects.
 */
function applyReviver(reviver, obj, key, val) {
    if (val && typeof val === 'object') {
        if (Array.isArray(val)) {
            for (let i = 0, len = val.length; i < len; ++i) {
                const v0 = val[i];
                const v1 = applyReviver(reviver, val, String(i), v0);
                // eslint-disable-next-line @typescript-eslint/no-array-delete
                if (v1 === undefined)
                    delete val[i];
                else if (v1 !== v0)
                    val[i] = v1;
            }
        }
        else if (val instanceof Map) {
            for (const k of Array.from(val.keys())) {
                const v0 = val.get(k);
                const v1 = applyReviver(reviver, val, k, v0);
                if (v1 === undefined)
                    val.delete(k);
                else if (v1 !== v0)
                    val.set(k, v1);
            }
        }
        else if (val instanceof Set) {
            for (const v0 of Array.from(val)) {
                const v1 = applyReviver(reviver, val, v0, v0);
                if (v1 === undefined)
                    val.delete(v0);
                else if (v1 !== v0) {
                    val.delete(v0);
                    val.add(v1);
                }
            }
        }
        else {
            for (const [k, v0] of Object.entries(val)) {
                const v1 = applyReviver(reviver, val, k, v0);
                if (v1 === undefined)
                    delete val[k];
                else if (v1 !== v0)
                    val[k] = v1;
            }
        }
    }
    return reviver.call(obj, key, val);
}

/**
 * Recursively convert any node or its contents to native JavaScript
 *
 * @param value - The input value
 * @param arg - If `value` defines a `toJSON()` method, use this
 *   as its first argument
 * @param ctx - Conversion context, originally set in Document#toJS(). If
 *   `{ keep: true }` is not set, output should be suitable for JSON
 *   stringification.
 */
function toJS(value, arg, ctx) {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    if (Array.isArray(value))
        return value.map((v, i) => toJS(v, String(i), ctx));
    if (value && typeof value.toJSON === 'function') {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-call
        if (!ctx || !hasAnchor(value))
            return value.toJSON(arg, ctx);
        const data = { aliasCount: 0, count: 1, res: undefined };
        ctx.anchors.set(value, data);
        ctx.onCreate = res => {
            data.res = res;
            delete ctx.onCreate;
        };
        const res = value.toJSON(arg, ctx);
        if (ctx.onCreate)
            ctx.onCreate(res);
        return res;
    }
    if (typeof value === 'bigint' && !ctx?.keep)
        return Number(value);
    return value;
}

class NodeBase {
    constructor(type) {
        Object.defineProperty(this, NODE_TYPE, { value: type });
    }
    /** Create a copy of this node.  */
    clone() {
        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
        if (this.range)
            copy.range = this.range.slice();
        return copy;
    }
    /** A plain JavaScript representation of this node. */
    toJS(doc, { mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        if (!isDocument(doc))
            throw new TypeError('A document argument is required');
        const ctx = {
            anchors: new Map(),
            doc,
            keep: true,
            mapAsMap: mapAsMap === true,
            mapKeyWarned: false,
            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
        };
        const res = toJS(this, '', ctx);
        if (typeof onAnchor === 'function')
            for (const { count, res } of ctx.anchors.values())
                onAnchor(res, count);
        return typeof reviver === 'function'
            ? applyReviver(reviver, { '': res }, '', res)
            : res;
    }
}

class Alias extends NodeBase {
    constructor(source) {
        super(ALIAS);
        this.source = source;
        Object.defineProperty(this, 'tag', {
            set() {
                throw new Error('Alias nodes cannot have tags');
            }
        });
    }
    /**
     * Resolve the value of this alias within `doc`, finding the last
     * instance of the `source` anchor before this node.
     */
    resolve(doc) {
        let found = undefined;
        visit(doc, {
            Node: (_key, node) => {
                if (node === this)
                    return visit.BREAK;
                if (node.anchor === this.source)
                    found = node;
            }
        });
        return found;
    }
    toJSON(_arg, ctx) {
        if (!ctx)
            return { source: this.source };
        const { anchors, doc, maxAliasCount } = ctx;
        const source = this.resolve(doc);
        if (!source) {
            const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
            throw new ReferenceError(msg);
        }
        let data = anchors.get(source);
        if (!data) {
            // Resolve anchors for Node.prototype.toJS()
            toJS(source, null, ctx);
            data = anchors.get(source);
        }
        /* istanbul ignore if */
        if (!data || data.res === undefined) {
            const msg = 'This should not happen: Alias anchor was not resolved?';
            throw new ReferenceError(msg);
        }
        if (maxAliasCount >= 0) {
            data.count += 1;
            if (data.aliasCount === 0)
                data.aliasCount = getAliasCount(doc, source, anchors);
            if (data.count * data.aliasCount > maxAliasCount) {
                const msg = 'Excessive alias count indicates a resource exhaustion attack';
                throw new ReferenceError(msg);
            }
        }
        return data.res;
    }
    toString(ctx, _onComment, _onChompKeep) {
        const src = `*${this.source}`;
        if (ctx) {
            anchorIsValid(this.source);
            if (ctx.options.verifyAliasOrder && !ctx.anchors.has(this.source)) {
                const msg = `Unresolved alias (the anchor must be set before the alias): ${this.source}`;
                throw new Error(msg);
            }
            if (ctx.implicitKey)
                return `${src} `;
        }
        return src;
    }
}
function getAliasCount(doc, node, anchors) {
    if (isAlias(node)) {
        const source = node.resolve(doc);
        const anchor = anchors && source && anchors.get(source);
        return anchor ? anchor.count * anchor.aliasCount : 0;
    }
    else if (isCollection(node)) {
        let count = 0;
        for (const item of node.items) {
            const c = getAliasCount(doc, item, anchors);
            if (c > count)
                count = c;
        }
        return count;
    }
    else if (isPair(node)) {
        const kc = getAliasCount(doc, node.key, anchors);
        const vc = getAliasCount(doc, node.value, anchors);
        return Math.max(kc, vc);
    }
    return 1;
}

const isScalarValue = (value) => !value || (typeof value !== 'function' && typeof value !== 'object');
class Scalar extends NodeBase {
    constructor(value) {
        super(SCALAR);
        this.value = value;
    }
    toJSON(arg, ctx) {
        return ctx?.keep ? this.value : toJS(this.value, arg, ctx);
    }
    toString() {
        return String(this.value);
    }
}
Scalar.BLOCK_FOLDED = 'BLOCK_FOLDED';
Scalar.BLOCK_LITERAL = 'BLOCK_LITERAL';
Scalar.PLAIN = 'PLAIN';
Scalar.QUOTE_DOUBLE = 'QUOTE_DOUBLE';
Scalar.QUOTE_SINGLE = 'QUOTE_SINGLE';

const defaultTagPrefix = 'tag:yaml.org,2002:';
function findTagObject(value, tagName, tags) {
    if (tagName) {
        const match = tags.filter(t => t.tag === tagName);
        const tagObj = match.find(t => !t.format) ?? match[0];
        if (!tagObj)
            throw new Error(`Tag ${tagName} not found`);
        return tagObj;
    }
    return tags.find(t => t.identify?.(value) && !t.format);
}
function createNode(value, tagName, ctx) {
    if (isDocument(value))
        value = value.contents;
    if (isNode(value))
        return value;
    if (isPair(value)) {
        const map = ctx.schema[MAP].createNode?.(ctx.schema, null, ctx);
        map.items.push(value);
        return map;
    }
    if (value instanceof String ||
        value instanceof Number ||
        value instanceof Boolean ||
        (typeof BigInt !== 'undefined' && value instanceof BigInt) // not supported everywhere
    ) {
        // https://tc39.es/ecma262/#sec-serializejsonproperty
        value = value.valueOf();
    }
    const { aliasDuplicateObjects, onAnchor, onTagObj, schema, sourceObjects } = ctx;
    // Detect duplicate references to the same object & use Alias nodes for all
    // after first. The `ref` wrapper allows for circular references to resolve.
    let ref = undefined;
    if (aliasDuplicateObjects && value && typeof value === 'object') {
        ref = sourceObjects.get(value);
        if (ref) {
            if (!ref.anchor)
                ref.anchor = onAnchor(value);
            return new Alias(ref.anchor);
        }
        else {
            ref = { anchor: null, node: null };
            sourceObjects.set(value, ref);
        }
    }
    if (tagName?.startsWith('!!'))
        tagName = defaultTagPrefix + tagName.slice(2);
    let tagObj = findTagObject(value, tagName, schema.tags);
    if (!tagObj) {
        if (value && typeof value.toJSON === 'function') {
            // eslint-disable-next-line @typescript-eslint/no-unsafe-call
            value = value.toJSON();
        }
        if (!value || typeof value !== 'object') {
            const node = new Scalar(value);
            if (ref)
                ref.node = node;
            return node;
        }
        tagObj =
            value instanceof Map
                ? schema[MAP]
                : Symbol.iterator in Object(value)
                    ? schema[SEQ]
                    : schema[MAP];
    }
    if (onTagObj) {
        onTagObj(tagObj);
        delete ctx.onTagObj;
    }
    const node = tagObj?.createNode
        ? tagObj.createNode(ctx.schema, value, ctx)
        : typeof tagObj?.nodeClass?.from === 'function'
            ? tagObj.nodeClass.from(ctx.schema, value, ctx)
            : new Scalar(value);
    if (tagName)
        node.tag = tagName;
    else if (!tagObj.default)
        node.tag = tagObj.tag;
    if (ref)
        ref.node = node;
    return node;
}

function collectionFromPath(schema, path, value) {
    let v = value;
    for (let i = path.length - 1; i >= 0; --i) {
        const k = path[i];
        if (typeof k === 'number' && Number.isInteger(k) && k >= 0) {
            const a = [];
            a[k] = v;
            v = a;
        }
        else {
            v = new Map([[k, v]]);
        }
    }
    return createNode(v, undefined, {
        aliasDuplicateObjects: false,
        keepUndefined: false,
        onAnchor: () => {
            throw new Error('This should not happen, please report a bug.');
        },
        schema,
        sourceObjects: new Map()
    });
}
// Type guard is intentionally a little wrong so as to be more useful,
// as it does not cover untypable empty non-string iterables (e.g. []).
const isEmptyPath = (path) => path == null ||
    (typeof path === 'object' && !!path[Symbol.iterator]().next().done);
class Collection extends NodeBase {
    constructor(type, schema) {
        super(type);
        Object.defineProperty(this, 'schema', {
            value: schema,
            configurable: true,
            enumerable: false,
            writable: true
        });
    }
    /**
     * Create a copy of this collection.
     *
     * @param schema - If defined, overwrites the original's schema
     */
    clone(schema) {
        const copy = Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
        if (schema)
            copy.schema = schema;
        copy.items = copy.items.map(it => isNode(it) || isPair(it) ? it.clone(schema) : it);
        if (this.range)
            copy.range = this.range.slice();
        return copy;
    }
    /**
     * Adds a value to the collection. For `!!map` and `!!omap` the value must
     * be a Pair instance or a `{ key, value }` object, which may not have a key
     * that already exists in the map.
     */
    addIn(path, value) {
        if (isEmptyPath(path))
            this.add(value);
        else {
            const [key, ...rest] = path;
            const node = this.get(key, true);
            if (isCollection(node))
                node.addIn(rest, value);
            else if (node === undefined && this.schema)
                this.set(key, collectionFromPath(this.schema, rest, value));
            else
                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
        }
    }
    /**
     * Removes a value from the collection.
     * @returns `true` if the item was found and removed.
     */
    deleteIn(path) {
        const [key, ...rest] = path;
        if (rest.length === 0)
            return this.delete(key);
        const node = this.get(key, true);
        if (isCollection(node))
            return node.deleteIn(rest);
        else
            throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
    }
    /**
     * Returns item at `key`, or `undefined` if not found. By default unwraps
     * scalar values from their surrounding node; to disable set `keepScalar` to
     * `true` (collections are always returned intact).
     */
    getIn(path, keepScalar) {
        const [key, ...rest] = path;
        const node = this.get(key, true);
        if (rest.length === 0)
            return !keepScalar && isScalar(node) ? node.value : node;
        else
            return isCollection(node) ? node.getIn(rest, keepScalar) : undefined;
    }
    hasAllNullValues(allowScalar) {
        return this.items.every(node => {
            if (!isPair(node))
                return false;
            const n = node.value;
            return (n == null ||
                (allowScalar &&
                    isScalar(n) &&
                    n.value == null &&
                    !n.commentBefore &&
                    !n.comment &&
                    !n.tag));
        });
    }
    /**
     * Checks if the collection includes a value with the key `key`.
     */
    hasIn(path) {
        const [key, ...rest] = path;
        if (rest.length === 0)
            return this.has(key);
        const node = this.get(key, true);
        return isCollection(node) ? node.hasIn(rest) : false;
    }
    /**
     * Sets a value in this collection. For `!!set`, `value` needs to be a
     * boolean to add/remove the item from the set.
     */
    setIn(path, value) {
        const [key, ...rest] = path;
        if (rest.length === 0) {
            this.set(key, value);
        }
        else {
            const node = this.get(key, true);
            if (isCollection(node))
                node.setIn(rest, value);
            else if (node === undefined && this.schema)
                this.set(key, collectionFromPath(this.schema, rest, value));
            else
                throw new Error(`Expected YAML collection at ${key}. Remaining path: ${rest}`);
        }
    }
}

/**
 * Stringifies a comment.
 *
 * Empty comment lines are left empty,
 * lines consisting of a single space are replaced by `#`,
 * and all other lines are prefixed with a `#`.
 */
const stringifyComment = (str) => str.replace(/^(?!$)(?: $)?/gm, '#');
function indentComment(comment, indent) {
    if (/^\n+$/.test(comment))
        return comment.substring(1);
    return indent ? comment.replace(/^(?! *$)/gm, indent) : comment;
}
const lineComment = (str, indent, comment) => str.endsWith('\n')
    ? indentComment(comment, indent)
    : comment.includes('\n')
        ? '\n' + indentComment(comment, indent)
        : (str.endsWith(' ') ? '' : ' ') + comment;

const FOLD_FLOW = 'flow';
const FOLD_BLOCK = 'block';
const FOLD_QUOTED = 'quoted';
/**
 * Tries to keep input at up to `lineWidth` characters, splitting only on spaces
 * not followed by newlines or spaces unless `mode` is `'quoted'`. Lines are
 * terminated with `\n` and started with `indent`.
 */
function foldFlowLines(text, indent, mode = 'flow', { indentAtStart, lineWidth = 80, minContentWidth = 20, onFold, onOverflow } = {}) {
    if (!lineWidth || lineWidth < 0)
        return text;
    if (lineWidth < minContentWidth)
        minContentWidth = 0;
    const endStep = Math.max(1 + minContentWidth, 1 + lineWidth - indent.length);
    if (text.length <= endStep)
        return text;
    const folds = [];
    const escapedFolds = {};
    let end = lineWidth - indent.length;
    if (typeof indentAtStart === 'number') {
        if (indentAtStart > lineWidth - Math.max(2, minContentWidth))
            folds.push(0);
        else
            end = lineWidth - indentAtStart;
    }
    let split = undefined;
    let prev = undefined;
    let overflow = false;
    let i = -1;
    let escStart = -1;
    let escEnd = -1;
    if (mode === FOLD_BLOCK) {
        i = consumeMoreIndentedLines(text, i, indent.length);
        if (i !== -1)
            end = i + endStep;
    }
    for (let ch; (ch = text[(i += 1)]);) {
        if (mode === FOLD_QUOTED && ch === '\\') {
            escStart = i;
            switch (text[i + 1]) {
                case 'x':
                    i += 3;
                    break;
                case 'u':
                    i += 5;
                    break;
                case 'U':
                    i += 9;
                    break;
                default:
                    i += 1;
            }
            escEnd = i;
        }
        if (ch === '\n') {
            if (mode === FOLD_BLOCK)
                i = consumeMoreIndentedLines(text, i, indent.length);
            end = i + indent.length + endStep;
            split = undefined;
        }
        else {
            if (ch === ' ' &&
                prev &&
                prev !== ' ' &&
                prev !== '\n' &&
                prev !== '\t') {
                // space surrounded by non-space can be replaced with newline + indent
                const next = text[i + 1];
                if (next && next !== ' ' && next !== '\n' && next !== '\t')
                    split = i;
            }
            if (i >= end) {
                if (split) {
                    folds.push(split);
                    end = split + endStep;
                    split = undefined;
                }
                else if (mode === FOLD_QUOTED) {
                    // white-space collected at end may stretch past lineWidth
                    while (prev === ' ' || prev === '\t') {
                        prev = ch;
                        ch = text[(i += 1)];
                        overflow = true;
                    }
                    // Account for newline escape, but don't break preceding escape
                    const j = i > escEnd + 1 ? i - 2 : escStart - 1;
                    // Bail out if lineWidth & minContentWidth are shorter than an escape string
                    if (escapedFolds[j])
                        return text;
                    folds.push(j);
                    escapedFolds[j] = true;
                    end = j + endStep;
                    split = undefined;
                }
                else {
                    overflow = true;
                }
            }
        }
        prev = ch;
    }
    if (overflow && onOverflow)
        onOverflow();
    if (folds.length === 0)
        return text;
    if (onFold)
        onFold();
    let res = text.slice(0, folds[0]);
    for (let i = 0; i < folds.length; ++i) {
        const fold = folds[i];
        const end = folds[i + 1] || text.length;
        if (fold === 0)
            res = `\n${indent}${text.slice(0, end)}`;
        else {
            if (mode === FOLD_QUOTED && escapedFolds[fold])
                res += `${text[fold]}\\`;
            res += `\n${indent}${text.slice(fold + 1, end)}`;
        }
    }
    return res;
}
/**
 * Presumes `i + 1` is at the start of a line
 * @returns index of last newline in more-indented block
 */
function consumeMoreIndentedLines(text, i, indent) {
    let end = i;
    let start = i + 1;
    let ch = text[start];
    while (ch === ' ' || ch === '\t') {
        if (i < start + indent) {
            ch = text[++i];
        }
        else {
            do {
                ch = text[++i];
            } while (ch && ch !== '\n');
            end = i;
            start = i + 1;
            ch = text[start];
        }
    }
    return end;
}

const getFoldOptions = (ctx, isBlock) => ({
    indentAtStart: isBlock ? ctx.indent.length : ctx.indentAtStart,
    lineWidth: ctx.options.lineWidth,
    minContentWidth: ctx.options.minContentWidth
});
// Also checks for lines starting with %, as parsing the output as YAML 1.1 will
// presume that's starting a new document.
const containsDocumentMarker = (str) => /^(%|---|\.\.\.)/m.test(str);
function lineLengthOverLimit(str, lineWidth, indentLength) {
    if (!lineWidth || lineWidth < 0)
        return false;
    const limit = lineWidth - indentLength;
    const strLen = str.length;
    if (strLen <= limit)
        return false;
    for (let i = 0, start = 0; i < strLen; ++i) {
        if (str[i] === '\n') {
            if (i - start > limit)
                return true;
            start = i + 1;
            if (strLen - start <= limit)
                return false;
        }
    }
    return true;
}
function doubleQuotedString(value, ctx) {
    const json = JSON.stringify(value);
    if (ctx.options.doubleQuotedAsJSON)
        return json;
    const { implicitKey } = ctx;
    const minMultiLineLength = ctx.options.doubleQuotedMinMultiLineLength;
    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');
    let str = '';
    let start = 0;
    for (let i = 0, ch = json[i]; ch; ch = json[++i]) {
        if (ch === ' ' && json[i + 1] === '\\' && json[i + 2] === 'n') {
            // space before newline needs to be escaped to not be folded
            str += json.slice(start, i) + '\\ ';
            i += 1;
            start = i;
            ch = '\\';
        }
        if (ch === '\\')
            switch (json[i + 1]) {
                case 'u':
                    {
                        str += json.slice(start, i);
                        const code = json.substr(i + 2, 4);
                        switch (code) {
                            case '0000':
                                str += '\\0';
                                break;
                            case '0007':
                                str += '\\a';
                                break;
                            case '000b':
                                str += '\\v';
                                break;
                            case '001b':
                                str += '\\e';
                                break;
                            case '0085':
                                str += '\\N';
                                break;
                            case '00a0':
                                str += '\\_';
                                break;
                            case '2028':
                                str += '\\L';
                                break;
                            case '2029':
                                str += '\\P';
                                break;
                            default:
                                if (code.substr(0, 2) === '00')
                                    str += '\\x' + code.substr(2);
                                else
                                    str += json.substr(i, 6);
                        }
                        i += 5;
                        start = i + 1;
                    }
                    break;
                case 'n':
                    if (implicitKey ||
                        json[i + 2] === '"' ||
                        json.length < minMultiLineLength) {
                        i += 1;
                    }
                    else {
                        // folding will eat first newline
                        str += json.slice(start, i) + '\n\n';
                        while (json[i + 2] === '\\' &&
                            json[i + 3] === 'n' &&
                            json[i + 4] !== '"') {
                            str += '\n';
                            i += 2;
                        }
                        str += indent;
                        // space after newline needs to be escaped to not be folded
                        if (json[i + 2] === ' ')
                            str += '\\';
                        i += 1;
                        start = i + 1;
                    }
                    break;
                default:
                    i += 1;
            }
    }
    str = start ? str + json.slice(start) : json;
    return implicitKey
        ? str
        : foldFlowLines(str, indent, FOLD_QUOTED, getFoldOptions(ctx, false));
}
function singleQuotedString(value, ctx) {
    if (ctx.options.singleQuote === false ||
        (ctx.implicitKey && value.includes('\n')) ||
        /[ \t]\n|\n[ \t]/.test(value) // single quoted string can't have leading or trailing whitespace around newline
    )
        return doubleQuotedString(value, ctx);
    const indent = ctx.indent || (containsDocumentMarker(value) ? '  ' : '');
    const res = "'" + value.replace(/'/g, "''").replace(/\n+/g, `$&\n${indent}`) + "'";
    return ctx.implicitKey
        ? res
        : foldFlowLines(res, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function quotedString(value, ctx) {
    const { singleQuote } = ctx.options;
    let qs;
    if (singleQuote === false)
        qs = doubleQuotedString;
    else {
        const hasDouble = value.includes('"');
        const hasSingle = value.includes("'");
        if (hasDouble && !hasSingle)
            qs = singleQuotedString;
        else if (hasSingle && !hasDouble)
            qs = doubleQuotedString;
        else
            qs = singleQuote ? singleQuotedString : doubleQuotedString;
    }
    return qs(value, ctx);
}
// The negative lookbehind avoids a polynomial search,
// but isn't supported yet on Safari: https://caniuse.com/js-regexp-lookbehind
let blockEndNewlines;
try {
    blockEndNewlines = new RegExp('(^|(?<!\n))\n+(?!\n|$)', 'g');
}
catch {
    blockEndNewlines = /\n+(?!\n|$)/g;
}
function blockString({ comment, type, value }, ctx, onComment, onChompKeep) {
    const { blockQuote, commentString, lineWidth } = ctx.options;
    // 1. Block can't end in whitespace unless the last line is non-empty.
    // 2. Strings consisting of only whitespace are best rendered explicitly.
    if (!blockQuote || /\n[\t ]+$/.test(value) || /^\s*$/.test(value)) {
        return quotedString(value, ctx);
    }
    const indent = ctx.indent ||
        (ctx.forceBlockIndent || containsDocumentMarker(value) ? '  ' : '');
    const literal = blockQuote === 'literal'
        ? true
        : blockQuote === 'folded' || type === Scalar.BLOCK_FOLDED
            ? false
            : type === Scalar.BLOCK_LITERAL
                ? true
                : !lineLengthOverLimit(value, lineWidth, indent.length);
    if (!value)
        return literal ? '|\n' : '>\n';
    // determine chomping from whitespace at value end
    let chomp;
    let endStart;
    for (endStart = value.length; endStart > 0; --endStart) {
        const ch = value[endStart - 1];
        if (ch !== '\n' && ch !== '\t' && ch !== ' ')
            break;
    }
    let end = value.substring(endStart);
    const endNlPos = end.indexOf('\n');
    if (endNlPos === -1) {
        chomp = '-'; // strip
    }
    else if (value === end || endNlPos !== end.length - 1) {
        chomp = '+'; // keep
        if (onChompKeep)
            onChompKeep();
    }
    else {
        chomp = ''; // clip
    }
    if (end) {
        value = value.slice(0, -end.length);
        if (end[end.length - 1] === '\n')
            end = end.slice(0, -1);
        end = end.replace(blockEndNewlines, `$&${indent}`);
    }
    // determine indent indicator from whitespace at value start
    let startWithSpace = false;
    let startEnd;
    let startNlPos = -1;
    for (startEnd = 0; startEnd < value.length; ++startEnd) {
        const ch = value[startEnd];
        if (ch === ' ')
            startWithSpace = true;
        else if (ch === '\n')
            startNlPos = startEnd;
        else
            break;
    }
    let start = value.substring(0, startNlPos < startEnd ? startNlPos + 1 : startEnd);
    if (start) {
        value = value.substring(start.length);
        start = start.replace(/\n+/g, `$&${indent}`);
    }
    const indentSize = indent ? '2' : '1'; // root is at -1
    // Leading | or > is added later
    let header = (startWithSpace ? indentSize : '') + chomp;
    if (comment) {
        header += ' ' + commentString(comment.replace(/ ?[\r\n]+/g, ' '));
        if (onComment)
            onComment();
    }
    if (!literal) {
        const foldedValue = value
            .replace(/\n+/g, '\n$&')
            .replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g, '$1$2') // more-indented lines aren't folded
            //                ^ more-ind. ^ empty     ^ capture next empty lines only at end of indent
            .replace(/\n+/g, `$&${indent}`);
        let literalFallback = false;
        const foldOptions = getFoldOptions(ctx, true);
        if (blockQuote !== 'folded' && type !== Scalar.BLOCK_FOLDED) {
            foldOptions.onOverflow = () => {
                literalFallback = true;
            };
        }
        const body = foldFlowLines(`${start}${foldedValue}${end}`, indent, FOLD_BLOCK, foldOptions);
        if (!literalFallback)
            return `>${header}\n${indent}${body}`;
    }
    value = value.replace(/\n+/g, `$&${indent}`);
    return `|${header}\n${indent}${start}${value}${end}`;
}
function plainString(item, ctx, onComment, onChompKeep) {
    const { type, value } = item;
    const { actualString, implicitKey, indent, indentStep, inFlow } = ctx;
    if ((implicitKey && value.includes('\n')) ||
        (inFlow && /[[\]{},]/.test(value))) {
        return quotedString(value, ctx);
    }
    if (!value ||
        /^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(value)) {
        // not allowed:
        // - empty string, '-' or '?'
        // - start with an indicator character (except [?:-]) or /[?-] /
        // - '\n ', ': ' or ' \n' anywhere
        // - '#' not preceded by a non-space char
        // - end with ' ' or ':'
        return implicitKey || inFlow || !value.includes('\n')
            ? quotedString(value, ctx)
            : blockString(item, ctx, onComment, onChompKeep);
    }
    if (!implicitKey &&
        !inFlow &&
        type !== Scalar.PLAIN &&
        value.includes('\n')) {
        // Where allowed & type not set explicitly, prefer block style for multiline strings
        return blockString(item, ctx, onComment, onChompKeep);
    }
    if (containsDocumentMarker(value)) {
        if (indent === '') {
            ctx.forceBlockIndent = true;
            return blockString(item, ctx, onComment, onChompKeep);
        }
        else if (implicitKey && indent === indentStep) {
            return quotedString(value, ctx);
        }
    }
    const str = value.replace(/\n+/g, `$&\n${indent}`);
    // Verify that output will be parsed as a string, as e.g. plain numbers and
    // booleans get parsed with those types in v1.2 (e.g. '42', 'true' & '0.9e-3'),
    // and others in v1.1.
    if (actualString) {
        const test = (tag) => tag.default && tag.tag !== 'tag:yaml.org,2002:str' && tag.test?.test(str);
        const { compat, tags } = ctx.doc.schema;
        if (tags.some(test) || compat?.some(test))
            return quotedString(value, ctx);
    }
    return implicitKey
        ? str
        : foldFlowLines(str, indent, FOLD_FLOW, getFoldOptions(ctx, false));
}
function stringifyString(item, ctx, onComment, onChompKeep) {
    const { implicitKey, inFlow } = ctx;
    const ss = typeof item.value === 'string'
        ? item
        : Object.assign({}, item, { value: String(item.value) });
    let { type } = item;
    if (type !== Scalar.QUOTE_DOUBLE) {
        // force double quotes on control characters & unpaired surrogates
        if (/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(ss.value))
            type = Scalar.QUOTE_DOUBLE;
    }
    const _stringify = (_type) => {
        switch (_type) {
            case Scalar.BLOCK_FOLDED:
            case Scalar.BLOCK_LITERAL:
                return implicitKey || inFlow
                    ? quotedString(ss.value, ctx) // blocks are not valid inside flow containers
                    : blockString(ss, ctx, onComment, onChompKeep);
            case Scalar.QUOTE_DOUBLE:
                return doubleQuotedString(ss.value, ctx);
            case Scalar.QUOTE_SINGLE:
                return singleQuotedString(ss.value, ctx);
            case Scalar.PLAIN:
                return plainString(ss, ctx, onComment, onChompKeep);
            default:
                return null;
        }
    };
    let res = _stringify(type);
    if (res === null) {
        const { defaultKeyType, defaultStringType } = ctx.options;
        const t = (implicitKey && defaultKeyType) || defaultStringType;
        res = _stringify(t);
        if (res === null)
            throw new Error(`Unsupported default string type ${t}`);
    }
    return res;
}

function createStringifyContext(doc, options) {
    const opt = Object.assign({
        blockQuote: true,
        commentString: stringifyComment,
        defaultKeyType: null,
        defaultStringType: 'PLAIN',
        directives: null,
        doubleQuotedAsJSON: false,
        doubleQuotedMinMultiLineLength: 40,
        falseStr: 'false',
        flowCollectionPadding: true,
        indentSeq: true,
        lineWidth: 80,
        minContentWidth: 20,
        nullStr: 'null',
        simpleKeys: false,
        singleQuote: null,
        trueStr: 'true',
        verifyAliasOrder: true
    }, doc.schema.toStringOptions, options);
    let inFlow;
    switch (opt.collectionStyle) {
        case 'block':
            inFlow = false;
            break;
        case 'flow':
            inFlow = true;
            break;
        default:
            inFlow = null;
    }
    return {
        anchors: new Set(),
        doc,
        flowCollectionPadding: opt.flowCollectionPadding ? ' ' : '',
        indent: '',
        indentStep: typeof opt.indent === 'number' ? ' '.repeat(opt.indent) : '  ',
        inFlow,
        options: opt
    };
}
function getTagObject(tags, item) {
    if (item.tag) {
        const match = tags.filter(t => t.tag === item.tag);
        if (match.length > 0)
            return match.find(t => t.format === item.format) ?? match[0];
    }
    let tagObj = undefined;
    let obj;
    if (isScalar(item)) {
        obj = item.value;
        let match = tags.filter(t => t.identify?.(obj));
        if (match.length > 1) {
            const testMatch = match.filter(t => t.test);
            if (testMatch.length > 0)
                match = testMatch;
        }
        tagObj =
            match.find(t => t.format === item.format) ?? match.find(t => !t.format);
    }
    else {
        obj = item;
        tagObj = tags.find(t => t.nodeClass && obj instanceof t.nodeClass);
    }
    if (!tagObj) {
        const name = obj?.constructor?.name ?? typeof obj;
        throw new Error(`Tag not resolved for ${name} value`);
    }
    return tagObj;
}
// needs to be called before value stringifier to allow for circular anchor refs
function stringifyProps(node, tagObj, { anchors, doc }) {
    if (!doc.directives)
        return '';
    const props = [];
    const anchor = (isScalar(node) || isCollection(node)) && node.anchor;
    if (anchor && anchorIsValid(anchor)) {
        anchors.add(anchor);
        props.push(`&${anchor}`);
    }
    const tag = node.tag ? node.tag : tagObj.default ? null : tagObj.tag;
    if (tag)
        props.push(doc.directives.tagString(tag));
    return props.join(' ');
}
function stringify$1(item, ctx, onComment, onChompKeep) {
    if (isPair(item))
        return item.toString(ctx, onComment, onChompKeep);
    if (isAlias(item)) {
        if (ctx.doc.directives)
            return item.toString(ctx);
        if (ctx.resolvedAliases?.has(item)) {
            throw new TypeError(`Cannot stringify circular structure without alias nodes`);
        }
        else {
            if (ctx.resolvedAliases)
                ctx.resolvedAliases.add(item);
            else
                ctx.resolvedAliases = new Set([item]);
            item = item.resolve(ctx.doc);
        }
    }
    let tagObj = undefined;
    const node = isNode(item)
        ? item
        : ctx.doc.createNode(item, { onTagObj: o => (tagObj = o) });
    if (!tagObj)
        tagObj = getTagObject(ctx.doc.schema.tags, node);
    const props = stringifyProps(node, tagObj, ctx);
    if (props.length > 0)
        ctx.indentAtStart = (ctx.indentAtStart ?? 0) + props.length + 1;
    const str = typeof tagObj.stringify === 'function'
        ? tagObj.stringify(node, ctx, onComment, onChompKeep)
        : isScalar(node)
            ? stringifyString(node, ctx, onComment, onChompKeep)
            : node.toString(ctx, onComment, onChompKeep);
    if (!props)
        return str;
    return isScalar(node) || str[0] === '{' || str[0] === '['
        ? `${props} ${str}`
        : `${props}\n${ctx.indent}${str}`;
}

function stringifyPair({ key, value }, ctx, onComment, onChompKeep) {
    const { allNullValues, doc, indent, indentStep, options: { commentString, indentSeq, simpleKeys } } = ctx;
    let keyComment = (isNode(key) && key.comment) || null;
    if (simpleKeys) {
        if (keyComment) {
            throw new Error('With simple keys, key nodes cannot have comments');
        }
        if (isCollection(key) || (!isNode(key) && typeof key === 'object')) {
            const msg = 'With simple keys, collection cannot be used as a key value';
            throw new Error(msg);
        }
    }
    let explicitKey = !simpleKeys &&
        (!key ||
            (keyComment && value == null && !ctx.inFlow) ||
            isCollection(key) ||
            (isScalar(key)
                ? key.type === Scalar.BLOCK_FOLDED || key.type === Scalar.BLOCK_LITERAL
                : typeof key === 'object'));
    ctx = Object.assign({}, ctx, {
        allNullValues: false,
        implicitKey: !explicitKey && (simpleKeys || !allNullValues),
        indent: indent + indentStep
    });
    let keyCommentDone = false;
    let chompKeep = false;
    let str = stringify$1(key, ctx, () => (keyCommentDone = true), () => (chompKeep = true));
    if (!explicitKey && !ctx.inFlow && str.length > 1024) {
        if (simpleKeys)
            throw new Error('With simple keys, single line scalar must not span more than 1024 characters');
        explicitKey = true;
    }
    if (ctx.inFlow) {
        if (allNullValues || value == null) {
            if (keyCommentDone && onComment)
                onComment();
            return str === '' ? '?' : explicitKey ? `? ${str}` : str;
        }
    }
    else if ((allNullValues && !simpleKeys) || (value == null && explicitKey)) {
        str = `? ${str}`;
        if (keyComment && !keyCommentDone) {
            str += lineComment(str, ctx.indent, commentString(keyComment));
        }
        else if (chompKeep && onChompKeep)
            onChompKeep();
        return str;
    }
    if (keyCommentDone)
        keyComment = null;
    if (explicitKey) {
        if (keyComment)
            str += lineComment(str, ctx.indent, commentString(keyComment));
        str = `? ${str}\n${indent}:`;
    }
    else {
        str = `${str}:`;
        if (keyComment)
            str += lineComment(str, ctx.indent, commentString(keyComment));
    }
    let vsb, vcb, valueComment;
    if (isNode(value)) {
        vsb = !!value.spaceBefore;
        vcb = value.commentBefore;
        valueComment = value.comment;
    }
    else {
        vsb = false;
        vcb = null;
        valueComment = null;
        if (value && typeof value === 'object')
            value = doc.createNode(value);
    }
    ctx.implicitKey = false;
    if (!explicitKey && !keyComment && isScalar(value))
        ctx.indentAtStart = str.length + 1;
    chompKeep = false;
    if (!indentSeq &&
        indentStep.length >= 2 &&
        !ctx.inFlow &&
        !explicitKey &&
        isSeq(value) &&
        !value.flow &&
        !value.tag &&
        !value.anchor) {
        // If indentSeq === false, consider '- ' as part of indentation where possible
        ctx.indent = ctx.indent.substring(2);
    }
    let valueCommentDone = false;
    const valueStr = stringify$1(value, ctx, () => (valueCommentDone = true), () => (chompKeep = true));
    let ws = ' ';
    if (keyComment || vsb || vcb) {
        ws = vsb ? '\n' : '';
        if (vcb) {
            const cs = commentString(vcb);
            ws += `\n${indentComment(cs, ctx.indent)}`;
        }
        if (valueStr === '' && !ctx.inFlow) {
            if (ws === '\n')
                ws = '\n\n';
        }
        else {
            ws += `\n${ctx.indent}`;
        }
    }
    else if (!explicitKey && isCollection(value)) {
        const vs0 = valueStr[0];
        const nl0 = valueStr.indexOf('\n');
        const hasNewline = nl0 !== -1;
        const flow = ctx.inFlow ?? value.flow ?? value.items.length === 0;
        if (hasNewline || !flow) {
            let hasPropsLine = false;
            if (hasNewline && (vs0 === '&' || vs0 === '!')) {
                let sp0 = valueStr.indexOf(' ');
                if (vs0 === '&' &&
                    sp0 !== -1 &&
                    sp0 < nl0 &&
                    valueStr[sp0 + 1] === '!') {
                    sp0 = valueStr.indexOf(' ', sp0 + 1);
                }
                if (sp0 === -1 || nl0 < sp0)
                    hasPropsLine = true;
            }
            if (!hasPropsLine)
                ws = `\n${ctx.indent}`;
        }
    }
    else if (valueStr === '' || valueStr[0] === '\n') {
        ws = '';
    }
    str += ws + valueStr;
    if (ctx.inFlow) {
        if (valueCommentDone && onComment)
            onComment();
    }
    else if (valueComment && !valueCommentDone) {
        str += lineComment(str, ctx.indent, commentString(valueComment));
    }
    else if (chompKeep && onChompKeep) {
        onChompKeep();
    }
    return str;
}

function warn(logLevel, warning) {
    if (logLevel === 'debug' || logLevel === 'warn') {
        console.warn(warning);
    }
}

// If the value associated with a merge key is a single mapping node, each of
// its key/value pairs is inserted into the current mapping, unless the key
// already exists in it. If the value associated with the merge key is a
// sequence, then this sequence is expected to contain mapping nodes and each
// of these nodes is merged in turn according to its order in the sequence.
// Keys in mapping nodes earlier in the sequence override keys specified in
// later mapping nodes. -- http://yaml.org/type/merge.html
const MERGE_KEY = '<<';
const merge = {
    identify: value => value === MERGE_KEY ||
        (typeof value === 'symbol' && value.description === MERGE_KEY),
    default: 'key',
    tag: 'tag:yaml.org,2002:merge',
    test: /^<<$/,
    resolve: () => Object.assign(new Scalar(Symbol(MERGE_KEY)), {
        addToJSMap: addMergeToJSMap
    }),
    stringify: () => MERGE_KEY
};
const isMergeKey = (ctx, key) => (merge.identify(key) ||
    (isScalar(key) &&
        (!key.type || key.type === Scalar.PLAIN) &&
        merge.identify(key.value))) &&
    ctx?.doc.schema.tags.some(tag => tag.tag === merge.tag && tag.default);
function addMergeToJSMap(ctx, map, value) {
    value = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
    if (isSeq(value))
        for (const it of value.items)
            mergeValue(ctx, map, it);
    else if (Array.isArray(value))
        for (const it of value)
            mergeValue(ctx, map, it);
    else
        mergeValue(ctx, map, value);
}
function mergeValue(ctx, map, value) {
    const source = ctx && isAlias(value) ? value.resolve(ctx.doc) : value;
    if (!isMap(source))
        throw new Error('Merge sources must be maps or map aliases');
    const srcMap = source.toJSON(null, ctx, Map);
    for (const [key, value] of srcMap) {
        if (map instanceof Map) {
            if (!map.has(key))
                map.set(key, value);
        }
        else if (map instanceof Set) {
            map.add(key);
        }
        else if (!Object.prototype.hasOwnProperty.call(map, key)) {
            Object.defineProperty(map, key, {
                value,
                writable: true,
                enumerable: true,
                configurable: true
            });
        }
    }
    return map;
}

function addPairToJSMap(ctx, map, { key, value }) {
    if (isNode(key) && key.addToJSMap)
        key.addToJSMap(ctx, map, value);
    // TODO: Should drop this special case for bare << handling
    else if (isMergeKey(ctx, key))
        addMergeToJSMap(ctx, map, value);
    else {
        const jsKey = toJS(key, '', ctx);
        if (map instanceof Map) {
            map.set(jsKey, toJS(value, jsKey, ctx));
        }
        else if (map instanceof Set) {
            map.add(jsKey);
        }
        else {
            const stringKey = stringifyKey(key, jsKey, ctx);
            const jsValue = toJS(value, stringKey, ctx);
            if (stringKey in map)
                Object.defineProperty(map, stringKey, {
                    value: jsValue,
                    writable: true,
                    enumerable: true,
                    configurable: true
                });
            else
                map[stringKey] = jsValue;
        }
    }
    return map;
}
function stringifyKey(key, jsKey, ctx) {
    if (jsKey === null)
        return '';
    if (typeof jsKey !== 'object')
        return String(jsKey);
    if (isNode(key) && ctx?.doc) {
        const strCtx = createStringifyContext(ctx.doc, {});
        strCtx.anchors = new Set();
        for (const node of ctx.anchors.keys())
            strCtx.anchors.add(node.anchor);
        strCtx.inFlow = true;
        strCtx.inStringifyKey = true;
        const strKey = key.toString(strCtx);
        if (!ctx.mapKeyWarned) {
            let jsonStr = JSON.stringify(strKey);
            if (jsonStr.length > 40)
                jsonStr = jsonStr.substring(0, 36) + '..."';
            warn(ctx.doc.options.logLevel, `Keys with collection values will be stringified due to JS Object restrictions: ${jsonStr}. Set mapAsMap: true to use object keys.`);
            ctx.mapKeyWarned = true;
        }
        return strKey;
    }
    return JSON.stringify(jsKey);
}

function createPair(key, value, ctx) {
    const k = createNode(key, undefined, ctx);
    const v = createNode(value, undefined, ctx);
    return new Pair(k, v);
}
class Pair {
    constructor(key, value = null) {
        Object.defineProperty(this, NODE_TYPE, { value: PAIR });
        this.key = key;
        this.value = value;
    }
    clone(schema) {
        let { key, value } = this;
        if (isNode(key))
            key = key.clone(schema);
        if (isNode(value))
            value = value.clone(schema);
        return new Pair(key, value);
    }
    toJSON(_, ctx) {
        const pair = ctx?.mapAsMap ? new Map() : {};
        return addPairToJSMap(ctx, pair, this);
    }
    toString(ctx, onComment, onChompKeep) {
        return ctx?.doc
            ? stringifyPair(this, ctx, onComment, onChompKeep)
            : JSON.stringify(this);
    }
}

function stringifyCollection(collection, ctx, options) {
    const flow = ctx.inFlow ?? collection.flow;
    const stringify = flow ? stringifyFlowCollection : stringifyBlockCollection;
    return stringify(collection, ctx, options);
}
function stringifyBlockCollection({ comment, items }, ctx, { blockItemPrefix, flowChars, itemIndent, onChompKeep, onComment }) {
    const { indent, options: { commentString } } = ctx;
    const itemCtx = Object.assign({}, ctx, { indent: itemIndent, type: null });
    let chompKeep = false; // flag for the preceding node's status
    const lines = [];
    for (let i = 0; i < items.length; ++i) {
        const item = items[i];
        let comment = null;
        if (isNode(item)) {
            if (!chompKeep && item.spaceBefore)
                lines.push('');
            addCommentBefore(ctx, lines, item.commentBefore, chompKeep);
            if (item.comment)
                comment = item.comment;
        }
        else if (isPair(item)) {
            const ik = isNode(item.key) ? item.key : null;
            if (ik) {
                if (!chompKeep && ik.spaceBefore)
                    lines.push('');
                addCommentBefore(ctx, lines, ik.commentBefore, chompKeep);
            }
        }
        chompKeep = false;
        let str = stringify$1(item, itemCtx, () => (comment = null), () => (chompKeep = true));
        if (comment)
            str += lineComment(str, itemIndent, commentString(comment));
        if (chompKeep && comment)
            chompKeep = false;
        lines.push(blockItemPrefix + str);
    }
    let str;
    if (lines.length === 0) {
        str = flowChars.start + flowChars.end;
    }
    else {
        str = lines[0];
        for (let i = 1; i < lines.length; ++i) {
            const line = lines[i];
            str += line ? `\n${indent}${line}` : '\n';
        }
    }
    if (comment) {
        str += '\n' + indentComment(commentString(comment), indent);
        if (onComment)
            onComment();
    }
    else if (chompKeep && onChompKeep)
        onChompKeep();
    return str;
}
function stringifyFlowCollection({ items }, ctx, { flowChars, itemIndent }) {
    const { indent, indentStep, flowCollectionPadding: fcPadding, options: { commentString } } = ctx;
    itemIndent += indentStep;
    const itemCtx = Object.assign({}, ctx, {
        indent: itemIndent,
        inFlow: true,
        type: null
    });
    let reqNewline = false;
    let linesAtValue = 0;
    const lines = [];
    for (let i = 0; i < items.length; ++i) {
        const item = items[i];
        let comment = null;
        if (isNode(item)) {
            if (item.spaceBefore)
                lines.push('');
            addCommentBefore(ctx, lines, item.commentBefore, false);
            if (item.comment)
                comment = item.comment;
        }
        else if (isPair(item)) {
            const ik = isNode(item.key) ? item.key : null;
            if (ik) {
                if (ik.spaceBefore)
                    lines.push('');
                addCommentBefore(ctx, lines, ik.commentBefore, false);
                if (ik.comment)
                    reqNewline = true;
            }
            const iv = isNode(item.value) ? item.value : null;
            if (iv) {
                if (iv.comment)
                    comment = iv.comment;
                if (iv.commentBefore)
                    reqNewline = true;
            }
            else if (item.value == null && ik?.comment) {
                comment = ik.comment;
            }
        }
        if (comment)
            reqNewline = true;
        let str = stringify$1(item, itemCtx, () => (comment = null));
        if (i < items.length - 1)
            str += ',';
        if (comment)
            str += lineComment(str, itemIndent, commentString(comment));
        if (!reqNewline && (lines.length > linesAtValue || str.includes('\n')))
            reqNewline = true;
        lines.push(str);
        linesAtValue = lines.length;
    }
    const { start, end } = flowChars;
    if (lines.length === 0) {
        return start + end;
    }
    else {
        if (!reqNewline) {
            const len = lines.reduce((sum, line) => sum + line.length + 2, 2);
            reqNewline = ctx.options.lineWidth > 0 && len > ctx.options.lineWidth;
        }
        if (reqNewline) {
            let str = start;
            for (const line of lines)
                str += line ? `\n${indentStep}${indent}${line}` : '\n';
            return `${str}\n${indent}${end}`;
        }
        else {
            return `${start}${fcPadding}${lines.join(' ')}${fcPadding}${end}`;
        }
    }
}
function addCommentBefore({ indent, options: { commentString } }, lines, comment, chompKeep) {
    if (comment && chompKeep)
        comment = comment.replace(/^\n+/, '');
    if (comment) {
        const ic = indentComment(commentString(comment), indent);
        lines.push(ic.trimStart()); // Avoid double indent on first line
    }
}

function findPair(items, key) {
    const k = isScalar(key) ? key.value : key;
    for (const it of items) {
        if (isPair(it)) {
            if (it.key === key || it.key === k)
                return it;
            if (isScalar(it.key) && it.key.value === k)
                return it;
        }
    }
    return undefined;
}
class YAMLMap extends Collection {
    static get tagName() {
        return 'tag:yaml.org,2002:map';
    }
    constructor(schema) {
        super(MAP, schema);
        this.items = [];
    }
    /**
     * A generic collection parsing method that can be extended
     * to other node classes that inherit from YAMLMap
     */
    static from(schema, obj, ctx) {
        const { keepUndefined, replacer } = ctx;
        const map = new this(schema);
        const add = (key, value) => {
            if (typeof replacer === 'function')
                value = replacer.call(obj, key, value);
            else if (Array.isArray(replacer) && !replacer.includes(key))
                return;
            if (value !== undefined || keepUndefined)
                map.items.push(createPair(key, value, ctx));
        };
        if (obj instanceof Map) {
            for (const [key, value] of obj)
                add(key, value);
        }
        else if (obj && typeof obj === 'object') {
            for (const key of Object.keys(obj))
                add(key, obj[key]);
        }
        if (typeof schema.sortMapEntries === 'function') {
            map.items.sort(schema.sortMapEntries);
        }
        return map;
    }
    /**
     * Adds a value to the collection.
     *
     * @param overwrite - If not set `true`, using a key that is already in the
     *   collection will throw. Otherwise, overwrites the previous value.
     */
    add(pair, overwrite) {
        let _pair;
        if (isPair(pair))
            _pair = pair;
        else if (!pair || typeof pair !== 'object' || !('key' in pair)) {
            // In TypeScript, this never happens.
            _pair = new Pair(pair, pair?.value);
        }
        else
            _pair = new Pair(pair.key, pair.value);
        const prev = findPair(this.items, _pair.key);
        const sortEntries = this.schema?.sortMapEntries;
        if (prev) {
            if (!overwrite)
                throw new Error(`Key ${_pair.key} already set`);
            // For scalars, keep the old node & its comments and anchors
            if (isScalar(prev.value) && isScalarValue(_pair.value))
                prev.value.value = _pair.value;
            else
                prev.value = _pair.value;
        }
        else if (sortEntries) {
            const i = this.items.findIndex(item => sortEntries(_pair, item) < 0);
            if (i === -1)
                this.items.push(_pair);
            else
                this.items.splice(i, 0, _pair);
        }
        else {
            this.items.push(_pair);
        }
    }
    delete(key) {
        const it = findPair(this.items, key);
        if (!it)
            return false;
        const del = this.items.splice(this.items.indexOf(it), 1);
        return del.length > 0;
    }
    get(key, keepScalar) {
        const it = findPair(this.items, key);
        const node = it?.value;
        return (!keepScalar && isScalar(node) ? node.value : node) ?? undefined;
    }
    has(key) {
        return !!findPair(this.items, key);
    }
    set(key, value) {
        this.add(new Pair(key, value), true);
    }
    /**
     * @param ctx - Conversion context, originally set in Document#toJS()
     * @param {Class} Type - If set, forces the returned collection type
     * @returns Instance of Type, Map, or Object
     */
    toJSON(_, ctx, Type) {
        const map = Type ? new Type() : ctx?.mapAsMap ? new Map() : {};
        if (ctx?.onCreate)
            ctx.onCreate(map);
        for (const item of this.items)
            addPairToJSMap(ctx, map, item);
        return map;
    }
    toString(ctx, onComment, onChompKeep) {
        if (!ctx)
            return JSON.stringify(this);
        for (const item of this.items) {
            if (!isPair(item))
                throw new Error(`Map items must all be pairs; found ${JSON.stringify(item)} instead`);
        }
        if (!ctx.allNullValues && this.hasAllNullValues(false))
            ctx = Object.assign({}, ctx, { allNullValues: true });
        return stringifyCollection(this, ctx, {
            blockItemPrefix: '',
            flowChars: { start: '{', end: '}' },
            itemIndent: ctx.indent || '',
            onChompKeep,
            onComment
        });
    }
}

const map = {
    collection: 'map',
    default: true,
    nodeClass: YAMLMap,
    tag: 'tag:yaml.org,2002:map',
    resolve(map, onError) {
        if (!isMap(map))
            onError('Expected a mapping for this tag');
        return map;
    },
    createNode: (schema, obj, ctx) => YAMLMap.from(schema, obj, ctx)
};

class YAMLSeq extends Collection {
    static get tagName() {
        return 'tag:yaml.org,2002:seq';
    }
    constructor(schema) {
        super(SEQ, schema);
        this.items = [];
    }
    add(value) {
        this.items.push(value);
    }
    /**
     * Removes a value from the collection.
     *
     * `key` must contain a representation of an integer for this to succeed.
     * It may be wrapped in a `Scalar`.
     *
     * @returns `true` if the item was found and removed.
     */
    delete(key) {
        const idx = asItemIndex(key);
        if (typeof idx !== 'number')
            return false;
        const del = this.items.splice(idx, 1);
        return del.length > 0;
    }
    get(key, keepScalar) {
        const idx = asItemIndex(key);
        if (typeof idx !== 'number')
            return undefined;
        const it = this.items[idx];
        return !keepScalar && isScalar(it) ? it.value : it;
    }
    /**
     * Checks if the collection includes a value with the key `key`.
     *
     * `key` must contain a representation of an integer for this to succeed.
     * It may be wrapped in a `Scalar`.
     */
    has(key) {
        const idx = asItemIndex(key);
        return typeof idx === 'number' && idx < this.items.length;
    }
    /**
     * Sets a value in this collection. For `!!set`, `value` needs to be a
     * boolean to add/remove the item from the set.
     *
     * If `key` does not contain a representation of an integer, this will throw.
     * It may be wrapped in a `Scalar`.
     */
    set(key, value) {
        const idx = asItemIndex(key);
        if (typeof idx !== 'number')
            throw new Error(`Expected a valid index, not ${key}.`);
        const prev = this.items[idx];
        if (isScalar(prev) && isScalarValue(value))
            prev.value = value;
        else
            this.items[idx] = value;
    }
    toJSON(_, ctx) {
        const seq = [];
        if (ctx?.onCreate)
            ctx.onCreate(seq);
        let i = 0;
        for (const item of this.items)
            seq.push(toJS(item, String(i++), ctx));
        return seq;
    }
    toString(ctx, onComment, onChompKeep) {
        if (!ctx)
            return JSON.stringify(this);
        return stringifyCollection(this, ctx, {
            blockItemPrefix: '- ',
            flowChars: { start: '[', end: ']' },
            itemIndent: (ctx.indent || '') + '  ',
            onChompKeep,
            onComment
        });
    }
    static from(schema, obj, ctx) {
        const { replacer } = ctx;
        const seq = new this(schema);
        if (obj && Symbol.iterator in Object(obj)) {
            let i = 0;
            for (let it of obj) {
                if (typeof replacer === 'function') {
                    const key = obj instanceof Set ? it : String(i++);
                    it = replacer.call(obj, key, it);
                }
                seq.items.push(createNode(it, undefined, ctx));
            }
        }
        return seq;
    }
}
function asItemIndex(key) {
    let idx = isScalar(key) ? key.value : key;
    if (idx && typeof idx === 'string')
        idx = Number(idx);
    return typeof idx === 'number' && Number.isInteger(idx) && idx >= 0
        ? idx
        : null;
}

const seq = {
    collection: 'seq',
    default: true,
    nodeClass: YAMLSeq,
    tag: 'tag:yaml.org,2002:seq',
    resolve(seq, onError) {
        if (!isSeq(seq))
            onError('Expected a sequence for this tag');
        return seq;
    },
    createNode: (schema, obj, ctx) => YAMLSeq.from(schema, obj, ctx)
};

const string = {
    identify: value => typeof value === 'string',
    default: true,
    tag: 'tag:yaml.org,2002:str',
    resolve: str => str,
    stringify(item, ctx, onComment, onChompKeep) {
        ctx = Object.assign({ actualString: true }, ctx);
        return stringifyString(item, ctx, onComment, onChompKeep);
    }
};

const nullTag = {
    identify: value => value == null,
    createNode: () => new Scalar(null),
    default: true,
    tag: 'tag:yaml.org,2002:null',
    test: /^(?:~|[Nn]ull|NULL)?$/,
    resolve: () => new Scalar(null),
    stringify: ({ source }, ctx) => typeof source === 'string' && nullTag.test.test(source)
        ? source
        : ctx.options.nullStr
};

const boolTag = {
    identify: value => typeof value === 'boolean',
    default: true,
    tag: 'tag:yaml.org,2002:bool',
    test: /^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,
    resolve: str => new Scalar(str[0] === 't' || str[0] === 'T'),
    stringify({ source, value }, ctx) {
        if (source && boolTag.test.test(source)) {
            const sv = source[0] === 't' || source[0] === 'T';
            if (value === sv)
                return source;
        }
        return value ? ctx.options.trueStr : ctx.options.falseStr;
    }
};

function stringifyNumber({ format, minFractionDigits, tag, value }) {
    if (typeof value === 'bigint')
        return String(value);
    const num = typeof value === 'number' ? value : Number(value);
    if (!isFinite(num))
        return isNaN(num) ? '.nan' : num < 0 ? '-.inf' : '.inf';
    let n = JSON.stringify(value);
    if (!format &&
        minFractionDigits &&
        (!tag || tag === 'tag:yaml.org,2002:float') &&
        /^\d/.test(n)) {
        let i = n.indexOf('.');
        if (i < 0) {
            i = n.length;
            n += '.';
        }
        let d = minFractionDigits - (n.length - i - 1);
        while (d-- > 0)
            n += '0';
    }
    return n;
}

const floatNaN$1 = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: str => str.slice(-3).toLowerCase() === 'nan'
        ? NaN
        : str[0] === '-'
            ? Number.NEGATIVE_INFINITY
            : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber
};
const floatExp$1 = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    format: 'EXP',
    test: /^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,
    resolve: str => parseFloat(str),
    stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber(node);
    }
};
const float$1 = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,
    resolve(str) {
        const node = new Scalar(parseFloat(str));
        const dot = str.indexOf('.');
        if (dot !== -1 && str[str.length - 1] === '0')
            node.minFractionDigits = str.length - dot - 1;
        return node;
    },
    stringify: stringifyNumber
};

const intIdentify$2 = (value) => typeof value === 'bigint' || Number.isInteger(value);
const intResolve$1 = (str, offset, radix, { intAsBigInt }) => (intAsBigInt ? BigInt(str) : parseInt(str.substring(offset), radix));
function intStringify$1(node, radix, prefix) {
    const { value } = node;
    if (intIdentify$2(value) && value >= 0)
        return prefix + value.toString(radix);
    return stringifyNumber(node);
}
const intOct$1 = {
    identify: value => intIdentify$2(value) && value >= 0,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'OCT',
    test: /^0o[0-7]+$/,
    resolve: (str, _onError, opt) => intResolve$1(str, 2, 8, opt),
    stringify: node => intStringify$1(node, 8, '0o')
};
const int$1 = {
    identify: intIdentify$2,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    test: /^[-+]?[0-9]+$/,
    resolve: (str, _onError, opt) => intResolve$1(str, 0, 10, opt),
    stringify: stringifyNumber
};
const intHex$1 = {
    identify: value => intIdentify$2(value) && value >= 0,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'HEX',
    test: /^0x[0-9a-fA-F]+$/,
    resolve: (str, _onError, opt) => intResolve$1(str, 2, 16, opt),
    stringify: node => intStringify$1(node, 16, '0x')
};

const schema$2 = [
    map,
    seq,
    string,
    nullTag,
    boolTag,
    intOct$1,
    int$1,
    intHex$1,
    floatNaN$1,
    floatExp$1,
    float$1
];

function intIdentify$1(value) {
    return typeof value === 'bigint' || Number.isInteger(value);
}
const stringifyJSON = ({ value }) => JSON.stringify(value);
const jsonScalars = [
    {
        identify: value => typeof value === 'string',
        default: true,
        tag: 'tag:yaml.org,2002:str',
        resolve: str => str,
        stringify: stringifyJSON
    },
    {
        identify: value => value == null,
        createNode: () => new Scalar(null),
        default: true,
        tag: 'tag:yaml.org,2002:null',
        test: /^null$/,
        resolve: () => null,
        stringify: stringifyJSON
    },
    {
        identify: value => typeof value === 'boolean',
        default: true,
        tag: 'tag:yaml.org,2002:bool',
        test: /^true$|^false$/,
        resolve: str => str === 'true',
        stringify: stringifyJSON
    },
    {
        identify: intIdentify$1,
        default: true,
        tag: 'tag:yaml.org,2002:int',
        test: /^-?(?:0|[1-9][0-9]*)$/,
        resolve: (str, _onError, { intAsBigInt }) => intAsBigInt ? BigInt(str) : parseInt(str, 10),
        stringify: ({ value }) => intIdentify$1(value) ? value.toString() : JSON.stringify(value)
    },
    {
        identify: value => typeof value === 'number',
        default: true,
        tag: 'tag:yaml.org,2002:float',
        test: /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,
        resolve: str => parseFloat(str),
        stringify: stringifyJSON
    }
];
const jsonError = {
    default: true,
    tag: '',
    test: /^/,
    resolve(str, onError) {
        onError(`Unresolved plain scalar ${JSON.stringify(str)}`);
        return str;
    }
};
const schema$1 = [map, seq].concat(jsonScalars, jsonError);

const binary = {
    identify: value => value instanceof Uint8Array, // Buffer inherits from Uint8Array
    default: false,
    tag: 'tag:yaml.org,2002:binary',
    /**
     * Returns a Buffer in node and an Uint8Array in browsers
     *
     * To use the resulting buffer as an image, you'll want to do something like:
     *
     *   const blob = new Blob([buffer], { type: 'image/jpeg' })
     *   document.querySelector('#photo').src = URL.createObjectURL(blob)
     */
    resolve(src, onError) {
        if (typeof atob === 'function') {
            // On IE 11, atob() can't handle newlines
            const str = atob(src.replace(/[\n\r]/g, ''));
            const buffer = new Uint8Array(str.length);
            for (let i = 0; i < str.length; ++i)
                buffer[i] = str.charCodeAt(i);
            return buffer;
        }
        else {
            onError('This environment does not support reading binary tags; either Buffer or atob is required');
            return src;
        }
    },
    stringify({ comment, type, value }, ctx, onComment, onChompKeep) {
        const buf = value; // checked earlier by binary.identify()
        let str;
        if (typeof btoa === 'function') {
            let s = '';
            for (let i = 0; i < buf.length; ++i)
                s += String.fromCharCode(buf[i]);
            str = btoa(s);
        }
        else {
            throw new Error('This environment does not support writing binary tags; either Buffer or btoa is required');
        }
        if (!type)
            type = Scalar.BLOCK_LITERAL;
        if (type !== Scalar.QUOTE_DOUBLE) {
            const lineWidth = Math.max(ctx.options.lineWidth - ctx.indent.length, ctx.options.minContentWidth);
            const n = Math.ceil(str.length / lineWidth);
            const lines = new Array(n);
            for (let i = 0, o = 0; i < n; ++i, o += lineWidth) {
                lines[i] = str.substr(o, lineWidth);
            }
            str = lines.join(type === Scalar.BLOCK_LITERAL ? '\n' : ' ');
        }
        return stringifyString({ comment, type, value: str }, ctx, onComment, onChompKeep);
    }
};

function resolvePairs(seq, onError) {
    if (isSeq(seq)) {
        for (let i = 0; i < seq.items.length; ++i) {
            let item = seq.items[i];
            if (isPair(item))
                continue;
            else if (isMap(item)) {
                if (item.items.length > 1)
                    onError('Each pair must have its own sequence indicator');
                const pair = item.items[0] || new Pair(new Scalar(null));
                if (item.commentBefore)
                    pair.key.commentBefore = pair.key.commentBefore
                        ? `${item.commentBefore}\n${pair.key.commentBefore}`
                        : item.commentBefore;
                if (item.comment) {
                    const cn = pair.value ?? pair.key;
                    cn.comment = cn.comment
                        ? `${item.comment}\n${cn.comment}`
                        : item.comment;
                }
                item = pair;
            }
            seq.items[i] = isPair(item) ? item : new Pair(item);
        }
    }
    else
        onError('Expected a sequence for this tag');
    return seq;
}
function createPairs(schema, iterable, ctx) {
    const { replacer } = ctx;
    const pairs = new YAMLSeq(schema);
    pairs.tag = 'tag:yaml.org,2002:pairs';
    let i = 0;
    if (iterable && Symbol.iterator in Object(iterable))
        for (let it of iterable) {
            if (typeof replacer === 'function')
                it = replacer.call(iterable, String(i++), it);
            let key, value;
            if (Array.isArray(it)) {
                if (it.length === 2) {
                    key = it[0];
                    value = it[1];
                }
                else
                    throw new TypeError(`Expected [key, value] tuple: ${it}`);
            }
            else if (it && it instanceof Object) {
                const keys = Object.keys(it);
                if (keys.length === 1) {
                    key = keys[0];
                    value = it[key];
                }
                else {
                    throw new TypeError(`Expected tuple with one key, not ${keys.length} keys`);
                }
            }
            else {
                key = it;
            }
            pairs.items.push(createPair(key, value, ctx));
        }
    return pairs;
}
const pairs = {
    collection: 'seq',
    default: false,
    tag: 'tag:yaml.org,2002:pairs',
    resolve: resolvePairs,
    createNode: createPairs
};

class YAMLOMap extends YAMLSeq {
    constructor() {
        super();
        this.add = YAMLMap.prototype.add.bind(this);
        this.delete = YAMLMap.prototype.delete.bind(this);
        this.get = YAMLMap.prototype.get.bind(this);
        this.has = YAMLMap.prototype.has.bind(this);
        this.set = YAMLMap.prototype.set.bind(this);
        this.tag = YAMLOMap.tag;
    }
    /**
     * If `ctx` is given, the return type is actually `Map<unknown, unknown>`,
     * but TypeScript won't allow widening the signature of a child method.
     */
    toJSON(_, ctx) {
        if (!ctx)
            return super.toJSON(_);
        const map = new Map();
        if (ctx?.onCreate)
            ctx.onCreate(map);
        for (const pair of this.items) {
            let key, value;
            if (isPair(pair)) {
                key = toJS(pair.key, '', ctx);
                value = toJS(pair.value, key, ctx);
            }
            else {
                key = toJS(pair, '', ctx);
            }
            if (map.has(key))
                throw new Error('Ordered maps must not include duplicate keys');
            map.set(key, value);
        }
        return map;
    }
    static from(schema, iterable, ctx) {
        const pairs = createPairs(schema, iterable, ctx);
        const omap = new this();
        omap.items = pairs.items;
        return omap;
    }
}
YAMLOMap.tag = 'tag:yaml.org,2002:omap';
const omap = {
    collection: 'seq',
    identify: value => value instanceof Map,
    nodeClass: YAMLOMap,
    default: false,
    tag: 'tag:yaml.org,2002:omap',
    resolve(seq, onError) {
        const pairs = resolvePairs(seq, onError);
        const seenKeys = [];
        for (const { key } of pairs.items) {
            if (isScalar(key)) {
                if (seenKeys.includes(key.value)) {
                    onError(`Ordered maps must not include duplicate keys: ${key.value}`);
                }
                else {
                    seenKeys.push(key.value);
                }
            }
        }
        return Object.assign(new YAMLOMap(), pairs);
    },
    createNode: (schema, iterable, ctx) => YAMLOMap.from(schema, iterable, ctx)
};

function boolStringify({ value, source }, ctx) {
    const boolObj = value ? trueTag : falseTag;
    if (source && boolObj.test.test(source))
        return source;
    return value ? ctx.options.trueStr : ctx.options.falseStr;
}
const trueTag = {
    identify: value => value === true,
    default: true,
    tag: 'tag:yaml.org,2002:bool',
    test: /^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,
    resolve: () => new Scalar(true),
    stringify: boolStringify
};
const falseTag = {
    identify: value => value === false,
    default: true,
    tag: 'tag:yaml.org,2002:bool',
    test: /^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,
    resolve: () => new Scalar(false),
    stringify: boolStringify
};

const floatNaN = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,
    resolve: (str) => str.slice(-3).toLowerCase() === 'nan'
        ? NaN
        : str[0] === '-'
            ? Number.NEGATIVE_INFINITY
            : Number.POSITIVE_INFINITY,
    stringify: stringifyNumber
};
const floatExp = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    format: 'EXP',
    test: /^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,
    resolve: (str) => parseFloat(str.replace(/_/g, '')),
    stringify(node) {
        const num = Number(node.value);
        return isFinite(num) ? num.toExponential() : stringifyNumber(node);
    }
};
const float = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    test: /^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,
    resolve(str) {
        const node = new Scalar(parseFloat(str.replace(/_/g, '')));
        const dot = str.indexOf('.');
        if (dot !== -1) {
            const f = str.substring(dot + 1).replace(/_/g, '');
            if (f[f.length - 1] === '0')
                node.minFractionDigits = f.length;
        }
        return node;
    },
    stringify: stringifyNumber
};

const intIdentify = (value) => typeof value === 'bigint' || Number.isInteger(value);
function intResolve(str, offset, radix, { intAsBigInt }) {
    const sign = str[0];
    if (sign === '-' || sign === '+')
        offset += 1;
    str = str.substring(offset).replace(/_/g, '');
    if (intAsBigInt) {
        switch (radix) {
            case 2:
                str = `0b${str}`;
                break;
            case 8:
                str = `0o${str}`;
                break;
            case 16:
                str = `0x${str}`;
                break;
        }
        const n = BigInt(str);
        return sign === '-' ? BigInt(-1) * n : n;
    }
    const n = parseInt(str, radix);
    return sign === '-' ? -1 * n : n;
}
function intStringify(node, radix, prefix) {
    const { value } = node;
    if (intIdentify(value)) {
        const str = value.toString(radix);
        return value < 0 ? '-' + prefix + str.substr(1) : prefix + str;
    }
    return stringifyNumber(node);
}
const intBin = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'BIN',
    test: /^[-+]?0b[0-1_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 2, opt),
    stringify: node => intStringify(node, 2, '0b')
};
const intOct = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'OCT',
    test: /^[-+]?0[0-7_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 1, 8, opt),
    stringify: node => intStringify(node, 8, '0')
};
const int = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    test: /^[-+]?[0-9][0-9_]*$/,
    resolve: (str, _onError, opt) => intResolve(str, 0, 10, opt),
    stringify: stringifyNumber
};
const intHex = {
    identify: intIdentify,
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'HEX',
    test: /^[-+]?0x[0-9a-fA-F_]+$/,
    resolve: (str, _onError, opt) => intResolve(str, 2, 16, opt),
    stringify: node => intStringify(node, 16, '0x')
};

class YAMLSet extends YAMLMap {
    constructor(schema) {
        super(schema);
        this.tag = YAMLSet.tag;
    }
    add(key) {
        let pair;
        if (isPair(key))
            pair = key;
        else if (key &&
            typeof key === 'object' &&
            'key' in key &&
            'value' in key &&
            key.value === null)
            pair = new Pair(key.key, null);
        else
            pair = new Pair(key, null);
        const prev = findPair(this.items, pair.key);
        if (!prev)
            this.items.push(pair);
    }
    /**
     * If `keepPair` is `true`, returns the Pair matching `key`.
     * Otherwise, returns the value of that Pair's key.
     */
    get(key, keepPair) {
        const pair = findPair(this.items, key);
        return !keepPair && isPair(pair)
            ? isScalar(pair.key)
                ? pair.key.value
                : pair.key
            : pair;
    }
    set(key, value) {
        if (typeof value !== 'boolean')
            throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof value}`);
        const prev = findPair(this.items, key);
        if (prev && !value) {
            this.items.splice(this.items.indexOf(prev), 1);
        }
        else if (!prev && value) {
            this.items.push(new Pair(key));
        }
    }
    toJSON(_, ctx) {
        return super.toJSON(_, ctx, Set);
    }
    toString(ctx, onComment, onChompKeep) {
        if (!ctx)
            return JSON.stringify(this);
        if (this.hasAllNullValues(true))
            return super.toString(Object.assign({}, ctx, { allNullValues: true }), onComment, onChompKeep);
        else
            throw new Error('Set items must all have null values');
    }
    static from(schema, iterable, ctx) {
        const { replacer } = ctx;
        const set = new this(schema);
        if (iterable && Symbol.iterator in Object(iterable))
            for (let value of iterable) {
                if (typeof replacer === 'function')
                    value = replacer.call(iterable, value, value);
                set.items.push(createPair(value, null, ctx));
            }
        return set;
    }
}
YAMLSet.tag = 'tag:yaml.org,2002:set';
const set = {
    collection: 'map',
    identify: value => value instanceof Set,
    nodeClass: YAMLSet,
    default: false,
    tag: 'tag:yaml.org,2002:set',
    createNode: (schema, iterable, ctx) => YAMLSet.from(schema, iterable, ctx),
    resolve(map, onError) {
        if (isMap(map)) {
            if (map.hasAllNullValues(true))
                return Object.assign(new YAMLSet(), map);
            else
                onError('Set items must all have null values');
        }
        else
            onError('Expected a mapping for this tag');
        return map;
    }
};

/** Internal types handle bigint as number, because TS can't figure it out. */
function parseSexagesimal(str, asBigInt) {
    const sign = str[0];
    const parts = sign === '-' || sign === '+' ? str.substring(1) : str;
    const num = (n) => asBigInt ? BigInt(n) : Number(n);
    const res = parts
        .replace(/_/g, '')
        .split(':')
        .reduce((res, p) => res * num(60) + num(p), num(0));
    return (sign === '-' ? num(-1) * res : res);
}
/**
 * hhhh:mm:ss.sss
 *
 * Internal types handle bigint as number, because TS can't figure it out.
 */
function stringifySexagesimal(node) {
    let { value } = node;
    let num = (n) => n;
    if (typeof value === 'bigint')
        num = n => BigInt(n);
    else if (isNaN(value) || !isFinite(value))
        return stringifyNumber(node);
    let sign = '';
    if (value < 0) {
        sign = '-';
        value *= num(-1);
    }
    const _60 = num(60);
    const parts = [value % _60]; // seconds, including ms
    if (value < 60) {
        parts.unshift(0); // at least one : is required
    }
    else {
        value = (value - parts[0]) / _60;
        parts.unshift(value % _60); // minutes
        if (value >= 60) {
            value = (value - parts[0]) / _60;
            parts.unshift(value); // hours
        }
    }
    return (sign +
        parts
            .map(n => String(n).padStart(2, '0'))
            .join(':')
            .replace(/000000\d*$/, '') // % 60 may introduce error
    );
}
const intTime = {
    identify: value => typeof value === 'bigint' || Number.isInteger(value),
    default: true,
    tag: 'tag:yaml.org,2002:int',
    format: 'TIME',
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,
    resolve: (str, _onError, { intAsBigInt }) => parseSexagesimal(str, intAsBigInt),
    stringify: stringifySexagesimal
};
const floatTime = {
    identify: value => typeof value === 'number',
    default: true,
    tag: 'tag:yaml.org,2002:float',
    format: 'TIME',
    test: /^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,
    resolve: str => parseSexagesimal(str, false),
    stringify: stringifySexagesimal
};
const timestamp = {
    identify: value => value instanceof Date,
    default: true,
    tag: 'tag:yaml.org,2002:timestamp',
    // If the time zone is omitted, the timestamp is assumed to be specified in UTC. The time part
    // may be omitted altogether, resulting in a date format. In such a case, the time part is
    // assumed to be 00:00:00Z (start of day, UTC).
    test: RegExp('^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})' + // YYYY-Mm-Dd
        '(?:' + // time is optional
        '(?:t|T|[ \\t]+)' + // t | T | whitespace
        '([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)' + // Hh:Mm:Ss(.ss)?
        '(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?' + // Z | +5 | -03:30
        ')?$'),
    resolve(str) {
        const match = str.match(timestamp.test);
        if (!match)
            throw new Error('!!timestamp expects a date, starting with yyyy-mm-dd');
        const [, year, month, day, hour, minute, second] = match.map(Number);
        const millisec = match[7] ? Number((match[7] + '00').substr(1, 3)) : 0;
        let date = Date.UTC(year, month - 1, day, hour || 0, minute || 0, second || 0, millisec);
        const tz = match[8];
        if (tz && tz !== 'Z') {
            let d = parseSexagesimal(tz, false);
            if (Math.abs(d) < 30)
                d *= 60;
            date -= 60000 * d;
        }
        return new Date(date);
    },
    stringify: ({ value }) => value.toISOString().replace(/(T00:00:00)?\.000Z$/, '')
};

const schema = [
    map,
    seq,
    string,
    nullTag,
    trueTag,
    falseTag,
    intBin,
    intOct,
    int,
    intHex,
    floatNaN,
    floatExp,
    float,
    binary,
    merge,
    omap,
    pairs,
    set,
    intTime,
    floatTime,
    timestamp
];

const schemas = new Map([
    ['core', schema$2],
    ['failsafe', [map, seq, string]],
    ['json', schema$1],
    ['yaml11', schema],
    ['yaml-1.1', schema]
]);
const tagsByName = {
    binary,
    bool: boolTag,
    float: float$1,
    floatExp: floatExp$1,
    floatNaN: floatNaN$1,
    floatTime,
    int: int$1,
    intHex: intHex$1,
    intOct: intOct$1,
    intTime,
    map,
    merge,
    null: nullTag,
    omap,
    pairs,
    seq,
    set,
    timestamp
};
const coreKnownTags = {
    'tag:yaml.org,2002:binary': binary,
    'tag:yaml.org,2002:merge': merge,
    'tag:yaml.org,2002:omap': omap,
    'tag:yaml.org,2002:pairs': pairs,
    'tag:yaml.org,2002:set': set,
    'tag:yaml.org,2002:timestamp': timestamp
};
function getTags(customTags, schemaName, addMergeTag) {
    const schemaTags = schemas.get(schemaName);
    if (schemaTags && !customTags) {
        return addMergeTag && !schemaTags.includes(merge)
            ? schemaTags.concat(merge)
            : schemaTags.slice();
    }
    let tags = schemaTags;
    if (!tags) {
        if (Array.isArray(customTags))
            tags = [];
        else {
            const keys = Array.from(schemas.keys())
                .filter(key => key !== 'yaml11')
                .map(key => JSON.stringify(key))
                .join(', ');
            throw new Error(`Unknown schema "${schemaName}"; use one of ${keys} or define customTags array`);
        }
    }
    if (Array.isArray(customTags)) {
        for (const tag of customTags)
            tags = tags.concat(tag);
    }
    else if (typeof customTags === 'function') {
        tags = customTags(tags.slice());
    }
    if (addMergeTag)
        tags = tags.concat(merge);
    return tags.reduce((tags, tag) => {
        const tagObj = typeof tag === 'string' ? tagsByName[tag] : tag;
        if (!tagObj) {
            const tagName = JSON.stringify(tag);
            const keys = Object.keys(tagsByName)
                .map(key => JSON.stringify(key))
                .join(', ');
            throw new Error(`Unknown custom tag ${tagName}; use one of ${keys}`);
        }
        if (!tags.includes(tagObj))
            tags.push(tagObj);
        return tags;
    }, []);
}

const sortMapEntriesByKey = (a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0;
class Schema {
    constructor({ compat, customTags, merge, resolveKnownTags, schema, sortMapEntries, toStringDefaults }) {
        this.compat = Array.isArray(compat)
            ? getTags(compat, 'compat')
            : compat
                ? getTags(null, compat)
                : null;
        this.name = (typeof schema === 'string' && schema) || 'core';
        this.knownTags = resolveKnownTags ? coreKnownTags : {};
        this.tags = getTags(customTags, this.name, merge);
        this.toStringOptions = toStringDefaults ?? null;
        Object.defineProperty(this, MAP, { value: map });
        Object.defineProperty(this, SCALAR, { value: string });
        Object.defineProperty(this, SEQ, { value: seq });
        // Used by createMap()
        this.sortMapEntries =
            typeof sortMapEntries === 'function'
                ? sortMapEntries
                : sortMapEntries === true
                    ? sortMapEntriesByKey
                    : null;
    }
    clone() {
        const copy = Object.create(Schema.prototype, Object.getOwnPropertyDescriptors(this));
        copy.tags = this.tags.slice();
        return copy;
    }
}

function stringifyDocument(doc, options) {
    const lines = [];
    let hasDirectives = options.directives === true;
    if (options.directives !== false && doc.directives) {
        const dir = doc.directives.toString(doc);
        if (dir) {
            lines.push(dir);
            hasDirectives = true;
        }
        else if (doc.directives.docStart)
            hasDirectives = true;
    }
    if (hasDirectives)
        lines.push('---');
    const ctx = createStringifyContext(doc, options);
    const { commentString } = ctx.options;
    if (doc.commentBefore) {
        if (lines.length !== 1)
            lines.unshift('');
        const cs = commentString(doc.commentBefore);
        lines.unshift(indentComment(cs, ''));
    }
    let chompKeep = false;
    let contentComment = null;
    if (doc.contents) {
        if (isNode(doc.contents)) {
            if (doc.contents.spaceBefore && hasDirectives)
                lines.push('');
            if (doc.contents.commentBefore) {
                const cs = commentString(doc.contents.commentBefore);
                lines.push(indentComment(cs, ''));
            }
            // top-level block scalars need to be indented if followed by a comment
            ctx.forceBlockIndent = !!doc.comment;
            contentComment = doc.contents.comment;
        }
        const onChompKeep = contentComment ? undefined : () => (chompKeep = true);
        let body = stringify$1(doc.contents, ctx, () => (contentComment = null), onChompKeep);
        if (contentComment)
            body += lineComment(body, '', commentString(contentComment));
        if ((body[0] === '|' || body[0] === '>') &&
            lines[lines.length - 1] === '---') {
            // Top-level block scalars with a preceding doc marker ought to use the
            // same line for their header.
            lines[lines.length - 1] = `--- ${body}`;
        }
        else
            lines.push(body);
    }
    else {
        lines.push(stringify$1(doc.contents, ctx));
    }
    if (doc.directives?.docEnd) {
        if (doc.comment) {
            const cs = commentString(doc.comment);
            if (cs.includes('\n')) {
                lines.push('...');
                lines.push(indentComment(cs, ''));
            }
            else {
                lines.push(`... ${cs}`);
            }
        }
        else {
            lines.push('...');
        }
    }
    else {
        let dc = doc.comment;
        if (dc && chompKeep)
            dc = dc.replace(/^\n+/, '');
        if (dc) {
            if ((!chompKeep || contentComment) && lines[lines.length - 1] !== '')
                lines.push('');
            lines.push(indentComment(commentString(dc), ''));
        }
    }
    return lines.join('\n') + '\n';
}

class Document {
    constructor(value, replacer, options) {
        /** A comment before this Document */
        this.commentBefore = null;
        /** A comment immediately after this Document */
        this.comment = null;
        /** Errors encountered during parsing. */
        this.errors = [];
        /** Warnings encountered during parsing. */
        this.warnings = [];
        Object.defineProperty(this, NODE_TYPE, { value: DOC });
        let _replacer = null;
        if (typeof replacer === 'function' || Array.isArray(replacer)) {
            _replacer = replacer;
        }
        else if (options === undefined && replacer) {
            options = replacer;
            replacer = undefined;
        }
        const opt = Object.assign({
            intAsBigInt: false,
            keepSourceTokens: false,
            logLevel: 'warn',
            prettyErrors: true,
            strict: true,
            stringKeys: false,
            uniqueKeys: true,
            version: '1.2'
        }, options);
        this.options = opt;
        let { version } = opt;
        if (options?._directives) {
            this.directives = options._directives.atDocument();
            if (this.directives.yaml.explicit)
                version = this.directives.yaml.version;
        }
        else
            this.directives = new Directives({ version });
        this.setSchema(version, options);
        // @ts-expect-error We can't really know that this matches Contents.
        this.contents =
            value === undefined ? null : this.createNode(value, _replacer, options);
    }
    /**
     * Create a deep copy of this Document and its contents.
     *
     * Custom Node values that inherit from `Object` still refer to their original instances.
     */
    clone() {
        const copy = Object.create(Document.prototype, {
            [NODE_TYPE]: { value: DOC }
        });
        copy.commentBefore = this.commentBefore;
        copy.comment = this.comment;
        copy.errors = this.errors.slice();
        copy.warnings = this.warnings.slice();
        copy.options = Object.assign({}, this.options);
        if (this.directives)
            copy.directives = this.directives.clone();
        copy.schema = this.schema.clone();
        // @ts-expect-error We can't really know that this matches Contents.
        copy.contents = isNode(this.contents)
            ? this.contents.clone(copy.schema)
            : this.contents;
        if (this.range)
            copy.range = this.range.slice();
        return copy;
    }
    /** Adds a value to the document. */
    add(value) {
        if (assertCollection(this.contents))
            this.contents.add(value);
    }
    /** Adds a value to the document. */
    addIn(path, value) {
        if (assertCollection(this.contents))
            this.contents.addIn(path, value);
    }
    /**
     * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
     *
     * If `node` already has an anchor, `name` is ignored.
     * Otherwise, the `node.anchor` value will be set to `name`,
     * or if an anchor with that name is already present in the document,
     * `name` will be used as a prefix for a new unique anchor.
     * If `name` is undefined, the generated anchor will use 'a' as a prefix.
     */
    createAlias(node, name) {
        if (!node.anchor) {
            const prev = anchorNames(this);
            node.anchor =
                // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
                !name || prev.has(name) ? findNewAnchor(name || 'a', prev) : name;
        }
        return new Alias(node.anchor);
    }
    createNode(value, replacer, options) {
        let _replacer = undefined;
        if (typeof replacer === 'function') {
            value = replacer.call({ '': value }, '', value);
            _replacer = replacer;
        }
        else if (Array.isArray(replacer)) {
            const keyToStr = (v) => typeof v === 'number' || v instanceof String || v instanceof Number;
            const asStr = replacer.filter(keyToStr).map(String);
            if (asStr.length > 0)
                replacer = replacer.concat(asStr);
            _replacer = replacer;
        }
        else if (options === undefined && replacer) {
            options = replacer;
            replacer = undefined;
        }
        const { aliasDuplicateObjects, anchorPrefix, flow, keepUndefined, onTagObj, tag } = options ?? {};
        const { onAnchor, setAnchors, sourceObjects } = createNodeAnchors(this, 
        // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing
        anchorPrefix || 'a');
        const ctx = {
            aliasDuplicateObjects: aliasDuplicateObjects ?? true,
            keepUndefined: keepUndefined ?? false,
            onAnchor,
            onTagObj,
            replacer: _replacer,
            schema: this.schema,
            sourceObjects
        };
        const node = createNode(value, tag, ctx);
        if (flow && isCollection(node))
            node.flow = true;
        setAnchors();
        return node;
    }
    /**
     * Convert a key and a value into a `Pair` using the current schema,
     * recursively wrapping all values as `Scalar` or `Collection` nodes.
     */
    createPair(key, value, options = {}) {
        const k = this.createNode(key, null, options);
        const v = this.createNode(value, null, options);
        return new Pair(k, v);
    }
    /**
     * Removes a value from the document.
     * @returns `true` if the item was found and removed.
     */
    delete(key) {
        return assertCollection(this.contents) ? this.contents.delete(key) : false;
    }
    /**
     * Removes a value from the document.
     * @returns `true` if the item was found and removed.
     */
    deleteIn(path) {
        if (isEmptyPath(path)) {
            if (this.contents == null)
                return false;
            // @ts-expect-error Presumed impossible if Strict extends false
            this.contents = null;
            return true;
        }
        return assertCollection(this.contents)
            ? this.contents.deleteIn(path)
            : false;
    }
    /**
     * Returns item at `key`, or `undefined` if not found. By default unwraps
     * scalar values from their surrounding node; to disable set `keepScalar` to
     * `true` (collections are always returned intact).
     */
    get(key, keepScalar) {
        return isCollection(this.contents)
            ? this.contents.get(key, keepScalar)
            : undefined;
    }
    /**
     * Returns item at `path`, or `undefined` if not found. By default unwraps
     * scalar values from their surrounding node; to disable set `keepScalar` to
     * `true` (collections are always returned intact).
     */
    getIn(path, keepScalar) {
        if (isEmptyPath(path))
            return !keepScalar && isScalar(this.contents)
                ? this.contents.value
                : this.contents;
        return isCollection(this.contents)
            ? this.contents.getIn(path, keepScalar)
            : undefined;
    }
    /**
     * Checks if the document includes a value with the key `key`.
     */
    has(key) {
        return isCollection(this.contents) ? this.contents.has(key) : false;
    }
    /**
     * Checks if the document includes a value at `path`.
     */
    hasIn(path) {
        if (isEmptyPath(path))
            return this.contents !== undefined;
        return isCollection(this.contents) ? this.contents.hasIn(path) : false;
    }
    /**
     * Sets a value in this document. For `!!set`, `value` needs to be a
     * boolean to add/remove the item from the set.
     */
    set(key, value) {
        if (this.contents == null) {
            // @ts-expect-error We can't really know that this matches Contents.
            this.contents = collectionFromPath(this.schema, [key], value);
        }
        else if (assertCollection(this.contents)) {
            this.contents.set(key, value);
        }
    }
    /**
     * Sets a value in this document. For `!!set`, `value` needs to be a
     * boolean to add/remove the item from the set.
     */
    setIn(path, value) {
        if (isEmptyPath(path)) {
            // @ts-expect-error We can't really know that this matches Contents.
            this.contents = value;
        }
        else if (this.contents == null) {
            // @ts-expect-error We can't really know that this matches Contents.
            this.contents = collectionFromPath(this.schema, Array.from(path), value);
        }
        else if (assertCollection(this.contents)) {
            this.contents.setIn(path, value);
        }
    }
    /**
     * Change the YAML version and schema used by the document.
     * A `null` version disables support for directives, explicit tags, anchors, and aliases.
     * It also requires the `schema` option to be given as a `Schema` instance value.
     *
     * Overrides all previously set schema options.
     */
    setSchema(version, options = {}) {
        if (typeof version === 'number')
            version = String(version);
        let opt;
        switch (version) {
            case '1.1':
                if (this.directives)
                    this.directives.yaml.version = '1.1';
                else
                    this.directives = new Directives({ version: '1.1' });
                opt = { resolveKnownTags: false, schema: 'yaml-1.1' };
                break;
            case '1.2':
            case 'next':
                if (this.directives)
                    this.directives.yaml.version = version;
                else
                    this.directives = new Directives({ version });
                opt = { resolveKnownTags: true, schema: 'core' };
                break;
            case null:
                if (this.directives)
                    delete this.directives;
                opt = null;
                break;
            default: {
                const sv = JSON.stringify(version);
                throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${sv}`);
            }
        }
        // Not using `instanceof Schema` to allow for duck typing
        if (options.schema instanceof Object)
            this.schema = options.schema;
        else if (opt)
            this.schema = new Schema(Object.assign(opt, options));
        else
            throw new Error(`With a null YAML version, the { schema: Schema } option is required`);
    }
    // json & jsonArg are only used from toJSON()
    toJS({ json, jsonArg, mapAsMap, maxAliasCount, onAnchor, reviver } = {}) {
        const ctx = {
            anchors: new Map(),
            doc: this,
            keep: !json,
            mapAsMap: mapAsMap === true,
            mapKeyWarned: false,
            maxAliasCount: typeof maxAliasCount === 'number' ? maxAliasCount : 100
        };
        const res = toJS(this.contents, jsonArg ?? '', ctx);
        if (typeof onAnchor === 'function')
            for (const { count, res } of ctx.anchors.values())
                onAnchor(res, count);
        return typeof reviver === 'function'
            ? applyReviver(reviver, { '': res }, '', res)
            : res;
    }
    /**
     * A JSON representation of the document `contents`.
     *
     * @param jsonArg Used by `JSON.stringify` to indicate the array index or
     *   property name.
     */
    toJSON(jsonArg, onAnchor) {
        return this.toJS({ json: true, jsonArg, mapAsMap: false, onAnchor });
    }
    /** A YAML representation of the document. */
    toString(options = {}) {
        if (this.errors.length > 0)
            throw new Error('Document with errors cannot be stringified');
        if ('indent' in options &&
            (!Number.isInteger(options.indent) || Number(options.indent) <= 0)) {
            const s = JSON.stringify(options.indent);
            throw new Error(`"indent" option must be a positive integer, not ${s}`);
        }
        return stringifyDocument(this, options);
    }
}
function assertCollection(contents) {
    if (isCollection(contents))
        return true;
    throw new Error('Expected a YAML collection as document contents');
}

new Set('0123456789ABCDEFabcdef');
new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()");
new Set(',[]{}');
new Set(' ,[]{}\n\r\t');

function stringify(value, replacer, options) {
    let _replacer = null;
    if (typeof replacer === 'function' || Array.isArray(replacer)) {
        _replacer = replacer;
    }
    else if (options === undefined && replacer) {
        options = replacer;
    }
    if (typeof options === 'string')
        options = options.length;
    if (typeof options === 'number') {
        const indent = Math.round(options);
        options = indent < 1 ? undefined : indent > 8 ? { indent: 8 } : { indent };
    }
    if (value === undefined) {
        const { keepUndefined } = options ?? replacer ?? {};
        if (!keepUndefined)
            return undefined;
    }
    if (isDocument(value) && !_replacer)
        return value.toString(options);
    return new Document(value, _replacer, options).toString(options);
}

function getOpenAPI3StatusCodes(program, statusCodes, response) {
    if (isDefaultResponse(program, response) || statusCodes === "*") {
        return [["default"], []];
    }
    else if (typeof statusCodes === "number") {
        return [[String(statusCodes)], []];
    }
    else {
        return rangeToOpenAPI(statusCodes, response);
    }
}
function rangeToOpenAPI(range, diagnosticTarget) {
    const diagnostics = [];
    const reportInvalid = () => diagnostics.push(createDiagnostic({
        code: "unsupported-status-code-range",
        format: { start: String(range.start), end: String(range.end) },
        target: diagnosticTarget,
    }));
    const codes = [];
    let start = range.start;
    let end = range.end;
    if (range.start < 100) {
        reportInvalid();
        start = 100;
        codes.push("default");
    }
    else if (range.end > 599) {
        reportInvalid();
        codes.push("default");
        end = 599;
    }
    const groups = [1, 2, 3, 4, 5];
    for (const group of groups) {
        if (start > end) {
            break;
        }
        const groupStart = group * 100;
        const groupEnd = groupStart + 99;
        if (start >= groupStart && start <= groupEnd) {
            codes.push(`${group}XX`);
            if (start !== groupStart || end < groupEnd) {
                reportInvalid();
            }
            start = groupStart + 100;
        }
    }
    return [codes, diagnostics];
}

/**
 * Checks if two objects are deeply equal.
 *
 * Does not support cycles. Intended to be used only on plain data that can
 * be directly represented in JSON.
 */
function deepEquals(left, right) {
    if (left === right) {
        return true;
    }
    if (left === null || right === null || typeof left !== "object" || typeof right !== "object") {
        return false;
    }
    if (Array.isArray(left)) {
        return Array.isArray(right) ? arrayEquals(left, right, deepEquals) : false;
    }
    return mapEquals(new Map(Object.entries(left)), new Map(Object.entries(right)), deepEquals);
}
/**
 * Check if two arrays have the same elements.
 *
 * @param equals Optional callback for element equality comparison.
 *               Default is to compare by identity using `===`.
 */
function arrayEquals(left, right, equals = (x, y) => x === y) {
    if (left === right) {
        return true;
    }
    if (left.length !== right.length) {
        return false;
    }
    for (let i = 0; i < left.length; i++) {
        if (!equals(left[i], right[i])) {
            return false;
        }
    }
    return true;
}
/**
 * Check if two maps have the same entries.
 *
 * @param equals Optional callback for value equality comparison.
 *               Default is to compare by identity using `===`.
 */
function mapEquals(left, right, equals = (x, y) => x === y) {
    if (left === right) {
        return true;
    }
    if (left.size !== right.size) {
        return false;
    }
    for (const [key, value] of left) {
        if (!right.has(key) || !equals(value, right.get(key))) {
            return false;
        }
    }
    return true;
}
function isSharedHttpOperation(operation) {
    return operation.kind === "shared";
}
function isStdType(program, type) {
    return program.checker.isStdType(type);
}
function isLiteralType(type) {
    return type.kind === "Boolean" || type.kind === "String" || type.kind === "Number";
}
function literalType(type) {
    switch (type.kind) {
        case "String":
            return "string";
        case "Number":
            return "number";
        case "Boolean":
            return "boolean";
    }
}
function includeDerivedModel(model) {
    return (!isTemplateDeclaration(model) &&
        (model.templateMapper?.args === undefined ||
            model.templateMapper.args?.length === 0 ||
            model.derivedModels.length > 0));
}
function isScalarExtendsBytes(type) {
    if (type.kind !== "Scalar") {
        return false;
    }
    let current = type;
    while (current) {
        if (current.name === "bytes") {
            return true;
        }
        current = current.baseScalar;
    }
    return false;
}
function getDefaultValue(program, defaultType, modelProperty) {
    return serializeValueAsJson(program, defaultType, modelProperty);
}
function isBytesKeptRaw(program, type) {
    return type.kind === "Scalar" && type.name === "bytes" && getEncode(program, type) === undefined;
}

function resolveOperationExamples(program, operation) {
    const examples = findOperationExamples(program, operation);
    const result = { requestBody: {}, responses: {} };
    if (examples.length === 0) {
        return result;
    }
    for (const [op, example] of examples) {
        if (example.parameters && op.parameters.body) {
            const contentTypeValue = getContentTypeValue(example.parameters, op.parameters.properties) ?? "application/json";
            result.requestBody[contentTypeValue] ??= [];
            const value = getBodyValue(example.parameters, op.parameters.properties);
            if (value) {
                result.requestBody[contentTypeValue].push([
                    {
                        value,
                        title: example.title,
                        description: example.description,
                    },
                    op.parameters.body.type,
                ]);
            }
        }
        if (example.returnType && op.responses) {
            const match = findResponseForExample(program, example.returnType, op.responses);
            if (match) {
                const value = getBodyValue(example.returnType, match.response.properties);
                if (value) {
                    for (const statusCode of match.statusCodes) {
                        result.responses[statusCode] ??= {};
                        result.responses[statusCode][match.contentType] ??= [];
                        result.responses[statusCode][match.contentType].push([
                            {
                                value,
                                title: example.title,
                                description: example.description,
                            },
                            match.response.body.type,
                        ]);
                    }
                }
            }
        }
    }
    return result;
}
function findOperationExamples(program, operation) {
    if (isSharedHttpOperation(operation)) {
        return operation.operations.flatMap((op) => getOpExamples(program, op.operation).map((x) => [op, x]));
    }
    else {
        return getOpExamples(program, operation.operation).map((x) => [operation, x]);
    }
}
function isStatusCodeIn(exampleStatusCode, statusCodes) {
    if (statusCodes === "*") {
        return true;
    }
    if (typeof statusCodes === "number") {
        return exampleStatusCode === statusCodes;
    }
    return exampleStatusCode >= statusCodes.start && exampleStatusCode <= statusCodes.end;
}
function findResponseForExample(program, exampleValue, responses) {
    const tentatives = [];
    for (const statusCodeResponse of responses) {
        for (const response of statusCodeResponse.responses) {
            if (response.body === undefined) {
                continue;
            }
            const contentType = getContentTypeValue(exampleValue, response.properties);
            const statusCode = getStatusCodeValue(exampleValue, response.properties);
            const contentTypeProp = response.properties.find((x) => x.kind === "contentType"); // if undefined MUST be application/json
            const statusCodeProp = response.properties.find((x) => x.kind === "statusCode"); // if undefined MUST be 200
            const statusCodeMatch = statusCode && statusCodeProp && isStatusCodeIn(statusCode, statusCodeResponse.statusCodes);
            const contentTypeMatch = contentType && response.body?.contentTypes.includes(contentType);
            if (statusCodeMatch && contentTypeMatch) {
                return {
                    contentType,
                    statusCodes: ignoreDiagnostics(getOpenAPI3StatusCodes(program, statusCodeResponse.statusCodes, statusCodeResponse.type)),
                    response,
                };
            }
            else if (statusCodeMatch && contentTypeProp === undefined) {
                tentatives.push([
                    {
                        response,
                        statusCodes: ignoreDiagnostics(getOpenAPI3StatusCodes(program, statusCodeResponse.statusCodes, statusCodeResponse.type)),
                    },
                    1,
                ]);
            }
            else if (contentTypeMatch && statusCodeMatch === undefined) {
                tentatives.push([{ response, contentType }, 1]);
            }
            else if (contentTypeProp === undefined && statusCodeProp === undefined) {
                tentatives.push([{ response }, 0]);
            }
        }
    }
    const tentative = tentatives.sort((a, b) => a[1] - b[1]).pop();
    if (tentative) {
        return {
            contentType: tentative[0].contentType ?? "application/json",
            statusCodes: tentative[0].statusCodes ?? ["200"],
            response: tentative[0].response,
        };
    }
    return undefined;
}
function getExampleOrExamples(program, examples) {
    if (examples.length === 0) {
        return {};
    }
    if (examples.length === 1 &&
        examples[0][0].title === undefined &&
        examples[0][0].description === undefined) {
        const [example, type] = examples[0];
        return { example: serializeValueAsJson(program, example.value, type) };
    }
    else {
        const exampleObj = {};
        for (const [index, [example, type]] of examples.entries()) {
            exampleObj[example.title ?? `example${index}`] = {
                summary: example.title,
                description: example.description,
                value: serializeValueAsJson(program, example.value, type),
            };
        }
        return { examples: exampleObj };
    }
}
function getStatusCodeValue(value, properties) {
    const statusCodeProperty = properties.find((p) => p.kind === "statusCode");
    if (statusCodeProperty === undefined) {
        return undefined;
    }
    const statusCode = getValueByPath(value, statusCodeProperty.path);
    if (statusCode?.valueKind === "NumericValue") {
        return statusCode.value.asNumber() ?? undefined;
    }
    return undefined;
}
function getContentTypeValue(value, properties) {
    const contentTypeProperty = properties.find((p) => p.kind === "contentType");
    if (contentTypeProperty === undefined) {
        return undefined;
    }
    const statusCode = getValueByPath(value, contentTypeProperty.path);
    if (statusCode?.valueKind === "StringValue") {
        return statusCode.value;
    }
    return undefined;
}
function getBodyValue(value, properties) {
    const bodyProperty = properties.find((p) => p.kind === "body" || p.kind === "bodyRoot");
    if (bodyProperty !== undefined) {
        return getValueByPath(value, bodyProperty.path);
    }
    return value;
}
function getValueByPath(value, path) {
    let current = value;
    for (const key of path) {
        switch (current?.valueKind) {
            case "ObjectValue":
                current = current.properties.get(key.toString())?.value;
                break;
            case "ArrayValue":
                current = current.values[key];
                break;
            default:
                return undefined;
        }
    }
    return current;
}

async function resolveJsonSchemaModule() {
    try {
        return await import('@typespec/json-schema');
    }
    catch {
        return undefined;
    }
}

function getSchemaForStdScalars(scalar, options) {
    switch (scalar.name) {
        case "bytes":
            return { type: "string", format: "byte" };
        case "numeric":
            return { type: "number" };
        case "integer":
            return { type: "integer" };
        case "int8":
            return { type: "integer", format: "int8" };
        case "int16":
            return { type: "integer", format: "int16" };
        case "int32":
            return { type: "integer", format: "int32" };
        case "int64":
            return { type: "integer", format: "int64" };
        case "safeint":
            switch (options.safeintStrategy) {
                case "double-int":
                    return { type: "integer", format: "double-int" };
                case "int64":
                default:
                    return { type: "integer", format: "int64" };
            }
        case "uint8":
            return { type: "integer", format: "uint8" };
        case "uint16":
            return { type: "integer", format: "uint16" };
        case "uint32":
            return { type: "integer", format: "uint32" };
        case "uint64":
            return { type: "integer", format: "uint64" };
        case "float":
            return { type: "number" };
        case "float64":
            return { type: "number", format: "double" };
        case "float32":
            return { type: "number", format: "float" };
        case "decimal":
            return { type: "number", format: "decimal" };
        case "decimal128":
            return { type: "number", format: "decimal128" };
        case "string":
            return { type: "string" };
        case "boolean":
            return { type: "boolean" };
        case "plainDate":
            return { type: "string", format: "date" };
        case "utcDateTime":
        case "offsetDateTime":
            return { type: "string", format: "date-time" };
        case "plainTime":
            return { type: "string", format: "time" };
        case "duration":
            return { type: "string", format: "duration" };
        case "url":
            return { type: "string", format: "uri" };
        default:
            scalar.name;
            return {};
    }
}

function applyEncoding$2(program, typespecType, target, getEncodedFieldName, options) {
    const encodeData = getEncode(program, typespecType);
    if (encodeData) {
        const newTarget = new ObjectBuilder(target);
        const newType = getSchemaForStdScalars(encodeData.type, options);
        newTarget.type = newType.type;
        // If the target already has a format it takes priority. (e.g. int32)
        const encodedFieldName = getEncodedFieldName(typespecType);
        newTarget[encodedFieldName] = mergeFormatAndEncoding(newTarget[encodedFieldName], encodeData.encoding, newType.format);
        return newTarget;
    }
    return new ObjectBuilder(target);
}
function mergeFormatAndEncoding(format, encoding, encodeAsFormat) {
    switch (format) {
        case undefined:
            return encodeAsFormat ?? encoding ?? format;
        case "date-time":
            switch (encoding) {
                case "rfc3339":
                    return "date-time";
                case "unixTimestamp":
                    return "unixtime";
                case "rfc7231":
                    return "http-date";
                default:
                    return encoding;
            }
        case "duration":
            switch (encoding) {
                case "ISO8601":
                    return "duration";
                default:
                    return encodeAsFormat ?? encoding;
            }
        default:
            return encodeAsFormat ?? encoding ?? format;
    }
}

function getEncodingFieldName$1() {
    // In Open API 3.0, format is always used for encoding.
    return "format";
}
const applyEncoding$1 = (program, typespecType, target, options) => {
    return applyEncoding$2(program, typespecType, target, getEncodingFieldName$1, options);
};
const getRawBinarySchema$1 = () => {
    return { type: "string", format: "binary" };
};
const isRawBinarySchema$1 = (schema) => {
    return schema.type === "string" && schema.format === "binary";
};

function getEncodingFieldName(typespecType) {
    // In Open API 3.1, `contentEncoding` is used for encoded binary data instead of `format`.
    const typeIsBytes = isScalarExtendsBytes(typespecType.kind === "ModelProperty" ? typespecType.type : typespecType);
    if (typeIsBytes) {
        return "contentEncoding";
    }
    return "format";
}
const applyEncoding = (program, typespecType, target, options) => {
    return applyEncoding$2(program, typespecType, target, getEncodingFieldName, options);
};
const getRawBinarySchema = (contentType) => {
    if (contentType) {
        return { contentMediaType: contentType };
    }
    return {};
};
const isRawBinarySchema = (schema) => {
    return schema.type === undefined;
};

function attachExtensions(program, type, emitObject) {
    // Attach any OpenAPI extensions
    const extensions = getExtensions$1(program, type);
    if (extensions) {
        for (const key of extensions.keys()) {
            emitObject[key] = extensions.get(key);
        }
    }
}

/**
 * Base OpenAPI3 schema emitter. Deals with emitting content of `components/schemas` section.
 */
class OpenAPI3SchemaEmitterBase extends TypeEmitter {
    _metadataInfo;
    _visibilityUsage;
    _options;
    _jsonSchemaModule;
    _xmlModule;
    constructor(emitter, metadataInfo, visibilityUsage, options, optionalDependencies) {
        super(emitter);
        this._metadataInfo = metadataInfo;
        this._visibilityUsage = visibilityUsage;
        this._options = options;
        this._jsonSchemaModule = optionalDependencies.jsonSchemaModule;
        this._xmlModule = optionalDependencies.xmlModule;
    }
    modelDeclarationReferenceContext(model, name) {
        return this.reduceContext(model);
    }
    modelLiteralReferenceContext(model) {
        return this.reduceContext(model);
    }
    scalarDeclarationReferenceContext(scalar, name) {
        return this.reduceContext(scalar);
    }
    enumDeclarationReferenceContext(en, name) {
        return this.reduceContext(en);
    }
    unionDeclarationReferenceContext(union) {
        return this.reduceContext(union);
    }
    reduceContext(type) {
        const visibility = this.#getVisibilityContext();
        const patch = {};
        if (visibility !== Visibility.Read && !this._metadataInfo.isTransformed(type, visibility)) {
            patch.visibility = Visibility.Read;
        }
        const contentType = this.getContentType();
        if (contentType === "application/json") {
            patch.contentType = undefined;
        }
        return patch;
    }
    applyDiscriminator(type, schema) {
        const program = this.emitter.getProgram();
        const discriminator = getDiscriminator(program, type);
        if (discriminator) {
            // the decorator validates that all the variants will be a model type
            // with the discriminator field present.
            schema.discriminator = { ...discriminator };
            const discriminatedUnion = ignoreDiagnostics(getDiscriminatedUnion(type, discriminator));
            if (discriminatedUnion.variants.size > 0) {
                schema.discriminator.mapping = this.getDiscriminatorMapping(discriminatedUnion);
            }
        }
    }
    modelDeclaration(model, _) {
        const program = this.emitter.getProgram();
        const visibility = this.#getVisibilityContext();
        const schema = new ObjectBuilder({
            type: "object",
            required: this.#requiredModelProperties(model, visibility),
            properties: this.emitter.emitModelProperties(model),
        });
        if (model.indexer) {
            schema.set("additionalProperties", this.emitter.emitTypeReference(model.indexer.value));
        }
        const derivedModels = model.derivedModels.filter(includeDerivedModel);
        // getSchemaOrRef on all children to push them into components.schemas
        for (const child of derivedModels) {
            this.emitter.emitTypeReference(child);
        }
        this.applyDiscriminator(model, schema);
        this.#applyExternalDocs(model, schema);
        if (model.baseModel) {
            schema.set("allOf", Builders.array([this.emitter.emitTypeReference(model.baseModel)]));
        }
        const baseName = getOpenAPITypeName(program, model, this.#typeNameOptions());
        const isMultipart = this.getContentType().startsWith("multipart/");
        const name = isMultipart ? baseName + "MultiPart" : baseName;
        return this.#createDeclaration(model, name, this.applyConstraints(model, schema));
    }
    #applyExternalDocs(typespecType, target) {
        const externalDocs = getExternalDocs(this.emitter.getProgram(), typespecType);
        if (externalDocs) {
            target.externalDocs = externalDocs;
        }
    }
    #typeNameOptions() {
        const serviceNamespaceName = this.emitter.getContext().serviceNamespaceName;
        return {
            // shorten type names by removing TypeSpec and service namespace
            namespaceFilter(ns) {
                const name = getNamespaceFullName(ns);
                return name !== serviceNamespaceName;
            },
        };
    }
    #getVisibilityContext() {
        return this.emitter.getContext().visibility ?? Visibility.Read;
    }
    #ignoreMetadataAnnotations() {
        return this.emitter.getContext().ignoreMetadataAnnotations;
    }
    getContentType() {
        return this.emitter.getContext().contentType ?? "application/json";
    }
    modelLiteral(model) {
        const schema = new ObjectBuilder({
            type: "object",
            properties: this.emitter.emitModelProperties(model),
            required: this.#requiredModelProperties(model, this.#getVisibilityContext()),
        });
        if (model.indexer) {
            schema.set("additionalProperties", this.emitter.emitTypeReference(model.indexer.value));
        }
        return schema;
    }
    modelInstantiation(model, name) {
        name = name ?? getOpenAPITypeName(this.emitter.getProgram(), model, this.#typeNameOptions());
        if (!name) {
            return this.modelLiteral(model);
        }
        return this.modelDeclaration(model, name);
    }
    arrayDeclaration(array, name, elementType) {
        const schema = new ObjectBuilder({
            type: "array",
            items: this.emitter.emitTypeReference(elementType),
        });
        return this.#createDeclaration(array, name, this.applyConstraints(array, schema));
    }
    arrayDeclarationReferenceContext(array, name, elementType) {
        return {
            visibility: this.#getVisibilityContext() | Visibility.Item,
        };
    }
    arrayLiteral(array, elementType) {
        return this.#inlineType(array, new ObjectBuilder({
            type: "array",
            items: this.emitter.emitTypeReference(elementType),
        }));
    }
    arrayLiteralReferenceContext(array, elementType) {
        return {
            visibility: this.#getVisibilityContext() | Visibility.Item,
        };
    }
    #requiredModelProperties(model, visibility) {
        const requiredProps = [];
        for (const prop of model.properties.values()) {
            if (isNeverType(prop.type)) {
                // If the property has a type of 'never', don't include it in the schema
                continue;
            }
            if (!this._metadataInfo.isPayloadProperty(prop, visibility, this.#ignoreMetadataAnnotations())) {
                continue;
            }
            if (!this._metadataInfo.isOptional(prop, visibility)) {
                const encodedName = resolveEncodedName(this.emitter.getProgram(), prop, this.getContentType());
                requiredProps.push(encodedName);
            }
        }
        const discriminator = getDiscriminator(this.emitter.getProgram(), model);
        if (discriminator) {
            if (!requiredProps.includes(discriminator.propertyName)) {
                requiredProps.push(discriminator.propertyName);
            }
        }
        return requiredProps.length > 0 ? requiredProps : undefined;
    }
    modelProperties(model) {
        const program = this.emitter.getProgram();
        const props = new ObjectBuilder();
        const visibility = this.emitter.getContext().visibility;
        const contentType = this.getContentType();
        for (const prop of model.properties.values()) {
            if (isNeverType(prop.type)) {
                // If the property has a type of 'never', don't include it in the schema
                continue;
            }
            if (!this._metadataInfo.isPayloadProperty(prop, visibility, this.#ignoreMetadataAnnotations())) {
                continue;
            }
            const result = this.emitter.emitModelProperty(prop);
            const encodedName = resolveEncodedName(program, prop, contentType);
            props.set(encodedName, result);
        }
        const discriminator = getDiscriminator(program, model);
        if (discriminator && !(discriminator.propertyName in props)) {
            props.set(discriminator.propertyName, {
                type: "string",
                description: `Discriminator property for ${model.name}.`,
            });
        }
        if (Object.keys(props).length === 0) {
            return this.emitter.result.none();
        }
        return props;
    }
    getRawBinarySchema() {
        throw new Error("Method not implemented.");
    }
    modelPropertyLiteral(prop) {
        const program = this.emitter.getProgram();
        const isMultipart = this.getContentType().startsWith("multipart/");
        if (isMultipart) {
            if (isBytesKeptRaw(program, prop.type) && getEncode(program, prop) === undefined) {
                return this.getRawBinarySchema();
            }
            if (prop.type.kind === "Model" &&
                isArrayModelType(program, prop.type) &&
                isBytesKeptRaw(program, prop.type.indexer.value)) {
                return { type: "array", items: this.getRawBinarySchema() };
            }
        }
        const refSchema = this.emitter.emitTypeReference(prop.type, {
            referenceContext: isMultipart &&
                (prop.type.kind !== "Union" ||
                    ![...prop.type.variants.values()].some((x) => isBytesKeptRaw(program, x.type)))
                ? { contentType: "application/json" }
                : {},
        });
        if (refSchema.kind !== "code") {
            reportDiagnostic(program, {
                code: "invalid-model-property",
                format: {
                    type: prop.type.kind,
                },
                target: prop,
            });
            return {};
        }
        const isRef = refSchema.value instanceof Placeholder || "$ref" in refSchema.value;
        const schema = this.applyEncoding(prop, refSchema.value);
        // Apply decorators on the property to the type's schema
        const additionalProps = this.applyConstraints(prop, {}, schema);
        if (prop.defaultValue) {
            additionalProps.default = getDefaultValue(program, prop.defaultValue, prop);
        }
        if (isReadonlyProperty(program, prop)) {
            additionalProps.readOnly = true;
        }
        // Attach any additional OpenAPI extensions
        attachExtensions(program, prop, additionalProps);
        if (schema && isRef && !(prop.type.kind === "Model" && isArrayModelType(program, prop.type))) {
            if (Object.keys(additionalProps).length === 0) {
                return schema;
            }
            else {
                if (additionalProps.xml?.attribute) {
                    return additionalProps;
                }
                else {
                    return {
                        allOf: [schema],
                        ...additionalProps,
                    };
                }
            }
        }
        else {
            if (getOneOf(program, prop) && schema.anyOf) {
                schema.oneOf = schema.anyOf;
                delete schema.anyOf;
            }
            const merged = new ObjectBuilder(schema);
            for (const [key, value] of Object.entries(additionalProps)) {
                merged.set(key, value);
            }
            return merged;
        }
    }
    booleanLiteral(boolean) {
        return { type: "boolean", enum: [boolean.value] };
    }
    stringLiteral(string) {
        return { type: "string", enum: [string.value] };
    }
    stringTemplate(string) {
        if (string.stringValue !== undefined) {
            return { type: "string", enum: [string.stringValue] };
        }
        const diagnostics = explainStringTemplateNotSerializable(string);
        this.emitter
            .getProgram()
            .reportDiagnostics(diagnostics.map((x) => ({ ...x, severity: "warning" })));
        return { type: "string" };
    }
    numericLiteral(number) {
        return { type: "number", enum: [number.value] };
    }
    enumDeclaration(en, name) {
        const baseName = getOpenAPITypeName(this.emitter.getProgram(), en, this.#typeNameOptions());
        return this.#createDeclaration(en, baseName, new ObjectBuilder(this.enumSchema(en)));
    }
    enumSchema(en) {
        // Enums are handled differently between 3.x versions due to the differences in `type`
        throw new Error("Method not implemented.");
    }
    enumMember(member) {
        return this.enumMemberReference(member);
    }
    enumMemberReference(member) {
        // would like to dispatch to the same `literal` codepaths but enum members aren't literal types
        switch (typeof member.value) {
            case "undefined":
                return { type: "string", enum: [member.name] };
            case "string":
                return { type: "string", enum: [member.value] };
            case "number":
                return { type: "number", enum: [member.value] };
        }
    }
    unionDeclaration(union, name) {
        const schema = this.unionSchema(union);
        const baseName = getOpenAPITypeName(this.emitter.getProgram(), union, this.#typeNameOptions());
        return this.#createDeclaration(union, baseName, schema);
    }
    unionSchema(union) {
        // Unions are handled differently between 3.x versions
        // mostly due to how nullable properties are handled.
        throw new Error("Method not implemented.");
    }
    getDiscriminatorMapping(union) {
        const mapping = {};
        for (const [key, model] of union.variants.entries()) {
            const ref = this.emitter.emitTypeReference(model);
            compilerAssert(ref.kind === "code", "Unexpected ref schema. Should be kind: code");
            mapping[key] = ref.value.$ref;
        }
        return mapping;
    }
    unionLiteral(union) {
        return this.unionSchema(union);
    }
    unionVariants(union) {
        const variants = new ArrayBuilder();
        for (const variant of union.variants.values()) {
            variants.push(this.emitter.emitType(variant));
        }
        return variants;
    }
    unionVariant(variant) {
        return this.emitter.emitTypeReference(variant.type);
    }
    modelPropertyReference(prop) {
        return this.modelPropertyLiteral(prop);
    }
    reference(targetDeclaration, pathUp, pathDown, commonScope) {
        if (targetDeclaration.value instanceof Placeholder) {
            // I don't think this is possible, confirm.
            throw new Error("Can't form reference to declaration that hasn't been created yet");
        }
        // these will be undefined when creating a self-reference
        const currentSfScope = pathUp[pathUp.length - 1];
        const targetSfScope = pathDown[0];
        if (targetSfScope && currentSfScope && !targetSfScope.sourceFile.meta.shouldEmit) {
            currentSfScope.sourceFile.meta.bundledRefs.push(targetDeclaration);
        }
        return { $ref: `#/components/schemas/${targetDeclaration.name}` };
    }
    circularReference(target, scope, cycle) {
        if (!cycle.containsDeclaration) {
            reportDiagnostic(this.emitter.getProgram(), {
                code: "inline-cycle",
                format: {
                    type: cycle.toString(),
                },
                target: cycle.first.type,
            });
            return {};
        }
        return super.circularReference(target, scope, cycle);
    }
    scalarDeclaration(scalar, name) {
        const isStd = isStdType(this.emitter.getProgram(), scalar);
        const schema = this.#getSchemaForScalar(scalar);
        const baseName = getOpenAPITypeName(this.emitter.getProgram(), scalar, this.#typeNameOptions());
        // Don't create a declaration for std types
        return isStd
            ? schema
            : this.#createDeclaration(scalar, baseName, new ObjectBuilder(schema));
    }
    scalarInstantiation(scalar, name) {
        return this.#getSchemaForScalar(scalar);
    }
    tupleLiteral(tuple) {
        return { type: "array", items: {} };
    }
    #getSchemaForScalar(scalar) {
        let result = {};
        const isStd = isStdType(this.emitter.getProgram(), scalar);
        if (isStd) {
            result = this.getSchemaForStdScalars(scalar);
        }
        else if (scalar.baseScalar) {
            result = this.#getSchemaForScalar(scalar.baseScalar);
        }
        const withDecorators = this.applyEncoding(scalar, this.applyConstraints(scalar, result));
        if (isStd) {
            // Standard types are going to be inlined in the spec and we don't want the description of the scalar to show up
            delete withDecorators.description;
        }
        return withDecorators;
    }
    getSchemaForStdScalars(scalar) {
        return getSchemaForStdScalars(scalar, this._options);
    }
    applyCustomConstraints(type, target, refSchema) { }
    applyConstraints(type, original, refSchema) {
        // Apply common constraints
        const schema = new ObjectBuilder(original);
        const program = this.emitter.getProgram();
        const applyConstraint = (fn, key) => {
            const value = fn(program, type);
            if (value !== undefined) {
                schema[key] = value;
            }
        };
        applyConstraint(getMinLength, "minLength");
        applyConstraint(getMaxLength, "maxLength");
        applyConstraint(getMinValue, "minimum");
        applyConstraint(getMaxValue, "maximum");
        applyConstraint(getPattern, "pattern");
        applyConstraint(getMinItems, "minItems");
        applyConstraint(getMaxItems, "maxItems");
        // apply json schema decorators
        const jsonSchemaModule = this._jsonSchemaModule;
        if (jsonSchemaModule) {
            applyConstraint(jsonSchemaModule.getMultipleOf, "multipleOf");
            applyConstraint(jsonSchemaModule.getUniqueItems, "uniqueItems");
            applyConstraint(jsonSchemaModule.getMinProperties, "minProperties");
            applyConstraint(jsonSchemaModule.getMaxProperties, "maxProperties");
        }
        if (isSecret(program, type)) {
            schema.format = "password";
        }
        // the stdlib applies a format of "url" but json schema wants "uri",
        // so ignore this format if it's the built-in type.
        if (!isStdType(program, type) || type.name !== "url") {
            applyConstraint(getFormat, "format");
        }
        applyConstraint(getDoc, "description");
        applyConstraint(getSummary, "title");
        applyConstraint((p, t) => (getDeprecated(p, t) !== undefined ? true : undefined), "deprecated");
        this.applyCustomConstraints(type, schema, refSchema);
        this.applyXml(type, schema, refSchema);
        attachExtensions(program, type, schema);
        const values = getKnownValues(program, type);
        if (values) {
            return new ObjectBuilder({
                oneOf: [schema, this.enumSchema(values)],
            });
        }
        return new ObjectBuilder(schema);
    }
    applyXml(type, schema, refSchema) {
        const program = this.emitter.getProgram();
        if (this._xmlModule) {
            switch (type.kind) {
                case "Scalar":
                case "Model":
                    this._xmlModule.attachXmlObjectForScalarOrModel(program, type, schema);
                    break;
                case "ModelProperty":
                    this._xmlModule.attachXmlObjectForModelProperty(program, this._options, type, schema, refSchema);
                    break;
            }
        }
    }
    #inlineType(type, schema) {
        if (this._options.includeXTypeSpecName !== "never") {
            schema.set("x-typespec-name", getTypeName(type, this.#typeNameOptions()));
        }
        return schema;
    }
    #createDeclaration(type, name, schema) {
        const refUrl = getRef(this.emitter.getProgram(), type);
        if (refUrl) {
            return {
                $ref: refUrl,
            };
        }
        if (shouldInline(this.emitter.getProgram(), type)) {
            return this.#inlineType(type, schema);
        }
        const title = getSummary(this.emitter.getProgram(), type);
        if (title) {
            schema.set("title", title);
        }
        const usage = this._visibilityUsage.getUsage(type);
        const shouldAddSuffix = usage !== undefined && usage.size > 1;
        const visibility = this.#getVisibilityContext();
        const fullName = name + (shouldAddSuffix ? getVisibilitySuffix(visibility, Visibility.Read) : "");
        const decl = this.emitter.result.declaration(fullName, schema);
        checkDuplicateTypeName(this.emitter.getProgram(), type, fullName, Object.fromEntries(decl.scope.declarations.map((x) => [x.name, true])));
        return decl;
    }
    applyEncoding(typespecType, target) {
        throw new Error("Method not implemented.");
    }
    programContext(program) {
        const sourceFile = this.emitter.createSourceFile("openapi");
        return { scope: sourceFile.globalScope };
    }
}
const Builders = {
    array: (items) => {
        const builder = new ArrayBuilder();
        for (const item of items) {
            builder.push(item);
        }
        return builder;
    },
    object: (obj) => {
        const builder = new ObjectBuilder();
        for (const [key, value] of Object.entries(obj)) {
            builder.set(key, value);
        }
        return builder;
    },
};

function createWrappedSchemaEmitterClass$1(metadataInfo, visibilityUsage, options, optionalDependencies) {
    return class extends OpenAPI3SchemaEmitter {
        constructor(emitter) {
            super(emitter, metadataInfo, visibilityUsage, options, optionalDependencies);
        }
    };
}
const createSchemaEmitter3_0 = ({ program, context, ...rest }) => {
    return createAssetEmitter(program, createWrappedSchemaEmitterClass$1(rest.metadataInfo, rest.visibilityUsage, rest.options, rest.optionalDependencies), context);
};
/**
 * OpenAPI 3.0 schema emitter. Deals with emitting content of `components/schemas` section.
 */
class OpenAPI3SchemaEmitter extends OpenAPI3SchemaEmitterBase {
    #applySchemaExamples(type, target) {
        const program = this.emitter.getProgram();
        const examples = getExamples(program, type);
        if (examples.length > 0) {
            target.set("example", serializeValueAsJson(program, examples[0].value, type));
        }
    }
    applyCustomConstraints(type, target, refSchema) {
        const program = this.emitter.getProgram();
        const minValueExclusive = getMinValueExclusive(program, type);
        if (minValueExclusive !== undefined) {
            target.minimum = minValueExclusive;
            target.exclusiveMinimum = true;
        }
        const maxValueExclusive = getMaxValueExclusive(program, type);
        if (maxValueExclusive !== undefined) {
            target.maximum = maxValueExclusive;
            target.exclusiveMaximum = true;
        }
        this.#applySchemaExamples(type, target);
    }
    applyEncoding(typespecType, target) {
        return applyEncoding$1(this.emitter.getProgram(), typespecType, target, this._options);
    }
    getRawBinarySchema() {
        return getRawBinarySchema$1();
    }
    enumSchema(en) {
        const program = this.emitter.getProgram();
        if (en.members.size === 0) {
            reportDiagnostic(program, { code: "empty-enum", target: en });
            return {};
        }
        const enumTypes = new Set();
        const enumValues = new Set();
        for (const member of en.members.values()) {
            enumTypes.add(typeof member.value === "number" ? "number" : "string");
            enumValues.add(member.value ?? member.name);
        }
        if (enumTypes.size > 1) {
            reportDiagnostic(program, { code: "enum-unique-type", target: en });
        }
        const schema = {
            type: enumTypes.values().next().value,
            enum: [...enumValues],
        };
        return this.applyConstraints(en, schema);
    }
    unionSchema(union) {
        const program = this.emitter.getProgram();
        if (union.variants.size === 0) {
            reportDiagnostic(program, { code: "empty-union", target: union });
            return new ObjectBuilder({});
        }
        const variants = Array.from(union.variants.values());
        const literalVariantEnumByType = {};
        const ofType = getOneOf(program, union) ? "oneOf" : "anyOf";
        const schemaMembers = [];
        let nullable = false;
        const isMultipart = this.getContentType().startsWith("multipart/");
        for (const variant of variants) {
            if (isNullType(variant.type)) {
                nullable = true;
                continue;
            }
            if (isMultipart && isBytesKeptRaw(program, variant.type)) {
                schemaMembers.push({ schema: this.getRawBinarySchema(), type: variant.type });
                continue;
            }
            if (isLiteralType(variant.type)) {
                if (!literalVariantEnumByType[variant.type.kind]) {
                    const enumValue = [variant.type.value];
                    literalVariantEnumByType[variant.type.kind] = enumValue;
                    schemaMembers.push({
                        schema: { type: literalType(variant.type), enum: enumValue },
                        type: null,
                    });
                }
                else {
                    literalVariantEnumByType[variant.type.kind].push(variant.type.value);
                }
            }
            else {
                const enumSchema = this.emitter.emitTypeReference(variant.type, {
                    referenceContext: isMultipart ? { contentType: "application/json" } : {},
                });
                compilerAssert(enumSchema.kind === "code", "Unexpected enum schema. Should be kind: code");
                schemaMembers.push({ schema: enumSchema.value, type: variant.type });
            }
        }
        const wrapWithObjectBuilder = (schemaMember, { mergeUnionWideConstraints }) => {
            // we can just return the single schema member after applying nullable
            const schema = schemaMember.schema;
            const type = schemaMember.type;
            const additionalProps = mergeUnionWideConstraints
                ? this.applyConstraints(union, {})
                : {};
            if (mergeUnionWideConstraints && nullable) {
                additionalProps.nullable = true;
            }
            if (Object.keys(additionalProps).length === 0) {
                return new ObjectBuilder(schema);
            }
            else {
                if ((schema instanceof Placeholder || "$ref" in schema) &&
                    !(type && shouldInline(program, type))) {
                    if (type && (type.kind === "Model" || type.kind === "Scalar")) {
                        return new ObjectBuilder({
                            type: "object",
                            allOf: Builders.array([schema]),
                            ...additionalProps,
                        });
                    }
                    else {
                        return new ObjectBuilder({ allOf: Builders.array([schema]), ...additionalProps });
                    }
                }
                else {
                    const merged = new ObjectBuilder(schema);
                    for (const [key, value] of Object.entries(additionalProps)) {
                        merged.set(key, value);
                    }
                    return merged;
                }
            }
        };
        const checkMerge = (schemaMembers) => {
            if (nullable) {
                for (const m of schemaMembers) {
                    if (m.schema instanceof Placeholder || "$ref" in m.schema) {
                        return true;
                    }
                }
            }
            return false;
        };
        if (schemaMembers.length === 0) {
            if (nullable) {
                // This union is equivalent to just `null` but OA3 has no way to specify
                // null as a value, so we throw an error.
                reportDiagnostic(program, { code: "union-null", target: union });
                return new ObjectBuilder({});
            }
            else {
                // completely empty union can maybe only happen with bugs?
                compilerAssert(false, "Attempting to emit an empty union");
            }
        }
        if (schemaMembers.length === 1) {
            return wrapWithObjectBuilder(schemaMembers[0], { mergeUnionWideConstraints: true });
        }
        const isMerge = checkMerge(schemaMembers);
        const schema = {
            [ofType]: schemaMembers.map((m) => wrapWithObjectBuilder(m, { mergeUnionWideConstraints: isMerge })),
        };
        if (!isMerge && nullable) {
            schema.nullable = true;
        }
        this.applyDiscriminator(union, schema);
        return this.applyConstraints(union, schema);
    }
    intrinsic(intrinsic, name) {
        switch (name) {
            case "unknown":
                return {};
            case "null":
                return { nullable: true };
        }
        reportDiagnostic(this.emitter.getProgram(), {
            code: "invalid-schema",
            format: { type: name },
            target: intrinsic,
        });
        return {};
    }
}

function createWrappedSchemaEmitterClass(metadataInfo, visibilityUsage, options, optionalDependencies) {
    return class extends OpenAPI31SchemaEmitter {
        constructor(emitter) {
            super(emitter, metadataInfo, visibilityUsage, options, optionalDependencies);
        }
    };
}
const createSchemaEmitter3_1 = ({ program, context, ...rest }) => {
    return createAssetEmitter(program, createWrappedSchemaEmitterClass(rest.metadataInfo, rest.visibilityUsage, rest.options, rest.optionalDependencies), context);
};
/**
 * OpenAPI 3.1 schema emitter. Deals with emitting content of `components/schemas` section.
 */
class OpenAPI31SchemaEmitter extends OpenAPI3SchemaEmitterBase {
    #applySchemaExamples(program, type, target) {
        const examples = getExamples(program, type);
        if (examples.length > 0) {
            target.set("examples", examples.map((example) => serializeValueAsJson(program, example.value, type)));
        }
    }
    applyCustomConstraints(type, target, refSchema) {
        const applyConstraint = (fn, key) => {
            const value = fn(program, type);
            if (value !== undefined) {
                target[key] = value;
            }
        };
        const applyTypeConstraint = (fn, key) => {
            const constraintType = fn(this.emitter.getProgram(), type);
            if (constraintType) {
                const ref = this.emitter.emitTypeReference(constraintType);
                compilerAssert(ref.kind === "code", "Unexpected non-code result from emit reference");
                target.set(key, ref.value);
            }
        };
        const program = this.emitter.getProgram();
        const minValueExclusive = getMinValueExclusive(program, type);
        if (minValueExclusive !== undefined) {
            target.minimum = undefined;
            target.exclusiveMinimum = minValueExclusive;
        }
        const maxValueExclusive = getMaxValueExclusive(program, type);
        if (maxValueExclusive !== undefined) {
            target.maximum = undefined;
            target.exclusiveMaximum = maxValueExclusive;
        }
        // apply json schema decorators
        const jsonSchemaModule = this._jsonSchemaModule;
        if (jsonSchemaModule) {
            applyTypeConstraint(jsonSchemaModule.getContains, "contains");
            applyConstraint(jsonSchemaModule.getMinContains, "minContains");
            applyConstraint(jsonSchemaModule.getMaxContains, "maxContains");
            applyConstraint(jsonSchemaModule.getContentEncoding, "contentEncoding");
            applyConstraint(jsonSchemaModule.getContentMediaType, "contentMediaType");
            applyTypeConstraint(jsonSchemaModule.getContentSchema, "contentSchema");
            const prefixItems = jsonSchemaModule.getPrefixItems(program, type);
            if (prefixItems) {
                const prefixItemsSchema = new ArrayBuilder();
                for (const item of prefixItems.values) {
                    prefixItemsSchema.push(this.emitter.emitTypeReference(item));
                }
                target.set("prefixItems", prefixItemsSchema);
            }
        }
        this.#applySchemaExamples(program, type, target);
    }
    applyEncoding(typespecType, target) {
        return applyEncoding(this.emitter.getProgram(), typespecType, target, this._options);
    }
    getRawBinarySchema() {
        return getRawBinarySchema();
    }
    getSchemaForStdScalars(scalar) {
        // Raw binary data is handled separately when resolving a request/response body.
        // Open API 3.1 treats encoded binaries differently from Open API 3.0, so we need to handle
        // the Scalar 'bytes' special here.
        // @see https://spec.openapis.org/oas/v3.1.1.html#working-with-binary-data
        if (scalar.name === "bytes") {
            const contentType = this.emitter.getContext().contentType;
            return { type: "string", contentMediaType: contentType, contentEncoding: "base64" };
        }
        return super.getSchemaForStdScalars(scalar);
    }
    enumSchema(en) {
        const program = this.emitter.getProgram();
        if (en.members.size === 0) {
            reportDiagnostic(program, { code: "empty-enum", target: en });
            return {};
        }
        const enumTypes = new Set();
        const enumValues = new Set();
        for (const member of en.members.values()) {
            enumTypes.add(typeof member.value === "number" ? "number" : "string");
            enumValues.add(member.value ?? member.name);
        }
        const enumTypesArray = [...enumTypes];
        const schema = {
            type: enumTypesArray.length === 1 ? enumTypesArray[0] : enumTypesArray,
            enum: [...enumValues],
        };
        return this.applyConstraints(en, schema);
    }
    unionSchema(union) {
        const program = this.emitter.getProgram();
        if (union.variants.size === 0) {
            reportDiagnostic(program, { code: "empty-union", target: union });
            return new ObjectBuilder({});
        }
        const variants = Array.from(union.variants.values());
        const literalVariantEnumByType = {};
        const ofType = getOneOf(program, union) ? "oneOf" : "anyOf";
        const schemaMembers = [];
        const isMultipart = this.getContentType().startsWith("multipart/");
        // 1. Iterate over all the union variants to generate a schema for each one.
        for (const variant of variants) {
            // 2. Special handling for multipart - want to treat as binary
            if (isMultipart && isBytesKeptRaw(program, variant.type)) {
                schemaMembers.push({ schema: this.getRawBinarySchema(), type: variant.type });
                continue;
            }
            // 3.a. Literal types are actual values (though not Value types)
            if (isLiteralType(variant.type)) {
                // Create schemas grouped by kind (boolean, string, numeric)
                // and add the literals seen to each respective `enum` array
                if (!literalVariantEnumByType[variant.type.kind]) {
                    const enumValue = [variant.type.value];
                    literalVariantEnumByType[variant.type.kind] = enumValue;
                    schemaMembers.push({
                        schema: { type: literalType(variant.type), enum: enumValue },
                        type: null,
                    });
                }
                else {
                    literalVariantEnumByType[variant.type.kind].push(variant.type.value);
                }
            }
            else {
                // 3.b. Anything else, we get the schema for that type.
                const enumSchema = this.emitter.emitTypeReference(variant.type, {
                    referenceContext: isMultipart ? { contentType: "application/json" } : {},
                });
                compilerAssert(enumSchema.kind === "code", "Unexpected enum schema. Should be kind: code");
                schemaMembers.push({ schema: enumSchema.value, type: variant.type });
            }
        }
        const wrapWithObjectBuilder = (schemaMember, { mergeUnionWideConstraints }) => {
            const schema = schemaMember.schema;
            const type = schemaMember.type;
            const additionalProps = mergeUnionWideConstraints
                ? this.applyConstraints(union, {})
                : {};
            if (Object.keys(additionalProps).length === 0) {
                return new ObjectBuilder(schema);
            }
            else {
                if ((schema instanceof Placeholder || "$ref" in schema) &&
                    !(type && shouldInline(program, type))) {
                    if (type && (type.kind === "Model" || type.kind === "Scalar")) {
                        return new ObjectBuilder({
                            type: "object",
                            allOf: Builders.array([schema]),
                            ...additionalProps,
                        });
                    }
                    else {
                        return new ObjectBuilder({ allOf: Builders.array([schema]), ...additionalProps });
                    }
                }
                else {
                    const merged = new ObjectBuilder(schema);
                    for (const [key, value] of Object.entries(additionalProps)) {
                        merged.set(key, value);
                    }
                    return merged;
                }
            }
        };
        if (schemaMembers.length === 0) {
            compilerAssert(false, "Attempting to emit an empty union");
        }
        if (schemaMembers.length === 1) {
            return wrapWithObjectBuilder(schemaMembers[0], { mergeUnionWideConstraints: true });
        }
        const schema = {
            [ofType]: schemaMembers.map((m) => wrapWithObjectBuilder(m, { mergeUnionWideConstraints: false })),
        };
        this.applyDiscriminator(union, schema);
        return this.applyConstraints(union, schema);
    }
    intrinsic(intrinsic, name) {
        switch (name) {
            case "unknown":
                return {};
            case "null":
                return { type: "null" };
        }
        reportDiagnostic(this.emitter.getProgram(), {
            code: "invalid-schema",
            format: { type: name },
            target: intrinsic,
        });
        return {};
    }
    tupleLiteral(tuple) {
        return new ObjectBuilder({
            type: "array",
            prefixItems: this.emitter.emitTupleLiteralValues(tuple),
        });
    }
    tupleLiteralValues(tuple) {
        const values = new ArrayBuilder();
        for (const value of tuple.values.values()) {
            values.push(this.emitter.emitType(value));
        }
        return values;
    }
}

function getOpenApiSpecProps(specVersion) {
    switch (specVersion) {
        case "3.0.0":
            return {
                applyEncoding: applyEncoding$1,
                createRootDoc(program, serviceType, serviceVersion) {
                    return createRoot(program, serviceType, specVersion, serviceVersion);
                },
                createSchemaEmitter: createSchemaEmitter3_0,
                getRawBinarySchema: getRawBinarySchema$1,
                isRawBinarySchema: isRawBinarySchema$1,
            };
        case "3.1.0":
            return {
                applyEncoding: applyEncoding,
                createRootDoc(program, serviceType, serviceVersion) {
                    return createRoot(program, serviceType, specVersion, serviceVersion);
                },
                createSchemaEmitter: createSchemaEmitter3_1,
                getRawBinarySchema: getRawBinarySchema,
                isRawBinarySchema: isRawBinarySchema,
            };
    }
}
function createRoot(program, serviceType, specVersion, serviceVersion) {
    const info = resolveInfo(program, serviceType);
    return {
        openapi: specVersion,
        info: {
            title: "(title)",
            ...info,
            version: serviceVersion ?? info?.version ?? "0.0.0",
        },
        externalDocs: getExternalDocs(program, serviceType),
        tags: [],
        paths: {},
        security: undefined,
        components: {
            parameters: {},
            requestBodies: {},
            responses: {},
            schemas: {},
            examples: {},
            securitySchemes: {},
        },
    };
}

function resolveVisibilityUsage(program, metadataInfo, root, omitUnreachableTypes) {
    const usages = new Map();
    addUsagesInContainer(program, metadataInfo, root, usages);
    const reachableTypes = new Set(usages.keys());
    if (!omitUnreachableTypes) {
        // Evaluate all unreferenced types and the types they reference with Visibility.All
        const trackType = (type) => {
            if (!usages.has(type)) {
                navigateReferencedTypes(type, Visibility.All, (type, vis) => trackUsageExact(usages, type, vis));
            }
        };
        navigateTypesInNamespace(root, {
            model: trackType,
            scalar: trackType,
            enum: trackType,
            union: trackType,
        });
    }
    return {
        getUsage: (type) => {
            const used = usages.get(type);
            if (used === undefined) {
                return undefined;
            }
            return usages.get(type);
        },
        isUnreachable: (type) => {
            return !reachableTypes.has(type);
        },
    };
}
function addUsagesInContainer(program, metadataInfo, type, usages) {
    switch (type.kind) {
        case "Namespace":
            addUsagesInNamespace(program, metadataInfo, type, usages);
            break;
        case "Interface":
            addUsagesInInterface(program, metadataInfo, type, usages);
            break;
        case "Operation":
            addUsagesInOperation(program, metadataInfo, type, usages);
            break;
    }
}
function trackUsage(metadataInfo, usages, type, usage) {
    const effective = metadataInfo.getEffectivePayloadType(type, usage);
    trackUsageExact(usages, type, usage);
    if (effective !== type) {
        trackUsageExact(usages, effective, usage);
    }
}
function trackUsageExact(usages, type, usage) {
    const existingFlag = usages.get(type) ?? new Set();
    existingFlag.add(usage);
    usages.set(type, existingFlag);
}
function addUsagesInNamespace(program, metadataInfo, namespace, usages) {
    for (const subNamespace of namespace.namespaces.values()) {
        addUsagesInNamespace(program, metadataInfo, subNamespace, usages);
    }
    for (const Interface of namespace.interfaces.values()) {
        addUsagesInInterface(program, metadataInfo, Interface, usages);
    }
    for (const operation of namespace.operations.values()) {
        addUsagesInOperation(program, metadataInfo, operation, usages);
    }
}
function addUsagesInInterface(program, metadataInfo, Interface, usages) {
    for (const operation of Interface.operations.values()) {
        addUsagesInOperation(program, metadataInfo, operation, usages);
    }
}
function addUsagesInOperation(program, metadataInfo, operation, usages) {
    const httpOperation = ignoreDiagnostics(getHttpOperation(program, operation));
    const visibility = resolveRequestVisibility(program, operation, httpOperation.verb);
    if (httpOperation.parameters.body) {
        navigateReferencedTypes(httpOperation.parameters.body.type, visibility, (type, vis) => trackUsage(metadataInfo, usages, type, vis));
    }
    for (const param of httpOperation.parameters.parameters) {
        navigateReferencedTypes(param.param, visibility, (type, vis) => trackUsage(metadataInfo, usages, type, vis));
    }
    navigateReferencedTypes(operation.returnType, Visibility.Read, (type, vis) => trackUsage(metadataInfo, usages, type, vis));
}
function navigateReferencedTypes(type, usage, callback, visited = new TwoLevelMap()) {
    if (visited.get(type)?.get(usage)) {
        return;
    }
    visited.getOrAdd(type, usage, () => true);
    switch (type.kind) {
        case "Model":
            callback(type, usage);
            navigateIterable(type.properties, usage, callback, visited);
            if (type.baseModel) {
                navigateReferencedTypes(type.baseModel, usage, callback, visited);
            }
            navigateIterable(type.derivedModels, usage, callback, visited);
            if (type.baseModel) {
                navigateReferencedTypes(type.baseModel, usage, callback, visited);
            }
            if (type.indexer) {
                if (type.indexer.key.name === "integer") {
                    navigateReferencedTypes(type.indexer.value, usage | Visibility.Item, callback, visited);
                }
                else {
                    navigateReferencedTypes(type.indexer.value, usage, callback, visited);
                }
            }
            break;
        case "ModelProperty":
            navigateReferencedTypes(type.type, usage, callback, visited);
            break;
        case "Union":
            callback(type, usage);
            navigateIterable(type.variants, usage, callback, visited);
            break;
        case "UnionVariant":
            navigateReferencedTypes(type.type, usage, callback, visited);
            break;
        default:
            callback(type, usage);
            break;
    }
}
function navigateIterable(map, usage, callback, visited) {
    for (const type of map.values()) {
        navigateReferencedTypes(type, usage, callback, visited);
    }
}

async function resolveXmlModule() {
    const xml = await tryImportXml();
    if (xml === undefined)
        return undefined;
    return {
        attachXmlObjectForScalarOrModel: (program, type, emitObject) => {
            const isXmlModel = isXmlModelChecker(program, type, []);
            if (!isXmlModel) {
                return;
            }
            const xmlObject = {};
            // Resolve XML name
            const xmlName = resolveEncodedName(program, type, "application/xml");
            if (xmlName !== type.name) {
                xmlObject.name = xmlName;
            }
            // Get and set XML namespace if present
            const currNs = xml.getNs(program, type);
            if (currNs) {
                xmlObject.prefix = currNs.prefix;
                xmlObject.namespace = currNs.namespace;
            }
            // Attach xml schema to emitObject if not empty
            if (Object.keys(xmlObject).length !== 0) {
                emitObject.xml = xmlObject;
            }
        },
        attachXmlObjectForModelProperty: (program, options, prop, emitObject, refSchema) => {
            if (!isXmlModelChecker(program, prop.model, []))
                return;
            const xmlObject = {};
            // Resolve XML name
            const xmlName = resolveEncodedName(program, prop, "application/xml");
            const jsonName = resolveEncodedName(program, prop, "application/json");
            if (xmlName !== prop.name && xmlName !== jsonName) {
                xmlObject.name = xmlName;
            }
            // Get and set XML namespace if present
            const currNs = xml.getNs(program, prop);
            if (currNs) {
                xmlObject.prefix = currNs.prefix;
                xmlObject.namespace = currNs.namespace;
            }
            // Set XML attribute if present
            const isAttribute = xml.isAttribute(program, prop);
            if (isAttribute) {
                if (prop.type?.kind === "Model") {
                    reportDiagnostic(program, {
                        code: "xml-attribute-invalid-property-type",
                        format: { name: prop.name },
                        target: prop,
                    });
                    emitObject.type = "string";
                    delete refSchema.items;
                }
                xmlObject.attribute = true;
            }
            // Handle array wrapping if necessary
            const hasUnwrappedDecorator = xml.isUnwrapped(program, prop);
            const isArrayProperty = prop.type?.kind === "Model" && isArrayModelType(program, prop.type);
            if (!isArrayProperty && hasUnwrappedDecorator) {
                reportDiagnostic(program, {
                    code: "xml-unwrapped-invalid-property-type",
                    format: { name: prop.name },
                    target: prop,
                });
            }
            if (isArrayProperty && refSchema.items && !isAttribute) {
                const propValue = prop.type.indexer.value;
                const propXmlName = hasUnwrappedDecorator
                    ? xmlName
                    : resolveEncodedName(program, propValue, "application/xml");
                if (propValue.kind === "Scalar") {
                    let scalarSchema = {};
                    const isStd = program.checker.isStdType(propValue);
                    if (isStd) {
                        scalarSchema = getSchemaForStdScalars(propValue, options);
                    }
                    else if (propValue.baseScalar) {
                        scalarSchema = getSchemaForStdScalars(propValue.baseScalar, options);
                    }
                    scalarSchema.xml = { name: propXmlName };
                    refSchema.items = scalarSchema;
                }
                else {
                    const items = new ArrayBuilder();
                    items.push(refSchema.items);
                    refSchema.items = new ObjectBuilder({
                        allOf: items,
                        xml: { name: propXmlName },
                    });
                }
                // handel unwrapped decorator
                if (!hasUnwrappedDecorator) {
                    xmlObject.wrapped = true;
                }
            }
            if (!isArrayProperty && !refSchema.type && !isAttribute) {
                emitObject.allOf = new ArrayBuilder();
                emitObject.allOf.push(refSchema);
                xmlObject.name = xmlName;
            }
            if (isArrayProperty && hasUnwrappedDecorator) {
                // if wrapped is false, xml.name of the wrapping element is ignored.
                delete xmlObject.name;
            }
            // Attach xml schema to emitObject if not empty
            if (Object.keys(xmlObject).length !== 0) {
                emitObject.xml = xmlObject;
            }
        },
    };
}
function isXmlModelChecker(program, model, checked) {
    if (model.decorators && model.decorators.some((d) => d.definition?.namespace.name === "Xml")) {
        return true;
    }
    const xmlName = resolveEncodedName(program, model, "application/xml");
    if (xmlName && xmlName !== model.name) {
        return true;
    }
    if (model.kind === "ModelProperty") {
        const propModel = model.type;
        if (propModel && !checked.includes(propModel.name)) {
            checked.push(propModel.name);
            if (isXmlModelChecker(program, propModel, checked)) {
                return true;
            }
        }
    }
    if (model.kind === "Model") {
        for (const prop of model.properties.values()) {
            if (isXmlModelChecker(program, prop, checked)) {
                return true;
            }
            if (prop.type?.kind === "Model" && isArrayModelType(program, prop.type)) {
                const propValue = prop.type.indexer.value;
                const propModel = propValue;
                if (propModel && !checked.includes(propModel.name)) {
                    checked.push(propModel.name);
                    if (isXmlModelChecker(program, propModel, checked)) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
async function tryImportXml() {
    try {
        const module = await import('./index-CSeYPdTe.js');
        return module;
    }
    catch {
        return undefined;
    }
}

const defaultFileType = "yaml";
const defaultOptions = {
    "new-line": "lf",
    "omit-unreachable-types": false,
    "include-x-typespec-name": "never",
    "safeint-strategy": "int64",
};
async function $onEmit(context) {
    const options = resolveOptions(context);
    for (const specVersion of options.openapiVersions) {
        const emitter = createOAPIEmitter(context, options, specVersion);
        await emitter.emitOpenAPI();
    }
}
/**
 * Get the OpenAPI 3 document records from the given program. The documents are
 * returned as a JS object.
 *
 * @param program The program to emit to OpenAPI 3
 * @param options OpenAPI 3 emit options
 * @returns An array of OpenAPI 3 document records.
 */
async function getOpenAPI3(program, options = {}) {
    const context = {
        program,
        // this value doesn't matter for getting the OpenAPI3 objects
        emitterOutputDir: "tsp-output",
        options: options,
        getAssetEmitter(TypeEmitterClass) {
            return createAssetEmitter(program, TypeEmitterClass, this);
        },
    };
    const resolvedOptions = resolveOptions(context);
    const serviceRecords = [];
    for (const specVersion of resolvedOptions.openapiVersions) {
        const emitter = createOAPIEmitter(context, resolvedOptions, specVersion);
        serviceRecords.push(...(await emitter.getOpenAPI()));
    }
    return serviceRecords;
}
function findFileTypeFromFilename(filename) {
    if (filename === undefined) {
        return defaultFileType;
    }
    switch (getAnyExtensionFromPath(filename)) {
        case ".yaml":
        case ".yml":
            return "yaml";
        case ".json":
            return "json";
        default:
            return defaultFileType;
    }
}
function resolveOptions(context) {
    const resolvedOptions = { ...defaultOptions, ...context.options };
    const fileType = resolvedOptions["file-type"] ?? findFileTypeFromFilename(resolvedOptions["output-file"]);
    const outputFile = resolvedOptions["output-file"] ?? `openapi.{service-name}.{version}.${fileType}`;
    const openapiVersions = resolvedOptions["openapi-versions"] ?? ["3.0.0"];
    const specDir = openapiVersions.length > 1 ? "{openapi-version}" : "";
    return {
        fileType,
        newLine: resolvedOptions["new-line"],
        omitUnreachableTypes: resolvedOptions["omit-unreachable-types"],
        includeXTypeSpecName: resolvedOptions["include-x-typespec-name"],
        safeintStrategy: resolvedOptions["safeint-strategy"],
        outputFile: resolvePath(context.emitterOutputDir, specDir, outputFile),
        openapiVersions,
    };
}
function createOAPIEmitter(context, options, specVersion = "3.0.0") {
    const { applyEncoding, createRootDoc, createSchemaEmitter, getRawBinarySchema, isRawBinarySchema, } = getOpenApiSpecProps(specVersion);
    const program = context.program;
    let schemaEmitter;
    let root;
    let diagnostics;
    let currentService;
    let serviceAuth;
    // Get the service namespace string for use in name shortening
    let serviceNamespaceName;
    let currentPath;
    let metadataInfo;
    let visibilityUsage;
    // Map model properties that represent shared parameters to their parameter
    // definition that will go in #/components/parameters. Inlined parameters do not go in
    // this map.
    let params;
    // Keep track of models that have had properties spread into parameters. We won't
    // consider these unreferenced when emitting unreferenced types.
    let paramModels;
    // De-dupe the per-endpoint tags that will be added into the #/tags
    let tags;
    // The per-endpoint tags that will be added into the #/tags
    const tagsMetadata = {};
    const typeNameOptions = {
        // shorten type names by removing TypeSpec and service namespace
        namespaceFilter(ns) {
            const name = getNamespaceFullName(ns);
            return name !== serviceNamespaceName;
        },
    };
    return { emitOpenAPI, getOpenAPI };
    async function emitOpenAPI() {
        const services = await getOpenAPI();
        // first, emit diagnostics
        for (const serviceRecord of services) {
            if (serviceRecord.versioned) {
                for (const documentRecord of serviceRecord.versions) {
                    program.reportDiagnostics(documentRecord.diagnostics);
                }
            }
            else {
                program.reportDiagnostics(serviceRecord.diagnostics);
            }
        }
        if (program.compilerOptions.noEmit || program.hasError()) {
            return;
        }
        const multipleService = services.length > 1;
        for (const serviceRecord of services) {
            if (serviceRecord.versioned) {
                for (const documentRecord of serviceRecord.versions) {
                    await emitFile(program, {
                        path: resolveOutputFile(serviceRecord.service, multipleService, documentRecord.version),
                        content: serializeDocument(documentRecord.document, options.fileType),
                        newLine: options.newLine,
                    });
                }
            }
            else {
                await emitFile(program, {
                    path: resolveOutputFile(serviceRecord.service, multipleService),
                    content: serializeDocument(serviceRecord.document, options.fileType),
                    newLine: options.newLine,
                });
            }
        }
    }
    function initializeEmitter(service, allHttpAuthentications, defaultAuth, optionalDependencies, version) {
        diagnostics = createDiagnosticCollector();
        currentService = service;
        metadataInfo = createMetadataInfo(program, {
            canonicalVisibility: Visibility.Read,
            canShareProperty: (p) => isReadonlyProperty(program, p),
        });
        visibilityUsage = resolveVisibilityUsage(program, metadataInfo, service.type, options.omitUnreachableTypes);
        schemaEmitter = createSchemaEmitter({
            program,
            context,
            metadataInfo,
            visibilityUsage,
            options,
            optionalDependencies,
        });
        const securitySchemes = getOpenAPISecuritySchemes(allHttpAuthentications);
        const security = getOpenAPISecurity(defaultAuth);
        root = createRootDoc(program, service.type, version);
        if (security.length > 0) {
            root.security = security;
        }
        root.components.securitySchemes = securitySchemes;
        const servers = getServers(program, service.type);
        if (servers) {
            root.servers = resolveServers(servers);
        }
        attachExtensions(program, service.type, root);
        serviceNamespaceName = getNamespaceFullName(service.type);
        currentPath = root.paths;
        params = new Map();
        paramModels = new Set();
        tags = new Set();
        // Get Tags Metadata
        const metadata = getTagsMetadata(program, service.type);
        if (metadata) {
            for (const [name, tag] of Object.entries(metadata)) {
                const tagData = { name: name, ...tag };
                tagsMetadata[name] = tagData;
            }
        }
    }
    function isValidServerVariableType(program, type) {
        switch (type.kind) {
            case "String":
            case "Union":
            case "Scalar":
                return ignoreDiagnostics(program.checker.isTypeAssignableTo(
                // eslint-disable-next-line @typescript-eslint/no-deprecated
                type.projectionBase ?? type, program.checker.getStdType("string"), type));
            case "Enum":
                for (const member of type.members.values()) {
                    if (member.value && typeof member.value !== "string") {
                        return false;
                    }
                }
                return true;
            default:
                return false;
        }
    }
    function validateValidServerVariable(program, prop) {
        const isValid = isValidServerVariableType(program, prop.type);
        if (!isValid) {
            diagnostics.add(createDiagnostic({
                code: "invalid-server-variable",
                format: { propName: prop.name },
                target: prop,
            }));
        }
        return isValid;
    }
    function resolveServers(servers) {
        return servers.map((server) => {
            const variables = {};
            for (const [name, prop] of server.parameters) {
                if (!validateValidServerVariable(program, prop)) {
                    continue;
                }
                const variable = {
                    default: prop.defaultValue ? getDefaultValue(program, prop.defaultValue, prop) : "",
                    description: getDoc(program, prop),
                };
                if (prop.type.kind === "Enum") {
                    variable.enum = getSchemaValue(prop.type, Visibility.Read, "application/json")
                        .enum;
                }
                else if (prop.type.kind === "Union") {
                    variable.enum = getSchemaValue(prop.type, Visibility.Read, "application/json")
                        .enum;
                }
                else if (prop.type.kind === "String") {
                    variable.enum = [prop.type.value];
                }
                attachExtensions(program, prop, variable);
                variables[name] = variable;
            }
            return {
                url: server.url,
                description: server.description,
                variables,
            };
        });
    }
    async function getOpenAPI() {
        const serviceRecords = [];
        const services = listServices(program);
        if (services.length === 0) {
            services.push({ type: program.getGlobalNamespaceType() });
        }
        for (const service of services) {
            const versions = getVersioningMutators(program, service.type);
            if (versions === undefined) {
                const document = await getOpenApiFromVersion(service);
                if (document === undefined) {
                    // an error occurred producing this document, so don't return it
                    return serviceRecords;
                }
                serviceRecords.push({
                    service,
                    versioned: false,
                    document: document[0],
                    diagnostics: document[1],
                });
            }
            else if (versions.kind === "transient") {
                const document = await getVersionSnapshotDocument(service, versions.mutator);
                if (document === undefined) {
                    // an error occurred producing this document, so don't return it
                    return serviceRecords;
                }
                serviceRecords.push({
                    service,
                    versioned: false,
                    document: document[0],
                    diagnostics: document[1],
                });
            }
            else {
                // versioned spec
                const serviceRecord = {
                    service,
                    versioned: true,
                    versions: [],
                };
                serviceRecords.push(serviceRecord);
                for (const snapshot of versions.snapshots) {
                    const document = await getVersionSnapshotDocument(service, snapshot.mutator, snapshot.version?.value);
                    if (document === undefined) {
                        // an error occurred producing this document
                        continue;
                    }
                    serviceRecord.versions.push({
                        service,
                        version: snapshot.version.value,
                        document: document[0],
                        diagnostics: document[1],
                    });
                }
            }
        }
        return serviceRecords;
    }
    async function getVersionSnapshotDocument(service, mutator, version) {
        const subgraph = unsafe_mutateSubgraphWithNamespace(program, [mutator], service.type);
        compilerAssert(subgraph.type.kind === "Namespace", "Should not have mutated to another type");
        const document = await getOpenApiFromVersion(getService(program, subgraph.type), version);
        return document;
    }
    function resolveOutputFile(service, multipleService, version) {
        return interpolatePath(options.outputFile, {
            "openapi-version": specVersion,
            "service-name": multipleService ? getNamespaceFullName(service.type) : undefined,
            version,
        });
    }
    /**
     * Validates that common responses are consistent and returns the minimal set that describes the differences.
     */
    function deduplicateCommonResponses(statusCodeResponses) {
        const ref = statusCodeResponses[0];
        const sameTypeKind = statusCodeResponses.every((r) => r.type.kind === ref.type.kind);
        const sameTypeValue = statusCodeResponses.every((r) => r.type === ref.type);
        if (sameTypeKind && sameTypeValue) {
            // response is consistent and in all shared operations. Only need one copy.
            return [ref];
        }
        else {
            return statusCodeResponses;
        }
    }
    /**
     * Validates that common parameters are consistent and returns the minimal set that describes the differences.
     */
    function resolveSharedRouteParameters(ops) {
        const finalParams = [];
        const parameters = new Map();
        for (const op of ops) {
            for (const parameter of op.parameters.parameters) {
                const existing = parameters.get(parameter.name);
                if (existing) {
                    existing.push(parameter);
                }
                else {
                    parameters.set(parameter.name, [parameter]);
                }
            }
        }
        if (parameters.size === 0) {
            return [];
        }
        for (const sharedParams of parameters.values()) {
            const reference = sharedParams[0];
            const inAllOps = ops.length === sharedParams.length;
            const sameLocations = sharedParams.every((p) => p.type === reference.type);
            const sameOptionality = sharedParams.every((p) => p.param.optional === reference.param.optional);
            const sameTypeKind = sharedParams.every((p) => p.param.type.kind === reference.param.type.kind);
            const sameTypeValue = sharedParams.every((p) => p.param.type === reference.param.type);
            if (inAllOps && sameLocations && sameOptionality && sameTypeKind && sameTypeValue) {
                // param is consistent and in all shared operations. Only need one copy.
                finalParams.push(reference);
            }
            else if (!inAllOps && sameLocations && sameOptionality && sameTypeKind && sameTypeValue) {
                // param is consistent when used, but does not appear in all shared operations. Only need one copy, but it must be optional.
                reference.param.optional = true;
                finalParams.push(reference);
            }
            else if (inAllOps && !(sameLocations && sameOptionality && sameTypeKind)) {
                // param is in all shared operations, but is not consistent. Need multiple copies, which must be optional.
                // exception allowed when the params only differ by their value (e.g. string enum values)
                sharedParams.forEach((p) => {
                    p.param.optional = true;
                });
                finalParams.push(...sharedParams);
            }
            else {
                finalParams.push(...sharedParams);
            }
        }
        return finalParams;
    }
    function buildSharedOperation(operations) {
        return {
            kind: "shared",
            operations: operations,
        };
    }
    /**
     * Groups HttpOperations together if they share the same route.
     */
    function resolveOperations(operations) {
        const result = [];
        const pathMap = new Map();
        operations.forEach((op) => {
            // we don't emit overloads anyhow so emit them from grouping
            if (op.overloading !== undefined && isOverloadSameEndpoint(op)) {
                return;
            }
            const opKey = `${op.verb}|${op.path}`;
            pathMap.has(opKey) ? pathMap.get(opKey).push(op) : pathMap.set(opKey, [op]);
        });
        // now push either the singular HttpOperations or the constructed SharedHttpOperations
        for (const [_, ops] of pathMap) {
            if (ops.length === 1) {
                result.push(ops[0]);
            }
            else {
                result.push(buildSharedOperation(ops));
            }
        }
        return result;
    }
    async function getOpenApiFromVersion(service, version) {
        try {
            const httpService = ignoreDiagnostics(getHttpService(program, service.type));
            const auth = (serviceAuth = resolveAuthentication(httpService));
            const xmlModule = await resolveXmlModule();
            const jsonSchemaModule = await resolveJsonSchemaModule();
            initializeEmitter(service, auth.schemes, auth.defaultAuth, { xmlModule, jsonSchemaModule }, version);
            reportIfNoRoutes(program, httpService.operations);
            for (const op of resolveOperations(httpService.operations)) {
                const result = getOperationOrSharedOperation(op);
                if (result) {
                    const { operation, path, verb } = result;
                    currentPath[path] ??= {};
                    currentPath[path][verb] = operation;
                }
            }
            emitParameters();
            emitSchemas(service.type);
            emitTags();
            // Clean up empty entries
            if (root.components) {
                for (const elem of Object.keys(root.components)) {
                    if (Object.keys(root.components[elem]).length === 0) {
                        delete root.components[elem];
                    }
                }
            }
            return [root, diagnostics.diagnostics];
        }
        catch (err) {
            if (err instanceof ErrorTypeFoundError) {
                // Return early, there must be a parse error if an ErrorType was
                // inserted into the TypeSpec output
                return;
            }
            else {
                throw err;
            }
        }
    }
    function joinOps(operations, func, joinChar) {
        const values = operations
            .map((op) => func(program, op.operation))
            .filter((op) => op !== undefined);
        if (values.length) {
            return values.join(joinChar);
        }
        else {
            return undefined;
        }
    }
    function computeSharedOperationId(shared) {
        return shared.operations.map((op) => resolveOperationId(program, op.operation)).join("_");
    }
    function getOperationOrSharedOperation(operation) {
        if (isSharedHttpOperation(operation)) {
            return getSharedOperation(operation);
        }
        else {
            return getOperation(operation);
        }
    }
    function getSharedOperation(shared) {
        const operations = shared.operations;
        const verb = operations[0].verb;
        const path = operations[0].path;
        const examples = resolveOperationExamples(program, shared);
        const oai3Operation = {
            operationId: computeSharedOperationId(shared),
            parameters: [],
            description: joinOps(operations, getDoc, " "),
            summary: joinOps(operations, getSummary, " "),
            responses: getSharedResponses(shared, examples),
        };
        for (const op of operations) {
            applyExternalDocs(op.operation, oai3Operation);
            attachExtensions(program, op.operation, oai3Operation);
            if (isDeprecated(program, op.operation)) {
                oai3Operation.deprecated = true;
            }
        }
        for (const op of operations) {
            const opTags = getAllTags(program, op.operation);
            if (opTags) {
                const currentTags = oai3Operation.tags;
                if (currentTags) {
                    // combine tags but eliminate duplicates
                    oai3Operation.tags = [...new Set([...currentTags, ...opTags])];
                }
                else {
                    oai3Operation.tags = opTags;
                }
                for (const tag of opTags) {
                    // Add to root tags if not already there
                    tags.add(tag);
                }
            }
        }
        // Error out if shared routes do not have consistent `@parameterVisibility`. We can
        // lift this restriction in the future if a use case develops.
        const visibilities = operations.map((op) => resolveRequestVisibility(program, op.operation, verb));
        if (visibilities.some((v) => v !== visibilities[0])) {
            diagnostics.add(createDiagnostic({
                code: "inconsistent-shared-route-request-visibility",
                target: operations[0].operation,
            }));
        }
        const visibility = visibilities[0];
        oai3Operation.parameters = getEndpointParameters(resolveSharedRouteParameters(operations), visibility);
        const bodies = [
            ...new Set(operations.map((op) => op.parameters.body).filter((x) => x !== undefined)),
        ];
        {
            oai3Operation.requestBody = getRequestBody(bodies, visibility, examples);
        }
        const authReference = serviceAuth.operationsAuth.get(shared.operations[0].operation);
        if (authReference) {
            oai3Operation.security = getEndpointSecurity(authReference);
        }
        return { operation: oai3Operation, verb, path };
    }
    function getOperation(operation) {
        const { path: fullPath, operation: op, verb, parameters } = operation;
        // If path contains a query string, issue msg and don't emit this endpoint
        if (fullPath.indexOf("?") > 0) {
            diagnostics.add(createDiagnostic({ code: "path-query", target: op }));
            return undefined;
        }
        const visibility = resolveRequestVisibility(program, operation.operation, verb);
        const examples = resolveOperationExamples(program, operation);
        const oai3Operation = {
            operationId: resolveOperationId(program, operation.operation),
            summary: getSummary(program, operation.operation),
            description: getDoc(program, operation.operation),
            parameters: getEndpointParameters(parameters.parameters, visibility),
            responses: getResponses(operation, operation.responses, examples),
        };
        const currentTags = getAllTags(program, op);
        if (currentTags) {
            oai3Operation.tags = currentTags;
            for (const tag of currentTags) {
                // Add to root tags if not already there
                tags.add(tag);
            }
        }
        applyExternalDocs(op, oai3Operation);
        // Set up basic endpoint fields
        if (parameters.body) {
            oai3Operation.requestBody = getRequestBody(parameters.body && [parameters.body], visibility, examples);
        }
        const authReference = serviceAuth.operationsAuth.get(operation.operation);
        if (authReference) {
            oai3Operation.security = getEndpointSecurity(authReference);
        }
        if (isDeprecated(program, op)) {
            oai3Operation.deprecated = true;
        }
        attachExtensions(program, op, oai3Operation);
        return { operation: oai3Operation, path: fullPath, verb };
    }
    function getSharedResponses(operation, examples) {
        const responseMap = new Map();
        for (const op of operation.operations) {
            for (const response of op.responses) {
                const statusCodes = diagnostics.pipe(getOpenAPI3StatusCodes(program, response.statusCodes, op.operation));
                for (const statusCode of statusCodes) {
                    if (responseMap.has(statusCode)) {
                        responseMap.get(statusCode).push(response);
                    }
                    else {
                        responseMap.set(statusCode, [response]);
                    }
                }
            }
        }
        const result = {};
        for (const [statusCode, statusCodeResponses] of responseMap) {
            const dedupeResponses = deduplicateCommonResponses(statusCodeResponses);
            result[statusCode] = getResponseForStatusCode(operation, statusCode, dedupeResponses, examples);
        }
        return result;
    }
    function getResponses(operation, responses, examples) {
        const result = {};
        for (const response of responses) {
            for (const statusCode of diagnostics.pipe(getOpenAPI3StatusCodes(program, response.statusCodes, response.type))) {
                result[statusCode] = getResponseForStatusCode(operation, statusCode, [response], examples);
            }
        }
        return result;
    }
    function isBinaryPayload(body, contentType) {
        return (body.kind === "Scalar" &&
            body.name === "bytes" &&
            contentType !== "application/json" &&
            contentType !== "text/plain");
    }
    function getResponseForStatusCode(operation, statusCode, responses, examples) {
        const openApiResponse = {
            description: "",
        };
        const schemaMap = new Map();
        for (const response of responses) {
            const refUrl = getRef(program, response.type);
            if (refUrl) {
                return { $ref: refUrl };
            }
            if (response.description && response.description !== openApiResponse.description) {
                openApiResponse.description = openApiResponse.description
                    ? `${openApiResponse.description} ${response.description}`
                    : response.description;
            }
            emitResponseHeaders(openApiResponse, response.responses, response.type);
            emitResponseContent(operation, openApiResponse, response.responses, statusCode, examples, schemaMap);
            if (!openApiResponse.description) {
                openApiResponse.description = getResponseDescriptionForStatusCode(statusCode);
            }
        }
        return openApiResponse;
    }
    function emitResponseHeaders(obj, responses, target) {
        for (const data of responses) {
            if (data.headers && Object.keys(data.headers).length > 0) {
                obj.headers ??= {};
                // OpenAPI can't represent different headers per content type.
                // So we merge headers here, and report any duplicates unless they are identical
                for (const [key, value] of Object.entries(data.headers)) {
                    const headerVal = getResponseHeader(value);
                    const existing = obj.headers[key];
                    if (existing) {
                        if (!deepEquals(existing, headerVal)) {
                            diagnostics.add(createDiagnostic({
                                code: "duplicate-header",
                                format: { header: key },
                                target: target,
                            }));
                        }
                        continue;
                    }
                    obj.headers[key] = headerVal;
                }
            }
        }
    }
    function emitResponseContent(operation, obj, responses, statusCode, examples, schemaMap = undefined) {
        schemaMap ??= new Map();
        for (const data of responses) {
            if (data.body === undefined || isVoidType(data.body.type)) {
                continue;
            }
            obj.content ??= {};
            for (const contentType of data.body.contentTypes) {
                const contents = getBodyContentEntry(data.body, Visibility.Read, contentType, examples.responses[statusCode]?.[contentType]);
                if (schemaMap.has(contentType)) {
                    schemaMap.get(contentType).push(contents);
                }
                else {
                    schemaMap.set(contentType, [contents]);
                }
            }
            for (const [contentType, contents] of schemaMap) {
                if (contents.length === 1) {
                    obj.content[contentType] = contents[0];
                }
                else {
                    obj.content[contentType] = {
                        schema: { anyOf: contents.map((x) => x.schema) },
                    };
                }
            }
        }
    }
    function getResponseDescriptionForStatusCode(statusCode) {
        if (statusCode === "default") {
            return "An unexpected error response.";
        }
        return getStatusCodeDescription(statusCode) ?? "unknown";
    }
    function getResponseHeader(prop) {
        return getOpenAPIParameterBase(prop, Visibility.Read);
    }
    function callSchemaEmitter(type, visibility, ignoreMetadataAnnotations, contentType) {
        const result = emitTypeWithSchemaEmitter(type, visibility, ignoreMetadataAnnotations, contentType);
        switch (result.kind) {
            case "code":
                return result.value;
            case "declaration":
                return { $ref: `#/components/schemas/${result.name}` };
            case "circular":
                diagnostics.add(createDiagnostic({
                    code: "inline-cycle",
                    format: { type: getOpenAPITypeName(program, type, typeNameOptions) },
                    target: type,
                }));
                return {};
            case "none":
                return {};
        }
    }
    function getSchemaValue(type, visibility, contentType) {
        const result = emitTypeWithSchemaEmitter(type, visibility, false, contentType);
        switch (result.kind) {
            case "code":
            case "declaration":
                return result.value;
            case "circular":
                diagnostics.add(createDiagnostic({
                    code: "inline-cycle",
                    format: { type: getOpenAPITypeName(program, type, typeNameOptions) },
                    target: type,
                }));
                return {};
            case "none":
                return {};
        }
    }
    function emitTypeWithSchemaEmitter(type, visibility, ignoreMetadataAnnotations, contentType) {
        if (!metadataInfo.isTransformed(type, visibility)) {
            visibility = Visibility.Read;
        }
        contentType = contentType === "application/json" ? undefined : contentType;
        return schemaEmitter.emitType(type, {
            referenceContext: {
                visibility,
                serviceNamespaceName: serviceNamespaceName,
                ignoreMetadataAnnotations: ignoreMetadataAnnotations ?? false,
                contentType,
            },
        });
    }
    function getBodyContentEntry(body, visibility, contentType, examples) {
        const isBinary = isBinaryPayload(body.type, contentType);
        if (isBinary) {
            return { schema: getRawBinarySchema(contentType) };
        }
        const oai3Examples = examples && getExampleOrExamples(program, examples);
        switch (body.bodyKind) {
            case "single":
                return {
                    schema: getSchemaForSingleBody(body.type, visibility, body.isExplicit && body.containsMetadataAnnotations, contentType.startsWith("multipart/") ? contentType : undefined),
                    ...oai3Examples,
                };
            case "multipart":
                return {
                    ...getBodyContentForMultipartBody(body, visibility, contentType),
                    ...oai3Examples,
                };
        }
    }
    function getSchemaForSingleBody(type, visibility, ignoreMetadataAnnotations, multipart) {
        const effectiveType = metadataInfo.getEffectivePayloadType(type, visibility);
        return callSchemaEmitter(effectiveType, visibility, ignoreMetadataAnnotations, multipart ?? "application/json");
    }
    function getBodyContentForMultipartBody(body, visibility, contentType) {
        const properties = {};
        const requiredProperties = [];
        const encodings = {};
        for (const [partIndex, part] of body.parts.entries()) {
            const partName = part.name ?? `part${partIndex}`;
            let schema = isBytesKeptRaw(program, part.body.type)
                ? getRawBinarySchema()
                : getSchemaForSingleBody(part.body.type, visibility, part.body.isExplicit && part.body.containsMetadataAnnotations, part.body.type.kind === "Union" ? contentType : undefined);
            if (part.multi) {
                schema = {
                    type: "array",
                    items: schema,
                };
            }
            properties[partName] = schema;
            const encoding = resolveEncodingForMultipartPart(part, visibility, schema);
            if (encoding) {
                encodings[partName] = encoding;
            }
            if (!part.optional) {
                requiredProperties.push(partName);
            }
        }
        const schema = {
            type: "object",
            properties,
            required: requiredProperties,
        };
        const name = "name" in body.type && body.type.name !== ""
            ? getOpenAPITypeName(program, body.type, typeNameOptions)
            : undefined;
        if (name) {
            root.components.schemas[name] = schema;
        }
        const result = {
            schema: name ? { $ref: "#/components/schemas/" + name } : schema,
        };
        if (Object.keys(encodings).length > 0) {
            result.encoding = encodings;
        }
        return result;
    }
    function resolveEncodingForMultipartPart(part, visibility, schema) {
        const encoding = {};
        if (!isDefaultContentTypeForOpenAPI3(part.body.contentTypes, schema)) {
            encoding.contentType = part.body.contentTypes.join(", ");
        }
        const headers = part.headers;
        if (headers.length > 0) {
            encoding.headers = {};
            for (const header of headers) {
                const schema = getOpenAPIParameterBase(header.property, visibility);
                if (schema !== undefined) {
                    encoding.headers[header.options.name] = schema;
                }
            }
        }
        if (Object.keys(encoding).length === 0) {
            return undefined;
        }
        return encoding;
    }
    function isDefaultContentTypeForOpenAPI3(contentTypes, schema) {
        if (contentTypes.length === 0) {
            return false;
        }
        if (contentTypes.length > 1) {
            return false;
        }
        const contentType = contentTypes[0];
        switch (contentType) {
            case "text/plain":
                return schema.type === "string" || schema.type === "number";
            case "application/octet-stream":
                return (isRawBinarySchema(schema) ||
                    (schema.type === "array" && !!schema.items && isRawBinarySchema(schema.items)));
            case "application/json":
                return schema.type === "object";
        }
        return false;
    }
    function getParameter(parameter, visibility) {
        const param = {
            name: parameter.name,
            in: parameter.type,
            ...getOpenAPIParameterBase(parameter.param, visibility),
        };
        const attributes = getParameterAttributes(parameter);
        if (attributes === undefined) {
            param.schema = {
                type: "string",
            };
        }
        else {
            Object.assign(param, attributes);
        }
        if (isDeprecated(program, parameter.param)) {
            param.deprecated = true;
        }
        return param;
    }
    function getEndpointParameters(parameters, visibility) {
        const result = [];
        for (const httpOpParam of parameters) {
            if (params.has(httpOpParam.param)) {
                result.push(params.get(httpOpParam.param));
                continue;
            }
            // eslint-disable-next-line @typescript-eslint/no-deprecated
            if (httpOpParam.type === "header" && isContentTypeHeader(program, httpOpParam.param)) {
                continue;
            }
            const param = getParameterOrRef(httpOpParam, visibility);
            if (param) {
                const existing = result.find((x) => !("$ref" in param) && !("$ref" in x) && x.name === param.name && x.in === param.in);
                if (existing && !("$ref" in param) && !("$ref" in existing)) {
                    mergeOpenApiParameters(existing, param);
                }
                else {
                    result.push(param);
                }
            }
        }
        return result;
    }
    function getRequestBody(bodies, visibility, examples) {
        if (bodies === undefined || bodies.every((x) => isVoidType(x.type))) {
            return undefined;
        }
        const requestBody = {
            required: bodies.every((body) => (body.property ? !body.property.optional : true)),
            content: {},
        };
        const schemaMap = new Map();
        for (const body of bodies.filter((x) => !isVoidType(x.type))) {
            const desc = body.property ? getDoc(program, body.property) : undefined;
            if (desc) {
                requestBody.description = requestBody.description
                    ? `${requestBody.description} ${desc}`
                    : desc;
            }
            const contentTypes = body.contentTypes.length > 0 ? body.contentTypes : ["application/json"];
            for (const contentType of contentTypes) {
                const existing = schemaMap.get(contentType);
                const entry = getBodyContentEntry(body, visibility, contentType, examples.requestBody[contentType]);
                if (existing) {
                    existing.push(entry);
                }
                else {
                    schemaMap.set(contentType, [entry]);
                }
            }
        }
        for (const [contentType, schemaArray] of schemaMap) {
            if (schemaArray.length === 1) {
                requestBody.content[contentType] = schemaArray[0];
            }
            else {
                requestBody.content[contentType] = {
                    schema: { anyOf: schemaArray.map((x) => x.schema).filter((x) => x !== undefined) },
                    encoding: schemaArray.find((x) => x.encoding)?.encoding,
                };
            }
        }
        return requestBody;
    }
    function getParameterOrRef(parameter, visibility) {
        if (isNeverType(parameter.param.type)) {
            return undefined;
        }
        let spreadParam = false;
        let property = parameter.param;
        if (property.sourceProperty) {
            // chase our sources all the way back to the first place this property
            // was defined.
            spreadParam = true;
            property = property.sourceProperty;
            while (property.sourceProperty) {
                property = property.sourceProperty;
            }
        }
        const refUrl = getRef(program, property);
        if (refUrl) {
            return {
                $ref: refUrl,
            };
        }
        if (params.has(property)) {
            return params.get(property);
        }
        const param = getParameter(parameter, visibility);
        // only parameters inherited by spreading from non-inlined type are shared in #/components/parameters
        if (spreadParam && property.model && !shouldInline(program, property.model)) {
            params.set(property, param);
            paramModels.add(property.model);
        }
        return param;
    }
    function getOpenAPIParameterBase(param, visibility) {
        const typeSchema = getSchemaForType(param.type, visibility);
        if (!typeSchema) {
            return undefined;
        }
        const schema = applyEncoding(program, param, applyIntrinsicDecorators(param, typeSchema), options);
        if (param.defaultValue) {
            schema.default = getDefaultValue(program, param.defaultValue, param);
        }
        // Description is already provided in the parameter itself.
        delete schema.description;
        const oaiParam = {
            required: !param.optional,
            description: getDoc(program, param),
            schema,
        };
        attachExtensions(program, param, oaiParam);
        return oaiParam;
    }
    function mergeOpenApiParameters(target, apply) {
        if (target.schema) {
            const schema = target.schema;
            if (schema.enum && apply.schema.enum) {
                schema.enum = [...new Set([...schema.enum, ...apply.schema.enum])];
            }
            target.schema = schema;
        }
        else {
            Object.assign(target, apply);
        }
        return target;
    }
    function getParameterAttributes(parameter) {
        switch (parameter.type) {
            case "header":
                return mapHeaderParameterFormat(parameter);
            case "cookie":
                // style and explode options are omitted from cookies
                // https://github.com/microsoft/typespec/pull/4761#discussion_r1803365689
                return { explode: false };
            case "query":
                return getQueryParameterAttributes(parameter);
            case "path":
                return getPathParameterAttributes(parameter);
        }
    }
    function getPathParameterAttributes(parameter) {
        if (parameter.allowReserved) {
            diagnostics.add(createDiagnostic({
                code: "path-reserved-expansion",
                target: parameter.param,
            }));
        }
        const attributes = {};
        if (parameter.explode) {
            attributes.explode = true;
        }
        switch (parameter.style) {
            case "label":
                attributes.style = "label";
                break;
            case "matrix":
                attributes.style = "matrix";
                break;
            case "simple":
                break;
            default:
                diagnostics.add(createDiagnostic({
                    code: "invalid-style",
                    format: { style: parameter.style, paramType: "path" },
                    target: parameter.param,
                }));
        }
        return attributes;
    }
    function getQueryParameterAttributes(parameter) {
        const attributes = {};
        if (parameter.explode !== true) {
            // For query parameters(style: form) the default is explode: true https://spec.openapis.org/oas/v3.0.2#fixed-fields-9
            attributes.explode = false;
        }
        // eslint-disable-next-line @typescript-eslint/no-deprecated
        switch (parameter.format) {
            case "ssv":
                return { style: "spaceDelimited", explode: false };
            case "pipes":
                return { style: "pipeDelimited", explode: false };
            case "csv":
            case "simple":
                return { explode: false };
            case undefined:
            case "multi":
            case "form":
                return attributes;
            default:
                diagnostics.add(createDiagnostic({
                    code: "invalid-format",
                    format: {
                        paramType: "query",
                        // eslint-disable-next-line @typescript-eslint/no-deprecated
                        value: parameter.format,
                    },
                    target: parameter.param,
                }));
                return undefined;
        }
    }
    function mapHeaderParameterFormat(parameter) {
        switch (parameter.format) {
            case undefined:
                return {};
            case "csv":
            case "simple":
                return { style: "simple" };
            default:
                diagnostics.add(createDiagnostic({
                    code: "invalid-format",
                    format: {
                        paramType: "header",
                        value: parameter.format,
                    },
                    target: parameter.param,
                }));
                return undefined;
        }
    }
    function validateComponentFixedFieldKey(type, name) {
        const pattern = /^[a-zA-Z0-9.\-_]+$/;
        if (!pattern.test(name)) {
            program.reportDiagnostic(createDiagnostic({
                code: "invalid-component-fixed-field-key",
                format: {
                    value: name,
                },
                target: type,
            }));
        }
    }
    function emitParameters() {
        for (const [property, param] of params) {
            const key = getParameterKey(program, property, param, root.components.parameters, typeNameOptions);
            validateComponentFixedFieldKey(property, key);
            root.components.parameters[key] = { ...param };
            for (const key of Object.keys(param)) {
                delete param[key];
            }
            param.$ref = "#/components/parameters/" + encodeURIComponent(key);
        }
    }
    function emitSchemas(serviceNamespace) {
        if (!options.omitUnreachableTypes) {
            processUnreferencedSchemas();
        }
        const files = schemaEmitter.getSourceFiles();
        if (files.length > 0) {
            compilerAssert(files.length === 1, `Should only have a single file for now but got ${files.length}`);
            const schemas = root.components.schemas;
            const declarations = files[0].globalScope.declarations;
            for (const declaration of declarations) {
                validateComponentFixedFieldKey(serviceNamespace, declaration.name);
                schemas[declaration.name] = declaration.value;
            }
        }
        function processUnreferencedSchemas() {
            const addSchema = (type) => {
                if (isOrExtendsHttpFile(program, type)) {
                    return;
                }
                if (visibilityUsage.isUnreachable(type) &&
                    !paramModels.has(type) &&
                    !shouldInline(program, type)) {
                    callSchemaEmitter(type, Visibility.All);
                }
            };
            const skipSubNamespaces = isGlobalNamespace(program, serviceNamespace);
            navigateTypesInNamespace(serviceNamespace, {
                model: addSchema,
                scalar: addSchema,
                enum: addSchema,
                union: addSchema,
            }, { skipSubNamespaces });
        }
    }
    function emitTags() {
        // emit Tag from op
        for (const tag of tags) {
            if (!tagsMetadata[tag]) {
                root.tags.push({ name: tag });
            }
        }
        for (const key in tagsMetadata) {
            root.tags.push(tagsMetadata[key]);
        }
    }
    function getSchemaForType(type, visibility) {
        return callSchemaEmitter(type, visibility);
    }
    function attachExtensions(program, type, emitObject) {
        // Attach any OpenAPI extensions
        const extensions = getExtensions$1(program, type);
        if (extensions) {
            for (const key of extensions.keys()) {
                emitObject[key] = extensions.get(key);
            }
        }
    }
    function applyIntrinsicDecorators(typespecType, target) {
        const newTarget = { ...target };
        const docStr = getDoc(program, typespecType);
        if (docStr) {
            newTarget.description = docStr;
        }
        const formatStr = getFormat(program, typespecType);
        if (formatStr) {
            newTarget.format = formatStr;
        }
        const pattern = getPattern(program, typespecType);
        if (pattern) {
            newTarget.pattern = pattern;
        }
        const minLength = getMinLength(program, typespecType);
        if (minLength !== undefined) {
            newTarget.minLength = minLength;
        }
        const maxLength = getMaxLength(program, typespecType);
        if (maxLength !== undefined) {
            newTarget.maxLength = maxLength;
        }
        const minValue = getMinValue(program, typespecType);
        if (minValue !== undefined) {
            newTarget.minimum = minValue;
        }
        const minValueExclusive = getMinValueExclusive(program, typespecType);
        if (minValueExclusive !== undefined) {
            newTarget.minimum = minValueExclusive;
            newTarget.exclusiveMinimum = true;
        }
        const maxValue = getMaxValue(program, typespecType);
        if (maxValue !== undefined) {
            newTarget.maximum = maxValue;
        }
        const maxValueExclusive = getMaxValueExclusive(program, typespecType);
        if (maxValueExclusive !== undefined) {
            newTarget.maximum = maxValueExclusive;
            newTarget.exclusiveMaximum = true;
        }
        const minItems = getMinItems(program, typespecType);
        if (!target.minItems && minItems !== undefined) {
            newTarget.minItems = minItems;
        }
        const maxItems = getMaxItems(program, typespecType);
        if (!target.maxItems && maxItems !== undefined) {
            newTarget.maxItems = maxItems;
        }
        if (isSecret(program, typespecType)) {
            newTarget.format = "password";
        }
        const title = getSummary(program, typespecType);
        if (title) {
            newTarget.title = title;
        }
        const values = getKnownValues(program, typespecType);
        if (values) {
            return {
                oneOf: [newTarget, callSchemaEmitter(values, Visibility.Read, false, "application/json")],
            };
        }
        attachExtensions(program, typespecType, newTarget);
        return newTarget;
    }
    function applyExternalDocs(typespecType, target) {
        const externalDocs = getExternalDocs(program, typespecType);
        if (externalDocs) {
            target.externalDocs = externalDocs;
        }
    }
    function getOpenAPISecuritySchemes(httpAuthentications) {
        const schemes = {};
        for (const httpAuth of httpAuthentications) {
            const scheme = getOpenAPI3Scheme(httpAuth);
            if (scheme) {
                schemes[httpAuth.id] = scheme;
            }
        }
        return schemes;
    }
    function getOpenAPISecurity(authReference) {
        const security = authReference.options.map((authOption) => {
            const securityOption = {};
            for (const httpAuthRef of authOption.all) {
                switch (httpAuthRef.kind) {
                    case "noAuth":
                        // should emit "{}" as a security option https://github.com/OAI/OpenAPI-Specification/issues/14#issuecomment-297457320
                        continue;
                    case "oauth2":
                        securityOption[httpAuthRef.auth.id] = httpAuthRef.scopes;
                        continue;
                    default:
                        securityOption[httpAuthRef.auth.id] = [];
                }
            }
            return securityOption;
        });
        return security;
    }
    function getEndpointSecurity(authReference) {
        const security = getOpenAPISecurity(authReference);
        if (deepEquals(security, root.security)) {
            return undefined;
        }
        if (security.length > 0) {
            return security;
        }
        return undefined;
    }
    function getOpenAPI3Scheme(auth) {
        const scheme = getOpenAPI3SchemeInternal(auth);
        if (scheme) {
            attachExtensions(program, auth.model, scheme);
        }
        return scheme;
    }
    function getOpenAPI3SchemeInternal(auth) {
        switch (auth.type) {
            case "http":
                return { type: "http", scheme: auth.scheme, description: auth.description };
            case "apiKey":
                return { type: "apiKey", in: auth.in, name: auth.name, description: auth.description };
            case "oauth2":
                const flows = {};
                const scopes = [];
                for (const flow of auth.flows) {
                    scopes.push(...flow.scopes.map((x) => x.value));
                    flows[flow.type] = {
                        authorizationUrl: flow.authorizationUrl,
                        tokenUrl: flow.tokenUrl,
                        refreshUrl: flow.refreshUrl,
                        scopes: Object.fromEntries(flow.scopes.map((x) => [x.value, x.description ?? ""])),
                    };
                }
                return { type: "oauth2", flows, description: auth.description };
            case "openIdConnect":
                return {
                    type: "openIdConnect",
                    openIdConnectUrl: auth.openIdConnectUrl,
                    description: auth.description,
                };
            case "noAuth":
                return undefined;
            default:
                diagnostics.add(createDiagnostic({
                    code: "unsupported-auth",
                    format: { authType: auth.type },
                    target: currentService.type,
                }));
                return undefined;
        }
    }
}
function serializeDocument(root, fileType) {
    sortOpenAPIDocument(root);
    switch (fileType) {
        case "json":
            return prettierOutput(JSON.stringify(root, null, 2));
        case "yaml":
            return stringify(root, {
                singleQuote: true,
                aliasDuplicateObjects: false,
                lineWidth: 0,
                compat: "yaml-1.1",
            });
    }
}
function prettierOutput(output) {
    return output + "\n";
}
class ErrorTypeFoundError extends Error {
    constructor() {
        super("Error type found in evaluated TypeSpec output");
    }
}
function sortObjectByKeys(obj) {
    return Object.keys(obj)
        .sort()
        .reduce((sortedObj, key) => {
        sortedObj[key] = obj[key];
        return sortedObj;
    }, {});
}
function sortOpenAPIDocument(doc) {
    doc.paths = sortObjectByKeys(doc.paths);
    if (doc.components?.schemas) {
        doc.components.schemas = sortObjectByKeys(doc.components.schemas);
    }
    if (doc.components?.parameters) {
        doc.components.parameters = sortObjectByKeys(doc.components.parameters);
    }
}

/** @internal */
const $decorators = {
    "TypeSpec.OpenAPI": {
        useRef: $useRef,
        oneOf: $oneOf,
    },
};

var f1 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	$decorators: $decorators,
	$lib: $lib
});

const namespace = "TypeSpec.OpenAPI";

var f0 = /*#__PURE__*/Object.freeze({
	__proto__: null,
	$decorators: $decorators,
	$lib: $lib,
	$onEmit: $onEmit,
	$oneOf: $oneOf,
	$useRef: $useRef,
	convertOpenAPI3Document: convertOpenAPI3Document,
	getOneOf: getOneOf,
	getOpenAPI3: getOpenAPI3,
	getRef: getRef,
	namespace: namespace,
	resolveOptions: resolveOptions
});

const TypeSpecJSSources = {
"dist/src/index.js": f0,
"dist/src/tsp-index.js": f1,
};
const TypeSpecSources = {
  "package.json": "{\"name\":\"@typespec/openapi3\",\"version\":\"0.65.0\",\"author\":\"Microsoft Corporation\",\"description\":\"TypeSpec library for emitting OpenAPI 3.0 from the TypeSpec REST protocol binding and converting OpenAPI3 to TypeSpec\",\"homepage\":\"https://typespec.io\",\"readme\":\"https://github.com/microsoft/typespec/blob/main/README.md\",\"license\":\"MIT\",\"repository\":{\"type\":\"git\",\"url\":\"git+https://github.com/microsoft/typespec.git\"},\"bugs\":{\"url\":\"https://github.com/microsoft/typespec/issues\"},\"keywords\":[\"typespec\"],\"bin\":{\"tsp-openapi3\":\"cmd/tsp-openapi3.js\"},\"type\":\"module\",\"main\":\"dist/src/index.js\",\"tspMain\":\"lib/main.tsp\",\"exports\":{\".\":{\"typespec\":\"./lib/main.tsp\",\"types\":\"./dist/src/index.d.ts\",\"default\":\"./dist/src/index.js\"},\"./testing\":{\"types\":\"./dist/src/testing/index.d.ts\",\"default\":\"./dist/src/testing/index.js\"}},\"engines\":{\"node\":\">=18.0.0\"},\"scripts\":{\"clean\":\"rimraf ./dist ./temp\",\"build\":\"npm run gen-version && npm run gen-extern-signature && tsc -p . && npm run lint-typespec-library\",\"watch\":\"tsc -p . --watch\",\"gen-extern-signature\":\"tspd --enable-experimental gen-extern-signature .\",\"lint-typespec-library\":\"tsp compile . --warn-as-error --import @typespec/library-linter --no-emit\",\"test\":\"vitest run\",\"test:watch\":\"vitest -w\",\"test:ui\":\"vitest --ui\",\"test:ci\":\"vitest run --coverage --reporter=junit --reporter=default\",\"lint\":\"eslint . --max-warnings=0\",\"lint:fix\":\"eslint . --fix\",\"regen-docs\":\"tspd doc .  --enable-experimental  --output-dir ../../website/src/content/docs/docs/emitters/openapi3/reference\",\"regen-specs\":\"cross-env RECORD=true vitest run\",\"gen-version\":\"node scripts/generate-version.js\"},\"files\":[\"lib/*.tsp\",\"dist/**\",\"!dist/test/**\"],\"dependencies\":{\"@apidevtools/swagger-parser\":\"~10.1.1\",\"openapi-types\":\"~12.1.3\",\"yaml\":\"~2.7.0\"},\"peerDependencies\":{\"@typespec/compiler\":\"workspace:~\",\"@typespec/http\":\"workspace:~\",\"@typespec/json-schema\":\"workspace:~\",\"@typespec/openapi\":\"workspace:~\",\"@typespec/versioning\":\"workspace:~\"},\"peerDependenciesMeta\":{\"@typespec/json-schema\":{\"optional\":true},\"@typespec/xml\":{\"optional\":true}},\"devDependencies\":{\"@types/node\":\"~22.10.10\",\"@types/yargs\":\"~17.0.33\",\"@typespec/compiler\":\"workspace:~\",\"@typespec/http\":\"workspace:~\",\"@typespec/json-schema\":\"workspace:~\",\"@typespec/library-linter\":\"workspace:~\",\"@typespec/openapi\":\"workspace:~\",\"@typespec/rest\":\"workspace:~\",\"@typespec/tspd\":\"workspace:~\",\"@typespec/versioning\":\"workspace:~\",\"@typespec/xml\":\"workspace:~\",\"@vitest/coverage-v8\":\"^3.0.4\",\"@vitest/ui\":\"^3.0.3\",\"c8\":\"^10.1.3\",\"cross-env\":\"~7.0.3\",\"rimraf\":\"~6.0.1\",\"typescript\":\"~5.7.3\",\"vitest\":\"^3.0.5\"}}",
  "../compiler/lib/intrinsics.tsp": "import \"../dist/src/lib/intrinsic/tsp-index.js\";\nimport \"./prototypes.tsp\";\n\n// This file contains all the intrinsic types of typespec. Everything here will always be loaded\nnamespace TypeSpec;\n\n/**\n * Represent a byte array\n */\nscalar bytes;\n\n/**\n * A numeric type\n */\nscalar numeric;\n\n/**\n * A whole number. This represent any `integer` value possible.\n * It is commonly represented as `BigInteger` in some languages.\n */\nscalar integer extends numeric;\n\n/**\n * A number with decimal value\n */\nscalar float extends numeric;\n\n/**\n * A 64-bit integer. (`-9,223,372,036,854,775,808` to `9,223,372,036,854,775,807`)\n */\nscalar int64 extends integer;\n\n/**\n * A 32-bit integer. (`-2,147,483,648` to `2,147,483,647`)\n */\nscalar int32 extends int64;\n\n/**\n * A 16-bit integer. (`-32,768` to `32,767`)\n */\nscalar int16 extends int32;\n\n/**\n * A 8-bit integer. (`-128` to `127`)\n */\nscalar int8 extends int16;\n\n/**\n * A 64-bit unsigned integer (`0` to `18,446,744,073,709,551,615`)\n */\nscalar uint64 extends integer;\n\n/**\n * A 32-bit unsigned integer (`0` to `4,294,967,295`)\n */\nscalar uint32 extends uint64;\n\n/**\n * A 16-bit unsigned integer (`0` to `65,535`)\n */\nscalar uint16 extends uint32;\n\n/**\n * A 8-bit unsigned integer (`0` to `255`)\n */\nscalar uint8 extends uint16;\n\n/**\n * An integer that can be serialized to JSON (`−9007199254740991 (−(2^53 − 1))` to `9007199254740991 (2^53 − 1)` )\n */\nscalar safeint extends int64;\n\n/**\n * A 64 bit floating point number. (`±5.0 × 10^−324` to `±1.7 × 10^308`)\n */\nscalar float64 extends float;\n\n/**\n * A 32 bit floating point number. (`±1.5 x 10^−45` to `±3.4 x 10^38`)\n */\nscalar float32 extends float64;\n\n/**\n * A decimal number with any length and precision. This represent any `decimal` value possible.\n * It is commonly represented as `BigDecimal` in some languages.\n */\nscalar decimal extends numeric;\n\n/**\n * A 128-bit decimal number.\n */\nscalar decimal128 extends decimal;\n\n/**\n * A sequence of textual characters.\n */\nscalar string;\n\n/**\n * A date on a calendar without a time zone, e.g. \"April 10th\"\n */\nscalar plainDate {\n  /**\n   * Create a plain date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = plainTime.fromISO(\"2024-05-06\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A time on a clock without a time zone, e.g. \"3:00 am\"\n */\nscalar plainTime {\n  /**\n   * Create a plain time from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = plainTime.fromISO(\"12:34\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * An instant in coordinated universal time (UTC)\"\n */\nscalar utcDateTime {\n  /**\n   * Create a date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = utcDateTime.fromISO(\"2024-05-06T12:20-12Z\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A date and time in a particular time zone, e.g. \"April 10th at 3:00am in PST\"\n */\nscalar offsetDateTime {\n  /**\n   * Create a date from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = offsetDateTime.fromISO(\"2024-05-06T12:20-12-0700\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * A duration/time period. e.g 5s, 10h\n */\nscalar duration {\n  /**\n   * Create a duration from an ISO 8601 string.\n   * @example\n   *\n   * ```tsp\n   * const time = duration.fromISO(\"P1Y1D\");\n   * ```\n   */\n  init fromISO(value: string);\n}\n\n/**\n * Boolean with `true` and `false` values.\n */\nscalar boolean;\n\n/**\n * @dev Array model type, equivalent to `Element[]`\n * @template Element The type of the array elements\n */\n@indexer(integer, Element)\nmodel Array<Element> {}\n\n/**\n * @dev Model with string properties where all the properties have type `Property`\n * @template Element The type of the properties\n */\n@indexer(string, Element)\nmodel Record<Element> {}\n",
  "../compiler/lib/prototypes.tsp": "namespace TypeSpec.Prototypes;\n\nextern dec getter(target: unknown);\n\nnamespace Types {\n  interface ModelProperty {\n    @getter type(): unknown;\n  }\n\n  interface Operation {\n    @getter returnType(): unknown;\n    @getter parameters(): unknown;\n  }\n\n  interface Array<TElementType> {\n    @getter elementType(): TElementType;\n  }\n}\n",
  "../compiler/lib/std/main.tsp": "// TypeSpec standard library. Everything in here can be omitted by using `--nostdlib` cli flag or `nostdlib` in the config.\nimport \"./types.tsp\";\nimport \"./decorators.tsp\";\nimport \"./reflection.tsp\";\nimport \"./projected-names.tsp\";\nimport \"./visibility.tsp\";\n",
  "../compiler/lib/std/types.tsp": "namespace TypeSpec;\n\n/**\n * Represent a 32-bit unix timestamp datetime with 1s of granularity.\n * It measures time by the number of seconds that have elapsed since 00:00:00 UTC on 1 January 1970.\n */\n@encode(\"unixTimestamp\", int32)\nscalar unixTimestamp32 extends utcDateTime;\n\n/**\n * Represent a model\n */\n// Deprecated June 2023 sprint\n#deprecated \"object is deprecated. Please use {} for an empty model, `Record<unknown>` for a record with unknown property types, `unknown[]` for an array.\"\nmodel object {}\n\n/**\n * Represent a URL string as described by https://url.spec.whatwg.org/\n */\nscalar url extends string;\n\n/**\n * Represents a collection of optional properties.\n *\n * @template Source An object whose spread properties are all optional.\n */\n@doc(\"The template for adding optional properties.\")\n@withOptionalProperties\nmodel OptionalProperties<Source> {\n  ...Source;\n}\n\n/**\n * Represents a collection of updateable properties.\n *\n * @template Source An object whose spread properties are all updateable.\n */\n@doc(\"The template for adding updateable properties.\")\n@withUpdateableProperties\nmodel UpdateableProperties<Source> {\n  ...Source;\n}\n\n/**\n * Represents a collection of omitted properties.\n *\n * @template Source An object whose properties are spread.\n * @template Keys The property keys to omit.\n */\n@doc(\"The template for omitting properties.\")\n@withoutOmittedProperties(Keys)\nmodel OmitProperties<Source, Keys extends string> {\n  ...Source;\n}\n\n/**\n * Represents a collection of properties with only the specified keys included.\n *\n * @template Source An object whose properties are spread.\n * @template Keys The property keys to include.\n */\n@doc(\"The template for picking properties.\")\n@withPickedProperties(Keys)\nmodel PickProperties<Source, Keys extends string> {\n  ...Source;\n}\n\n/**\n * Represents a collection of properties with default values omitted.\n *\n * @template Source An object whose spread property defaults are all omitted.\n */\n@withoutDefaultValues\nmodel OmitDefaults<Source> {\n  ...Source;\n}\n\n/**\n * Applies a visibility setting to a collection of properties.\n *\n * @template Source An object whose properties are spread.\n * @template Visibility The visibility to apply to all properties.\n */\n@doc(\"The template for setting the default visibility of key properties.\")\n@withDefaultKeyVisibility(Visibility)\nmodel DefaultKeyVisibility<Source, Visibility extends valueof string> {\n  ...Source;\n}\n",
  "../compiler/lib/std/decorators.tsp": "import \"../../dist/src/lib/tsp-index.js\";\n\nusing TypeSpec.Reflection;\n\nnamespace TypeSpec;\n\n/**\n * Typically a short, single-line description.\n * @param summary Summary string.\n *\n * @example\n * ```typespec\n * @summary(\"This is a pet\")\n * model Pet {}\n * ```\n */\nextern dec summary(target: unknown, summary: valueof string);\n\n/**\n * Attach a documentation string.\n * @param doc Documentation string\n * @param formatArgs Record with key value pair that can be interpolated in the doc.\n *\n * @example\n * ```typespec\n * @doc(\"Represent a Pet available in the PetStore\")\n * model Pet {}\n * ```\n */\nextern dec doc(target: unknown, doc: valueof string, formatArgs?: {});\n\n/**\n * Attach a documentation string to describe the successful return types of an operation.\n * If an operation returns a union of success and errors it only describes the success. See `@errorsDoc` for error documentation.\n * @param doc Documentation string\n *\n * @example\n * ```typespec\n * @returnsDoc(\"Returns doc\")\n * op get(): Pet | NotFound;\n * ```\n */\nextern dec returnsDoc(target: Operation, doc: valueof string);\n\n/**\n * Attach a documentation string to describe the error return types of an operation.\n * If an operation returns a union of success and errors it only describes the errors. See `@returnsDoc` for success documentation.\n * @param doc Documentation string\n *\n * @example\n * ```typespec\n * @errorsDoc(\"Errors doc\")\n * op get(): Pet | NotFound;\n * ```\n */\nextern dec errorsDoc(target: Operation, doc: valueof string);\n\n/**\n * Mark this type as deprecated.\n *\n * NOTE: This decorator **should not** be used, use the `#deprecated` directive instead.\n *\n * @deprecated Use the `#deprecated` [directive](https://typespec.io/docs/language-basics/directives/#deprecated) instead.\n * @param message Deprecation message.\n *\n * @example\n *\n * Use the `#deprecated` directive instead:\n *\n * ```typespec\n * #deprecated \"Use ActionV2\"\n * op Action<Result>(): Result;\n * ```\n */\n#deprecated \"@deprecated decorator is deprecated. Use the `#deprecated` directive instead.\"\nextern dec deprecated(target: unknown, message: valueof string);\n\n/**\n * Service options.\n */\nmodel ServiceOptions {\n  /**\n   * Title of the service.\n   */\n  title?: string;\n\n  /**\n   * Version of the service.\n   */\n  version?: string;\n}\n\n/**\n * Mark this namespace as describing a service and configure service properties.\n * @param options Optional configuration for the service.\n *\n * @example\n * ```typespec\n * @service\n * namespace PetStore;\n * ```\n *\n * @example Setting service title\n * ```typespec\n * @service({title: \"Pet store\"})\n * namespace PetStore;\n * ```\n *\n * @example Setting service version\n * ```typespec\n * @service({version: \"1.0\"})\n * namespace PetStore;\n * ```\n */\nextern dec service(target: Namespace, options?: ServiceOptions);\n\n/**\n * Specify that this model is an error type. Operations return error types when the operation has failed.\n *\n * @example\n * ```typespec\n * @error\n * model PetStoreError {\n *   code: string;\n *   message: string;\n * }\n * ```\n */\nextern dec error(target: Model);\n\n/**\n * Specify a known data format hint for this string type. For example `uuid`, `uri`, etc.\n * This differs from the `@pattern` decorator which is meant to specify a regular expression while `@format` accepts a known format name.\n * The format names are open ended and are left to emitter to interpret.\n *\n * @param format format name.\n *\n * @example\n * ```typespec\n * @format(\"uuid\")\n * scalar uuid extends string;\n * ```\n */\nextern dec format(target: string | bytes | ModelProperty, format: valueof string);\n\n/**\n * Specify the the pattern this string should respect using simple regular expression syntax.\n * The following syntax is allowed: alternations (`|`), quantifiers (`?`, `*`, `+`, and `{ }`), wildcard (`.`), and grouping parentheses.\n * Advanced features like look-around, capture groups, and references are not supported.\n *\n * This decorator may optionally provide a custom validation _message_. Emitters may choose to use the message to provide\n * context when pattern validation fails. For the sake of consistency, the message should be a phrase that describes in\n * plain language what sort of content the pattern attempts to validate. For example, a complex regular expression that\n * validates a GUID string might have a message like \"Must be a valid GUID.\"\n *\n * @param pattern Regular expression.\n * @param validationMessage Optional validation message that may provide context when validation fails.\n *\n * @example\n * ```typespec\n * @pattern(\"[a-z]+\", \"Must be a string consisting of only lower case letters and of at least one character.\")\n * scalar LowerAlpha extends string;\n * ```\n */\nextern dec pattern(\n  target: string | bytes | ModelProperty,\n  pattern: valueof string,\n  validationMessage?: valueof string\n);\n\n/**\n * Specify the minimum length this string type should be.\n * @param value Minimum length\n *\n * @example\n * ```typespec\n * @minLength(2)\n * scalar Username extends string;\n * ```\n */\nextern dec minLength(target: string | ModelProperty, value: valueof integer);\n\n/**\n * Specify the maximum length this string type should be.\n * @param value Maximum length\n *\n * @example\n * ```typespec\n * @maxLength(20)\n * scalar Username extends string;\n * ```\n */\nextern dec maxLength(target: string | ModelProperty, value: valueof integer);\n\n/**\n * Specify the minimum number of items this array should have.\n * @param value Minimum number\n *\n * @example\n * ```typespec\n * @minItems(1)\n * model Endpoints is string[];\n * ```\n */\nextern dec minItems(target: unknown[] | ModelProperty, value: valueof integer);\n\n/**\n * Specify the maximum number of items this array should have.\n * @param value Maximum number\n *\n * @example\n * ```typespec\n * @maxItems(5)\n * model Endpoints is string[];\n * ```\n */\nextern dec maxItems(target: unknown[] | ModelProperty, value: valueof integer);\n\n/**\n * Specify the minimum value this numeric type should be.\n * @param value Minimum value\n *\n * @example\n * ```typespec\n * @minValue(18)\n * scalar Age is int32;\n * ```\n */\nextern dec minValue(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the maximum value this numeric type should be.\n * @param value Maximum value\n *\n * @example\n * ```typespec\n * @maxValue(200)\n * scalar Age is int32;\n * ```\n */\nextern dec maxValue(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the minimum value this numeric type should be, exclusive of the given\n * value.\n * @param value Minimum value\n *\n * @example\n * ```typespec\n * @minValueExclusive(0)\n * scalar distance is float64;\n * ```\n */\nextern dec minValueExclusive(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Specify the maximum value this numeric type should be, exclusive of the given\n * value.\n * @param value Maximum value\n *\n * @example\n * ```typespec\n * @maxValueExclusive(50)\n * scalar distance is float64;\n * ```\n */\nextern dec maxValueExclusive(target: numeric | ModelProperty, value: valueof numeric);\n\n/**\n * Mark this string as a secret value that should be treated carefully to avoid exposure\n *\n * @example\n * ```typespec\n * @secret\n * scalar Password is string;\n * ```\n */\nextern dec secret(target: string | ModelProperty);\n\n/**\n * Attaches a tag to an operation, interface, or namespace. Multiple `@tag` decorators can be specified to attach multiple tags to a TypeSpec element.\n * @param tag Tag value\n */\nextern dec tag(target: Namespace | Interface | Operation, tag: valueof string);\n\n/**\n * Specifies how a templated type should name their instances.\n * @param name name the template instance should take\n * @param formatArgs Model with key value used to interpolate the name\n *\n * @example\n * ```typespec\n * @friendlyName(\"{name}List\", T)\n * model List<Item> {\n *   value: Item[];\n *   nextLink: string;\n * }\n * ```\n */\nextern dec friendlyName(target: unknown, name: valueof string, formatArgs?: unknown);\n\n/**\n * Provide a set of known values to a string type.\n * @param values Known values enum.\n *\n * @example\n * ```typespec\n * @knownValues(KnownErrorCode)\n * scalar ErrorCode extends string;\n *\n * enum KnownErrorCode {\n *   NotFound,\n *   Invalid,\n * }\n * ```\n */\n#deprecated \"This decorator has been deprecated. Use a named union of string literals with a string variant to achieve the same result without a decorator.\"\nextern dec knownValues(target: string | numeric | ModelProperty, values: Enum);\n\n/**\n * Mark a model property as the key to identify instances of that type\n * @param altName Name of the property. If not specified, the decorated property name is used.\n *\n * @example\n * ```typespec\n * model Pet {\n *   @key id: string;\n * }\n * ```\n */\nextern dec key(target: ModelProperty, altName?: valueof string);\n\n/**\n * Specify this operation is an overload of the given operation.\n * @param overloadbase Base operation that should be a union of all overloads\n *\n * @example\n * ```typespec\n * op upload(data: string | bytes, @header contentType: \"text/plain\" | \"application/octet-stream\"): void;\n * @overload(upload)\n * op uploadString(data: string, @header contentType: \"text/plain\" ): void;\n * @overload(upload)\n * op uploadBytes(data: bytes, @header contentType: \"application/octet-stream\"): void;\n * ```\n */\nextern dec overload(target: Operation, overloadbase: Operation);\n\n/**\n * DEPRECATED: Use `@encodedName` instead.\n *\n * Provide an alternative name for this type.\n * @param targetName Projection target\n * @param projectedName Alternative name\n *\n * @example\n * ```typespec\n * model Certificate {\n *   @projectedName(\"json\", \"exp\")\n *   expireAt: int32;\n * }\n * ```\n */\n#deprecated \"Use `@encodedName` instead for changing the name over the wire.\"\nextern dec projectedName(\n  target: unknown,\n  targetName: valueof string,\n  projectedName: valueof string\n);\n\n/**\n * Provide an alternative name for this type when serialized to the given mime type.\n * @param mimeType Mime type this should apply to. The mime type should be a known mime type as described here https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types without any suffix (e.g. `+json`)\n * @param name Alternative name\n *\n * @example\n *\n * ```typespec\n * model Certificate {\n *   @encodedName(\"application/json\", \"exp\")\n *   @encodedName(\"application/xml\", \"expiry\")\n *   expireAt: int32;\n * }\n * ```\n *\n * @example Invalid values\n *\n * ```typespec\n * @encodedName(\"application/merge-patch+json\", \"exp\")\n *              ^ error cannot use subtype\n * ```\n */\nextern dec encodedName(target: unknown, mimeType: valueof string, name: valueof string);\n\n/**\n * Specify the property to be used to discriminate this type.\n * @param propertyName The property name to use for discrimination\n *\n * @example\n *\n * ```typespec\n * @discriminator(\"kind\")\n * union Pet{ cat: Cat, dog: Dog }\n *\n * model Cat {kind: \"cat\", meow: boolean}\n * model Dog {kind: \"dog\", bark: boolean}\n * ```\n *\n * ```typespec\n * @discriminator(\"kind\")\n * model Pet{ kind: string }\n *\n * model Cat extends Pet {kind: \"cat\", meow: boolean}\n * model Dog extends Pet  {kind: \"dog\", bark: boolean}\n * ```\n */\nextern dec discriminator(target: Model | Union, propertyName: valueof string);\n\n/**\n * Known encoding to use on utcDateTime or offsetDateTime\n */\nenum DateTimeKnownEncoding {\n  /**\n   * RFC 3339 standard. https://www.ietf.org/rfc/rfc3339.txt\n   * Encode to string.\n   */\n  rfc3339: \"rfc3339\",\n\n  /**\n   * RFC 7231 standard. https://www.ietf.org/rfc/rfc7231.txt\n   * Encode to string.\n   */\n  rfc7231: \"rfc7231\",\n\n  /**\n   * Encode a datetime to a unix timestamp.\n   * Unix timestamps are represented as an integer number of seconds since the Unix epoch and usually encoded as an int32.\n   */\n  unixTimestamp: \"unixTimestamp\",\n}\n\n/**\n * Known encoding to use on duration\n */\nenum DurationKnownEncoding {\n  /**\n   * ISO8601 duration\n   */\n  ISO8601: \"ISO8601\",\n\n  /**\n   * Encode to integer or float\n   */\n  seconds: \"seconds\",\n}\n\n/**\n * Known encoding to use on bytes\n */\nenum BytesKnownEncoding {\n  /**\n   * Encode to Base64\n   */\n  base64: \"base64\",\n\n  /**\n   * Encode to Base64 Url\n   */\n  base64url: \"base64url\",\n}\n\n/**\n * Encoding for serializing arrays\n */\nenum ArrayEncoding {\n  /** Each values of the array is separated by a | */\n  pipeDelimited,\n\n  /** Each values of the array is separated by a <space> */\n  spaceDelimited,\n}\n\n/**\n * Specify how to encode the target type.\n * @param encodingOrEncodeAs Known name of an encoding or a scalar type to encode as(Only for numeric types to encode as string).\n * @param encodedAs What target type is this being encoded as. Default to string.\n *\n * @example offsetDateTime encoded with rfc7231\n *\n * ```tsp\n * @encode(\"rfc7231\")\n * scalar myDateTime extends offsetDateTime;\n * ```\n *\n * @example utcDateTime encoded with unixTimestamp\n *\n * ```tsp\n * @encode(\"unixTimestamp\", int32)\n * scalar myDateTime extends unixTimestamp;\n * ```\n *\n * @example encode numeric type to string\n *\n * ```tsp\n * model Pet {\n *   @encode(string) id: int64;\n * }\n * ```\n */\nextern dec encode(\n  target: Scalar | ModelProperty,\n  encodingOrEncodeAs: (valueof string | EnumMember) | Scalar,\n  encodedAs?: Scalar\n);\n\n/** Options for example decorators */\nmodel ExampleOptions {\n  /** The title of the example */\n  title?: string;\n\n  /** Description of the example */\n  description?: string;\n}\n\n/**\n * Provide an example value for a data type.\n *\n * @param example Example value.\n * @param options Optional metadata for the example.\n *\n * @example\n *\n * ```tsp\n * @example(#{name: \"Fluffy\", age: 2})\n * model Pet {\n *  name: string;\n *  age: int32;\n * }\n * ```\n */\nextern dec example(\n  target: Model | Enum | Scalar | Union | ModelProperty | UnionVariant,\n  example: valueof unknown,\n  options?: valueof ExampleOptions\n);\n\n/**\n * Operation example configuration.\n */\nmodel OperationExample {\n  /** Example request body. */\n  parameters?: unknown;\n\n  /** Example response body. */\n  returnType?: unknown;\n}\n\n/**\n * Provide example values for an operation's parameters and corresponding return type.\n *\n * @param example Example value.\n * @param options Optional metadata for the example.\n *\n * @example\n *\n * ```tsp\n * @opExample(#{parameters: #{name: \"Fluffy\", age: 2}, returnType: #{name: \"Fluffy\", age: 2, id: \"abc\"})\n * op createPet(pet: Pet): Pet;\n * ```\n */\nextern dec opExample(\n  target: Operation,\n  example: valueof OperationExample,\n  options?: valueof ExampleOptions\n);\n\n/**\n * Returns the model with required properties removed.\n */\nextern dec withOptionalProperties(target: Model);\n\n/**\n * Returns the model with any default values removed.\n */\nextern dec withoutDefaultValues(target: Model);\n\n/**\n * Returns the model with the given properties omitted.\n * @param omit List of properties to omit\n */\nextern dec withoutOmittedProperties(target: Model, omit: string | Union);\n\n/**\n * Returns the model with only the given properties included.\n * @param pick List of properties to include\n */\nextern dec withPickedProperties(target: Model, pick: string | Union);\n\n//---------------------------------------------------------------------------\n// Paging\n//---------------------------------------------------------------------------\n\n/**\n * Mark this operation as a `list` operation that returns a paginated list of items.\n */\nextern dec list(target: Operation);\n\n/**\n * Pagination property defining the number of items to skip.\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@offset skip: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec offset(target: ModelProperty);\n\n/**\n * Pagination property defining the page index.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@pageIndex page: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec pageIndex(target: ModelProperty);\n\n/**\n * Specify the pagination parameter that controls the maximum number of items to include in a page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@pageIndex page: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec pageSize(target: ModelProperty);\n\n/**\n * Specify the the property that contains the array of page items.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n * }\n * @list op listPets(@pageIndex page: int32, @pageSize pageSize: int8): Page<Pet>;\n * ```\n */\nextern dec pageItems(target: ModelProperty);\n\n/**\n * Pagination property defining the token to get to the next page.\n * It MUST be specified both on the request parameter and the response.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @continuationToken continuationToken: string;\n * }\n * @list op listPets(@continuationToken continuationToken: string): Page<Pet>;\n * ```\n */\nextern dec continuationToken(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the next page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec nextLink(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the previous page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec prevLink(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the first page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec firstLink(target: ModelProperty);\n\n/**\n * Pagination property defining a link to the last page.\n *\n * It is expected that navigating to the link will return the same set of responses as the operation that returned the current page.\n *\n * @example\n * ```tsp\n * model Page<T> {\n *   @pageItems items: T[];\n *   @nextLink next: url;\n *   @prevLink prev: url;\n *   @firstLink first: url;\n *   @lastLink last: url;\n * }\n * @list op listPets(): Page<Pet>;\n * ```\n */\nextern dec lastLink(target: ModelProperty);\n\n//---------------------------------------------------------------------------\n// Debugging\n//---------------------------------------------------------------------------\n\n/**\n * A debugging decorator used to inspect a type.\n * @param text Custom text to log\n */\nextern dec inspectType(target: unknown, text: valueof string);\n\n/**\n * A debugging decorator used to inspect a type name.\n * @param text Custom text to log\n */\nextern dec inspectTypeName(target: unknown, text: valueof string);\n",
  "../compiler/lib/std/reflection.tsp": "namespace TypeSpec.Reflection;\n\nmodel Enum {}\nmodel EnumMember {}\nmodel Interface {}\nmodel Model {}\nmodel ModelProperty {}\nmodel Namespace {}\nmodel Operation {}\nmodel Scalar {}\nmodel Union {}\nmodel UnionVariant {}\nmodel StringTemplate {}\n",
  "../compiler/lib/std/projected-names.tsp": "// Set of projections consuming the @projectedName decorator\n#suppress \"deprecated\"\nprojection op#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n  }\n}\n\n#suppress \"deprecated\"\nprojection interface#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n  }\n}\n\n#suppress \"deprecated\"\nprojection model#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n\n    self::properties::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameProperty(p::name, getProjectedName(p, targetName));\n      };\n    });\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n\n    self::projectionBase::properties::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameProperty(getProjectedName(p, targetName), p::name);\n      };\n    });\n  }\n}\n\n#suppress \"deprecated\"\nprojection enum#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n\n    self::members::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameMember(p::name, getProjectedName(p, targetName));\n      };\n    });\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n\n    self::projectionBase::members::forEach((p) => {\n      if hasProjectedName(p, targetName) {\n        self::renameMember(getProjectedName(p, targetName), p::name);\n      };\n    });\n  }\n}\n\n#suppress \"deprecated\"\nprojection union#target {\n  to(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(getProjectedName(self, targetName));\n    };\n  }\n  from(targetName) {\n    if hasProjectedName(self, targetName) {\n      self::rename(self::projectionBase::name);\n    };\n  }\n}\n",
  "../compiler/lib/std/visibility.tsp": "// Copyright (c) Microsoft Corporation\n// Licensed under the MIT license.\n\nimport \"../../dist/src/lib/tsp-index.js\";\n\nusing TypeSpec.Reflection;\n\nnamespace TypeSpec;\n\n/**\n * Sets the visibility modifiers that are active on a property, indicating that it is only considered to be present\n * (or \"visible\") in contexts that select for the given modifiers.\n *\n * A property without any visibility settings applied for any visibility class (e.g. `Lifecycle`) is considered to have\n * the default visibility settings for that class.\n *\n * If visibility for the property has already been set for a visibility class (for example, using `@invisible` or\n * `@removeVisibility`), this decorator will **add** the specified visibility modifiers to the property.\n *\n * See: [Visibility](https://typespec.io/docs/language-basics/visibility)\n *\n * The `@typespec/http` library uses `Lifecycle` visibility to determine which properties are included in the request or\n * response bodies of HTTP operations. By default, it uses the following visibility settings:\n *\n * - For the return type of operations, properties are included if they have `Lifecycle.Read` visibility.\n * - For POST operation parameters, properties are included if they have `Lifecycle.Create` visibility.\n * - For PUT operation parameters, properties are included if they have `Lifecycle.Create` or `Lifecycle.Update` visibility.\n * - For PATCH operation parameters, properties are included if they have `Lifecycle.Update` visibility.\n * - For DELETE operation parameters, properties are included if they have `Lifecycle.Delete` visibility.\n * - For GET or HEAD operation parameters, properties are included if they have `Lifecycle.Query` visibility.\n *\n * By default, properties have all five Lifecycle visibility modifiers enabled, so a property is visible in all contexts\n * by default.\n *\n * The default settings may be overridden using the `@returnTypeVisibility` and `@parameterVisibility` decorators.\n *\n * See also: [Automatic visibility](https://typespec.io/docs/libraries/http/operations#automatic-visibility)\n *\n * @param visibilities List of visibilities which apply to this property.\n *\n * @example\n *\n * ```typespec\n * model Dog {\n *   // The service will generate an ID, so you don't need to send it.\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   // The service will store this secret name, but won't ever return it.\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   // The regular name has all vi\n *   name: string;\n * }\n * ```\n */\nextern dec visibility(target: ModelProperty, ...visibilities: valueof (string | EnumMember)[]);\n\n/**\n * Indicates that a property is not visible in the given visibility class.\n *\n * This decorator removes all active visibility modifiers from the property within\n * the given visibility class, making it invisible to any context that selects for\n * visibility modifiers within that class.\n *\n * @param visibilityClass The visibility class to make the property invisible within.\n *\n * @example\n * ```typespec\n * model Example {\n *   @invisible(Lifecycle)\n *   hidden_property: string;\n * }\n * ```\n */\nextern dec invisible(target: ModelProperty, visibilityClass: Enum);\n\n/**\n * Removes visibility modifiers from a property.\n *\n * If the visibility modifiers for a visibility class have not been initialized,\n * this decorator will use the default visibility modifiers for the visibility\n * class as the default modifier set.\n *\n * @param target The property to remove visibility from.\n * @param visibilities The visibility modifiers to remove from the target property.\n *\n * @example\n * ```typespec\n * model Example {\n *   // This property will have all Lifecycle visibilities except the Read\n *   // visibility, since it is removed.\n *   @removeVisibility(Lifecycle.Read)\n *   secret_property: string;\n * }\n * ```\n */\nextern dec removeVisibility(target: ModelProperty, ...visibilities: valueof EnumMember[]);\n\n/**\n * Removes properties that do not have at least one of the given visibility modifiers\n * active.\n *\n * If no visibility modifiers are supplied, this decorator has no effect.\n *\n * See also: [Automatic visibility](https://typespec.io/docs/libraries/http/operations#automatic-visibility)\n *\n * When using an emitter that applies visibility automatically, it is generally\n * not necessary to use this decorator.\n *\n * @param visibilities List of visibilities that apply to this property.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // The spread operator will copy all the properties of Dog into DogRead,\n * // and @withVisibility will then remove those that are not visible with\n * // create or update visibility.\n * //\n * // In this case, the id property is removed, and the name and secretName\n * // properties are kept.\n * @withVisibility(Lifecycle.Create, Lifecycle.Update)\n * model DogCreateOrUpdate {\n *   ...Dog;\n * }\n *\n * // In this case the id and name properties are kept and the secretName property\n * // is removed.\n * @withVisibility(Lifecycle.Read)\n * model DogRead {\n *   ...Dog;\n * }\n * ```\n */\nextern dec withVisibility(target: Model, ...visibilities: valueof (string | EnumMember)[]);\n\n/**\n * Set the visibility of key properties in a model if not already set.\n *\n * This will set the visibility modifiers of all key properties in the model if the visibility is not already _explicitly_ set,\n * but will not change the visibility of any properties that have visibility set _explicitly_, even if the visibility\n * is the same as the default visibility.\n *\n * Visibility may be explicitly set using any of the following decorators:\n *\n * - `@visibility`\n * - `@removeVisibility`\n * - `@invisible`\n *\n * @param visibility The desired default visibility value. If a key property already has visibility set, it will not be changed.\n */\nextern dec withDefaultKeyVisibility(target: Model, visibility: valueof string | EnumMember);\n\n/**\n * Declares the visibility constraint of the parameters of a given operation.\n *\n * A parameter or property nested within a parameter will be visible if it has _any_ of the visibilities\n * in the list.\n *\n * WARNING: If no arguments are provided to this decorator, the `@typespec/http` library considers only properties\n * that do not have visibility modifiers _explicitly_ configured to be visible. Additionally, the HTTP library will\n * disable the feature of `@patch` operations that causes the properties of the request body to become effectively\n * optional. Some specifications have used this configuration in the past to describe exact PATCH bodies, but using this\n * decorator with no arguments in that manner is not recommended. The legacy behavior of `@parameterVisibility` with no\n * arguments is preserved for backwards compatibility pending a future review and possible deprecation.\n *\n * @param visibilities List of visibility modifiers that apply to the parameters of this operation.\n */\nextern dec parameterVisibility(target: Operation, ...visibilities: valueof (string | EnumMember)[]);\n\n/**\n * Declares the visibility constraint of the return type of a given operation.\n *\n * A property within the return type of the operation will be visible if it has _any_ of the visibilities\n * in the list, or if the list is empty (in which case the property is always visible).\n *\n * @param visibilities List of visibility modifiers that apply to the return type of this operation.\n */\nextern dec returnTypeVisibility(\n  target: Operation,\n  ...visibilities: valueof (string | EnumMember)[]\n);\n\n/**\n * Returns the model with non-updateable properties removed.\n */\nextern dec withUpdateableProperties(target: Model);\n\n/**\n * Declares the default visibility modifiers for a visibility class.\n *\n * The default modifiers are used when a property does not have any visibility decorators\n * applied to it.\n *\n * The modifiers passed to this decorator _MUST_ be members of the target Enum.\n *\n * @param visibilities the list of modifiers to use as the default visibility modifiers.\n */\nextern dec defaultVisibility(target: Enum, ...visibilities: valueof EnumMember[]);\n\n/**\n * A visibility class for resource lifecycle phases.\n *\n * These visibilities control whether a property is visible during the various phases of a resource's lifecycle.\n *\n * @example\n * ```typespec\n * model Dog {\n *  @visibility(Lifecycle.Read)\n *  id: int32;\n *\n *  @visibility(Lifecycle.Create, Lifecycle.Update)\n *  secretName: string;\n *\n *  name: string;\n * }\n * ```\n *\n * In this example, the `id` property is only visible during the read phase, and the `secretName` property is only visible\n * during the create and update phases. This means that the server will return the `id` property when returning a `Dog`,\n * but the client will not be able to set or update it. In contrast, the `secretName` property can be set when creating\n * or updating a `Dog`, but the server will never return it. The `name` property has no visibility modifiers and is\n * therefore visible in all phases.\n */\nenum Lifecycle {\n  /**\n   * The property is visible when a resource is being created.\n   */\n  Create,\n\n  /**\n   * The property is visible when a resource is being read.\n   */\n  Read,\n\n  /**\n   * The property is visible when a resource is being updated.\n   */\n  Update,\n\n  /**\n   * The property is visible when a resource is being deleted.\n   */\n  Delete,\n\n  /**\n   * The property is visible when a resource is being queried.\n   *\n   * In HTTP APIs, this visibility applies to parameters of GET or HEAD operations.\n   */\n  Query,\n}\n\n/**\n * A visibility filter, used to specify which properties should be included when\n * using the `withVisibilityFilter` decorator.\n *\n * The filter matches any property with ALL of the following:\n * - If the `any` key is present, the property must have at least one of the specified visibilities.\n * - If the `all` key is present, the property must have all of the specified visibilities.\n * - If the `none` key is present, the property must have none of the specified visibilities.\n */\nmodel VisibilityFilter {\n  any?: EnumMember[];\n  all?: EnumMember[];\n  none?: EnumMember[];\n}\n\n/**\n * Applies the given visibility filter to the properties of the target model.\n *\n * This transformation is recursive, so it will also apply the filter to any nested\n * or referenced models that are the types of any properties in the `target`.\n *\n * @param target The model to apply the visibility filter to.\n * @param filter The visibility filter to apply to the properties of the target model.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   name: string;\n * }\n *\n * @withVisibilityFilter(#{ all: #[Lifecycle.Read] })\n * model DogRead {\n *  ...Dog\n * }\n * ```\n */\nextern dec withVisibilityFilter(target: Model, filter: valueof VisibilityFilter);\n\n/**\n * Transforms the `target` model to include only properties that are visible during the\n * \"Update\" lifecycle phase.\n *\n * Any nested models of optional properties will be transformed into the \"CreateOrUpdate\"\n * lifecycle phase instead of the \"Update\" lifecycle phase, so that nested models may be\n * fully updated.\n *\n * @param target The model to apply the transformation to.\n *\n * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * @withLifecycleUpdate\n * model DogUpdate {\n *   ...Dog\n * }\n * ```\n */\nextern dec withLifecycleUpdate(target: Model);\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * \"Create\" resource lifecycle phase.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Create` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   name: string;\n * }\n *\n * // This model has only the `name` field.\n * model CreateDog is Create<Dog>;\n * ```\n */\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Create] })\nmodel Create<T extends Reflection.Model, NameTemplate extends valueof string = \"Create{name}\"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * \"Read\" resource lifecycle phase.\n *\n * The \"Read\" lifecycle phase is used for properties returned by operations that read data, like\n * HTTP GET operations.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Read` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // This model has the `id` and `name` fields, but not `secretName`.\n * model ReadDog is Read<Dog>;\n * ```\n */\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Read] })\nmodel Read<T extends Reflection.Model, NameTemplate extends valueof string = \"Read{name}\"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * \"Update\" resource lifecycle phase.\n *\n * The \"Update\" lifecycle phase is used for properties passed as parameters to operations\n * that update data, like HTTP PATCH operations.\n *\n * This transformation will include only the properties that have the `Lifecycle.Update`\n * visibility modifier, and the types of all properties will be replaced with the\n * equivalent `CreateOrUpdate` transformation.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // This model will have the `secretName` and `name` fields, but not the `id` field.\n * model UpdateDog is Update<Dog>;\n * ```\n */\n@friendlyName(NameTemplate, T)\n@withLifecycleUpdate\nmodel Update<T extends Reflection.Model, NameTemplate extends valueof string = \"Update{name}\"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * \"Create\" or \"Update\" resource lifecycle phases.\n *\n * The \"CreateOrUpdate\" lifecycle phase is used by default for properties passed as parameters to operations\n * that can create _or_ update data, like HTTP PUT operations.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Create` or `Lifecycle.Update` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   @visibility(Lifecycle.Create)\n *   immutableSecret: string;\n *\n *   @visibility(Lifecycle.Create, Lifecycle.Update)\n *   secretName: string;\n *\n *   name: string;\n * }\n *\n * // This model will have the `immutableSecret`, `secretName`, and `name` fields, but not the `id` field.\n * model CreateOrUpdateDog is CreateOrUpdate<Dog>;\n * ```\n */\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ any: #[Lifecycle.Create, Lifecycle.Update] })\nmodel CreateOrUpdate<\n  T extends Reflection.Model,\n  NameTemplate extends valueof string = \"CreateOrUpdate{name}\"\n> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * \"Delete\" resource lifecycle phase.\n *\n * The \"Delete\" lifecycle phase is used for properties passed as parameters to operations\n * that delete data, like HTTP DELETE operations.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Delete` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   // Set when the Dog is removed from our data store. This happens when the\n *   // Dog is re-homed to a new owner.\n *   @visibility(Lifecycle.Delete)\n *   nextOwner: string;\n *\n *   name: string;\n * }\n *\n * // This model will have the `nextOwner` and `name` fields, but not the `id` field.\n * model DeleteDog is Delete<Dog>;\n * ```\n */\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Delete] })\nmodel Delete<T extends Reflection.Model, NameTemplate extends valueof string = \"Delete{name}\"> {\n  ...T;\n}\n\n/**\n * A copy of the input model `T` with only the properties that are visible during the\n * \"Query\" resource lifecycle phase.\n *\n * The \"Query\" lifecycle phase is used for properties passed as parameters to operations\n * that read data, like HTTP GET or HEAD operations. This should not be confused for\n * the `@query` decorator, which specifies that the property is transmitted in the\n * query string of an HTTP request.\n *\n * This transformation is recursive, and will include only properties that have the\n * `Lifecycle.Query` visibility modifier.\n *\n * If a `NameTemplate` is provided, the new model will be named according to the template.\n * The template uses the same syntax as the `@friendlyName` decorator.\n *\n * @template T The model to transform.\n * @template NameTemplate The name template to use for the new model.\n *\n *  * @example\n * ```typespec\n * model Dog {\n *   @visibility(Lifecycle.Read)\n *   id: int32;\n *\n *   // When getting information for a Dog, you can set this field to true to include\n *   // some extra information about the Dog's pedigree that is normally not returned.\n *   // Alternatively, you could just use a separate option parameter to get this\n *   // information.\n *   @visibility(Lifecycle.Query)\n *   includePedigree?: boolean;\n *\n *   name: string;\n *\n *   // Only included if `includePedigree` is set to true in the request.\n *   @visibility(Lifecycle.Read)\n *   pedigree?: string;\n * }\n *\n * // This model will have the `includePedigree` and `name` fields, but not `id` or `pedigree`.\n * model QueryDog is Query<Dog>;\n * ```\n */\n@friendlyName(NameTemplate, T)\n@withVisibilityFilter(#{ all: #[Lifecycle.Query] })\nmodel Query<T extends Reflection.Model, NameTemplate extends valueof string = \"Query{name}\"> {\n  ...T;\n}\n",
  "lib/main.tsp": "import \"./decorators.tsp\";\n",
  "lib/decorators.tsp": "import \"../dist/src/tsp-index.js\";\n\nnamespace TypeSpec.OpenAPI;\n\nusing TypeSpec.Reflection;\n\n/**\n * Specify that `oneOf` should be used instead of `anyOf` for that union.\n */\nextern dec oneOf(target: Union | ModelProperty);\n/**\n * Specify an external reference that should be used inside of emitting this type.\n * @param ref External reference(e.g. \"../../common.json#/components/schemas/Foo\")\n */\nextern dec useRef(target: Model | ModelProperty, ref: valueof string);\n"
};
const _TypeSpecLibrary_ = {
  jsSourceFiles: TypeSpecJSSources,
  typespecSourceFiles: TypeSpecSources,
};

export { $decorators, $lib, $onEmit, $oneOf, $useRef, _TypeSpecLibrary_, convertOpenAPI3Document, getOneOf, getOpenAPI3, getRef, namespace, resolveOptions };
