build-my-own
Version:
A CLI tool that helps developers learn by recreating open source projects from scratch. It sets up learning environments with AI-powered coding assistance for the 'build-your-own-X' approach.
12,685 lines • 715 kB
JavaScript
#!/usr/bin/env node
/*! For license information please see index.js.LICENSE.txt */
(function(root, factory) {
if ('object' == typeof exports && 'object' == typeof module) module.exports = factory(require("node:fs"), require("node:path"), require("node:process"), require("node:child_process"));
else if ('function' == typeof define && define.amd) define([
"node:fs",
"node:path",
"node:process",
"node:child_process"
], factory);
else {
var a = 'object' == typeof exports ? factory(require("node:fs"), require("node:path"), require("node:process"), require("node:child_process")) : factory(root["node:fs"], root["node:path"], root["node:process"], root["node:child_process"]);
for(var i in a)('object' == typeof exports ? exports : root)[i] = a[i];
}
})(global, (__WEBPACK_EXTERNAL_MODULE_node_fs__, __WEBPACK_EXTERNAL_MODULE_node_path__, __WEBPACK_EXTERNAL_MODULE_node_process__, __WEBPACK_EXTERNAL_MODULE_node_child_process__)=>(()=>{
var __webpack_modules__ = {
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/ajv.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var compileSchema = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/index.js"), resolve = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/resolve.js"), Cache = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/cache.js"), SchemaObject = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/schema_obj.js"), stableStringify = __webpack_require__("./node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js"), formats = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/formats.js"), rules = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/rules.js"), $dataMetaSchema = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/data.js"), util = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js");
module1.exports = Ajv;
Ajv.prototype.validate = validate;
Ajv.prototype.compile = compile;
Ajv.prototype.addSchema = addSchema;
Ajv.prototype.addMetaSchema = addMetaSchema;
Ajv.prototype.validateSchema = validateSchema;
Ajv.prototype.getSchema = getSchema;
Ajv.prototype.removeSchema = removeSchema;
Ajv.prototype.addFormat = addFormat;
Ajv.prototype.errorsText = errorsText;
Ajv.prototype._addSchema = _addSchema;
Ajv.prototype._compile = _compile;
Ajv.prototype.compileAsync = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/async.js");
var customKeyword = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/keyword.js");
Ajv.prototype.addKeyword = customKeyword.add;
Ajv.prototype.getKeyword = customKeyword.get;
Ajv.prototype.removeKeyword = customKeyword.remove;
Ajv.prototype.validateKeyword = customKeyword.validate;
var errorClasses = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/error_classes.js");
Ajv.ValidationError = errorClasses.Validation;
Ajv.MissingRefError = errorClasses.MissingRef;
Ajv.$dataMetaSchema = $dataMetaSchema;
var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
var META_IGNORE_OPTIONS = [
'removeAdditional',
'useDefaults',
'coerceTypes',
'strictDefaults'
];
var META_SUPPORT_DATA = [
'/properties'
];
function Ajv(opts) {
if (!(this instanceof Ajv)) return new Ajv(opts);
opts = this._opts = util.copy(opts) || {};
setLogger(this);
this._schemas = {};
this._refs = {};
this._fragments = {};
this._formats = formats(opts.format);
this._cache = opts.cache || new Cache;
this._loadingSchemas = {};
this._compilations = [];
this.RULES = rules();
this._getId = chooseGetId(opts);
opts.loopRequired = opts.loopRequired || 1 / 0;
if ('property' == opts.errorDataPath) opts._errorDataPathProperty = true;
if (void 0 === opts.serialize) opts.serialize = stableStringify;
this._metaOpts = getMetaSchemaOptions(this);
if (opts.formats) addInitialFormats(this);
if (opts.keywords) addInitialKeywords(this);
addDefaultMetaSchema(this);
if ('object' == typeof opts.meta) this.addMetaSchema(opts.meta);
if (opts.nullable) this.addKeyword('nullable', {
metaSchema: {
type: 'boolean'
}
});
addInitialSchemas(this);
}
function validate(schemaKeyRef, data) {
var v;
if ('string' == typeof schemaKeyRef) {
v = this.getSchema(schemaKeyRef);
if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
} else {
var schemaObj = this._addSchema(schemaKeyRef);
v = schemaObj.validate || this._compile(schemaObj);
}
var valid = v(data);
if (true !== v.$async) this.errors = v.errors;
return valid;
}
function compile(schema, _meta) {
var schemaObj = this._addSchema(schema, void 0, _meta);
return schemaObj.validate || this._compile(schemaObj);
}
function addSchema(schema, key, _skipValidation, _meta) {
if (Array.isArray(schema)) {
for(var i = 0; i < schema.length; i++)this.addSchema(schema[i], void 0, _skipValidation, _meta);
return this;
}
var id = this._getId(schema);
if (void 0 !== id && 'string' != typeof id) throw new Error('schema id must be string');
key = resolve.normalizeId(key || id);
checkUnique(this, key);
this._schemas[key] = this._addSchema(schema, _skipValidation, _meta, true);
return this;
}
function addMetaSchema(schema, key, skipValidation) {
this.addSchema(schema, key, skipValidation, true);
return this;
}
function validateSchema(schema, throwOrLogError) {
var $schema = schema.$schema;
if (void 0 !== $schema && 'string' != typeof $schema) throw new Error('$schema must be a string');
$schema = $schema || this._opts.defaultMeta || defaultMeta(this);
if (!$schema) {
this.logger.warn('meta-schema not available');
this.errors = null;
return true;
}
var valid = this.validate($schema, schema);
if (!valid && throwOrLogError) {
var message = 'schema is invalid: ' + this.errorsText();
if ('log' == this._opts.validateSchema) this.logger.error(message);
else throw new Error(message);
}
return valid;
}
function defaultMeta(self) {
var meta = self._opts.meta;
self._opts.defaultMeta = 'object' == typeof meta ? self._getId(meta) || meta : self.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0;
return self._opts.defaultMeta;
}
function getSchema(keyRef) {
var schemaObj = _getSchemaObj(this, keyRef);
switch(typeof schemaObj){
case 'object':
return schemaObj.validate || this._compile(schemaObj);
case 'string':
return this.getSchema(schemaObj);
case 'undefined':
return _getSchemaFragment(this, keyRef);
}
}
function _getSchemaFragment(self, ref) {
var res = resolve.schema.call(self, {
schema: {}
}, ref);
if (res) {
var schema = res.schema, root = res.root, baseId = res.baseId;
var v = compileSchema.call(self, schema, root, void 0, baseId);
self._fragments[ref] = new SchemaObject({
ref: ref,
fragment: true,
schema: schema,
root: root,
baseId: baseId,
validate: v
});
return v;
}
}
function _getSchemaObj(self, keyRef) {
keyRef = resolve.normalizeId(keyRef);
return self._schemas[keyRef] || self._refs[keyRef] || self._fragments[keyRef];
}
function removeSchema(schemaKeyRef) {
if (schemaKeyRef instanceof RegExp) {
_removeAllSchemas(this, this._schemas, schemaKeyRef);
_removeAllSchemas(this, this._refs, schemaKeyRef);
return this;
}
switch(typeof schemaKeyRef){
case 'undefined':
_removeAllSchemas(this, this._schemas);
_removeAllSchemas(this, this._refs);
this._cache.clear();
break;
case 'string':
var schemaObj = _getSchemaObj(this, schemaKeyRef);
if (schemaObj) this._cache.del(schemaObj.cacheKey);
delete this._schemas[schemaKeyRef];
delete this._refs[schemaKeyRef];
break;
case 'object':
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schemaKeyRef) : schemaKeyRef;
this._cache.del(cacheKey);
var id = this._getId(schemaKeyRef);
if (id) {
id = resolve.normalizeId(id);
delete this._schemas[id];
delete this._refs[id];
}
}
return this;
}
function _removeAllSchemas(self, schemas, regex) {
for(var keyRef in schemas){
var schemaObj = schemas[keyRef];
if (!schemaObj.meta && (!regex || regex.test(keyRef))) {
self._cache.del(schemaObj.cacheKey);
delete schemas[keyRef];
}
}
}
function _addSchema(schema, skipValidation, meta, shouldAddSchema) {
if ('object' != typeof schema && 'boolean' != typeof schema) throw new Error('schema should be object or boolean');
var serialize = this._opts.serialize;
var cacheKey = serialize ? serialize(schema) : schema;
var cached = this._cache.get(cacheKey);
if (cached) return cached;
shouldAddSchema = shouldAddSchema || false !== this._opts.addUsedSchema;
var id = resolve.normalizeId(this._getId(schema));
if (id && shouldAddSchema) checkUnique(this, id);
var willValidate = false !== this._opts.validateSchema && !skipValidation;
var recursiveMeta;
if (willValidate && !(recursiveMeta = id && id == resolve.normalizeId(schema.$schema))) this.validateSchema(schema, true);
var localRefs = resolve.ids.call(this, schema);
var schemaObj = new SchemaObject({
id: id,
schema: schema,
localRefs: localRefs,
cacheKey: cacheKey,
meta: meta
});
if ('#' != id[0] && shouldAddSchema) this._refs[id] = schemaObj;
this._cache.put(cacheKey, schemaObj);
if (willValidate && recursiveMeta) this.validateSchema(schema, true);
return schemaObj;
}
function _compile(schemaObj, root) {
if (schemaObj.compiling) {
schemaObj.validate = callValidate;
callValidate.schema = schemaObj.schema;
callValidate.errors = null;
callValidate.root = root ? root : callValidate;
if (true === schemaObj.schema.$async) callValidate.$async = true;
return callValidate;
}
schemaObj.compiling = true;
var currentOpts;
if (schemaObj.meta) {
currentOpts = this._opts;
this._opts = this._metaOpts;
}
var v;
try {
v = compileSchema.call(this, schemaObj.schema, root, schemaObj.localRefs);
} catch (e) {
delete schemaObj.validate;
throw e;
} finally{
schemaObj.compiling = false;
if (schemaObj.meta) this._opts = currentOpts;
}
schemaObj.validate = v;
schemaObj.refs = v.refs;
schemaObj.refVal = v.refVal;
schemaObj.root = v.root;
return v;
function callValidate() {
var _validate = schemaObj.validate;
var result = _validate.apply(this, arguments);
callValidate.errors = _validate.errors;
return result;
}
}
function chooseGetId(opts) {
switch(opts.schemaId){
case 'auto':
return _get$IdOrId;
case 'id':
return _getId;
default:
return _get$Id;
}
}
function _getId(schema) {
if (schema.$id) this.logger.warn('schema $id ignored', schema.$id);
return schema.id;
}
function _get$Id(schema) {
if (schema.id) this.logger.warn('schema id ignored', schema.id);
return schema.$id;
}
function _get$IdOrId(schema) {
if (schema.$id && schema.id && schema.$id != schema.id) throw new Error('schema $id is different from id');
return schema.$id || schema.id;
}
function errorsText(errors, options) {
errors = errors || this.errors;
if (!errors) return 'No errors';
options = options || {};
var separator = void 0 === options.separator ? ', ' : options.separator;
var dataVar = void 0 === options.dataVar ? 'data' : options.dataVar;
var text = '';
for(var i = 0; i < errors.length; i++){
var e = errors[i];
if (e) text += dataVar + e.dataPath + ' ' + e.message + separator;
}
return text.slice(0, -separator.length);
}
function addFormat(name, format) {
if ('string' == typeof format) format = new RegExp(format);
this._formats[name] = format;
return this;
}
function addDefaultMetaSchema(self) {
var $dataSchema;
if (self._opts.$data) {
$dataSchema = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/refs/data.json");
self.addMetaSchema($dataSchema, $dataSchema.$id, true);
}
if (false === self._opts.meta) return;
var metaSchema = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/refs/json-schema-draft-07.json");
if (self._opts.$data) metaSchema = $dataMetaSchema(metaSchema, META_SUPPORT_DATA);
self.addMetaSchema(metaSchema, META_SCHEMA_ID, true);
self._refs['http://json-schema.org/schema'] = META_SCHEMA_ID;
}
function addInitialSchemas(self) {
var optsSchemas = self._opts.schemas;
if (!optsSchemas) return;
if (Array.isArray(optsSchemas)) self.addSchema(optsSchemas);
else for(var key in optsSchemas)self.addSchema(optsSchemas[key], key);
}
function addInitialFormats(self) {
for(var name in self._opts.formats){
var format = self._opts.formats[name];
self.addFormat(name, format);
}
}
function addInitialKeywords(self) {
for(var name in self._opts.keywords){
var keyword = self._opts.keywords[name];
self.addKeyword(name, keyword);
}
}
function checkUnique(self, id) {
if (self._schemas[id] || self._refs[id]) throw new Error('schema with key or id "' + id + '" already exists');
}
function getMetaSchemaOptions(self) {
var metaOpts = util.copy(self._opts);
for(var i = 0; i < META_IGNORE_OPTIONS.length; i++)delete metaOpts[META_IGNORE_OPTIONS[i]];
return metaOpts;
}
function setLogger(self) {
var logger = self._opts.logger;
if (false === logger) self.logger = {
log: noop,
warn: noop,
error: noop
};
else {
if (void 0 === logger) logger = console;
if (!('object' == typeof logger && logger.log && logger.warn && logger.error)) throw new Error('logger must implement log, warn and error methods');
self.logger = logger;
}
}
function noop() {}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/cache.js": function(module1) {
"use strict";
var Cache = module1.exports = function() {
this._cache = {};
};
Cache.prototype.put = function(key, value) {
this._cache[key] = value;
};
Cache.prototype.get = function(key) {
return this._cache[key];
};
Cache.prototype.del = function(key) {
delete this._cache[key];
};
Cache.prototype.clear = function() {
this._cache = {};
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/async.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var MissingRefError = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/error_classes.js").MissingRef;
module1.exports = compileAsync;
function compileAsync(schema, meta, callback) {
var self = this;
if ('function' != typeof this._opts.loadSchema) throw new Error('options.loadSchema should be a function');
if ('function' == typeof meta) {
callback = meta;
meta = void 0;
}
var p = loadMetaSchemaOf(schema).then(function() {
var schemaObj = self._addSchema(schema, void 0, meta);
return schemaObj.validate || _compileAsync(schemaObj);
});
if (callback) p.then(function(v) {
callback(null, v);
}, callback);
return p;
function loadMetaSchemaOf(sch) {
var $schema = sch.$schema;
return $schema && !self.getSchema($schema) ? compileAsync.call(self, {
$ref: $schema
}, true) : Promise.resolve();
}
function _compileAsync(schemaObj) {
try {
return self._compile(schemaObj);
} catch (e) {
if (e instanceof MissingRefError) return loadMissingSchema(e);
throw e;
}
function loadMissingSchema(e) {
var ref = e.missingSchema;
if (added(ref)) throw new Error('Schema ' + ref + ' is loaded but ' + e.missingRef + ' cannot be resolved');
var schemaPromise = self._loadingSchemas[ref];
if (!schemaPromise) {
schemaPromise = self._loadingSchemas[ref] = self._opts.loadSchema(ref);
schemaPromise.then(removePromise, removePromise);
}
return schemaPromise.then(function(sch) {
if (!added(ref)) return loadMetaSchemaOf(sch).then(function() {
if (!added(ref)) self.addSchema(sch, ref, void 0, meta);
});
}).then(function() {
return _compileAsync(schemaObj);
});
function removePromise() {
delete self._loadingSchemas[ref];
}
function added(ref) {
return self._refs[ref] || self._schemas[ref];
}
}
}
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/error_classes.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var resolve = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/resolve.js");
module1.exports = {
Validation: errorSubclass(ValidationError),
MissingRef: errorSubclass(MissingRefError)
};
function ValidationError(errors) {
this.message = 'validation failed';
this.errors = errors;
this.ajv = this.validation = true;
}
MissingRefError.message = function(baseId, ref) {
return 'can\'t resolve reference ' + ref + ' from id ' + baseId;
};
function MissingRefError(baseId, ref, message) {
this.message = message || MissingRefError.message(baseId, ref);
this.missingRef = resolve.url(baseId, ref);
this.missingSchema = resolve.normalizeId(resolve.fullPath(this.missingRef));
}
function errorSubclass(Subclass) {
Subclass.prototype = Object.create(Error.prototype);
Subclass.prototype.constructor = Subclass;
return Subclass;
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/formats.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var util = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js");
var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
var DAYS = [
0,
31,
28,
31,
30,
31,
30,
31,
31,
30,
31,
30,
31
];
var TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i;
var HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i;
var URI = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;
var URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
var URL1 = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
module1.exports = formats;
function formats(mode) {
mode = 'full' == mode ? 'full' : 'fast';
return util.copy(formats[mode]);
}
formats.fast = {
date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,
'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,
uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
'uri-reference': /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
'uri-template': URITEMPLATE,
url: URL1,
email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
hostname: HOSTNAME,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
uuid: UUID,
'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
'relative-json-pointer': RELATIVE_JSON_POINTER
};
formats.full = {
date: date,
time: time,
'date-time': date_time,
uri: uri,
'uri-reference': URIREF,
'uri-template': URITEMPLATE,
url: URL1,
email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
hostname: HOSTNAME,
ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
regex: regex,
uuid: UUID,
'json-pointer': JSON_POINTER,
'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
'relative-json-pointer': RELATIVE_JSON_POINTER
};
function isLeapYear(year) {
return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
}
function date(str) {
var matches = str.match(DATE);
if (!matches) return false;
var year = +matches[1];
var month = +matches[2];
var day = +matches[3];
return month >= 1 && month <= 12 && day >= 1 && day <= (2 == month && isLeapYear(year) ? 29 : DAYS[month]);
}
function time(str, full) {
var matches = str.match(TIME);
if (!matches) return false;
var hour = matches[1];
var minute = matches[2];
var second = matches[3];
var timeZone = matches[5];
return (hour <= 23 && minute <= 59 && second <= 59 || 23 == hour && 59 == minute && 60 == second) && (!full || timeZone);
}
var DATE_TIME_SEPARATOR = /t|\s/i;
function date_time(str) {
var dateTime = str.split(DATE_TIME_SEPARATOR);
return 2 == dateTime.length && date(dateTime[0]) && time(dateTime[1], true);
}
var NOT_URI_FRAGMENT = /\/|:/;
function uri(str) {
return NOT_URI_FRAGMENT.test(str) && URI.test(str);
}
var Z_ANCHOR = /[^\\]\\Z/;
function regex(str) {
if (Z_ANCHOR.test(str)) return false;
try {
new RegExp(str);
return true;
} catch (e) {
return false;
}
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var resolve = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/resolve.js"), util = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js"), errorClasses = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/error_classes.js"), stableStringify = __webpack_require__("./node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js");
var validateGenerator = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/validate.js");
var ucs2length = util.ucs2length;
var equal = __webpack_require__("./node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js");
var ValidationError = errorClasses.Validation;
module1.exports = compile;
function compile(schema, root, localRefs, baseId) {
var self = this, opts = this._opts, refVal = [
void 0
], refs = {}, patterns = [], patternsHash = {}, defaults = [], defaultsHash = {}, customRules = [];
root = root || {
schema: schema,
refVal: refVal,
refs: refs
};
var c = checkCompiling.call(this, schema, root, baseId);
var compilation = this._compilations[c.index];
if (c.compiling) return compilation.callValidate = callValidate;
var formats = this._formats;
var RULES = this.RULES;
try {
var v = localCompile(schema, root, localRefs, baseId);
compilation.validate = v;
var cv = compilation.callValidate;
if (cv) {
cv.schema = v.schema;
cv.errors = null;
cv.refs = v.refs;
cv.refVal = v.refVal;
cv.root = v.root;
cv.$async = v.$async;
if (opts.sourceCode) cv.source = v.source;
}
return v;
} finally{
endCompiling.call(this, schema, root, baseId);
}
function callValidate() {
var validate = compilation.validate;
var result = validate.apply(this, arguments);
callValidate.errors = validate.errors;
return result;
}
function localCompile(_schema, _root, localRefs, baseId) {
var isRoot = !_root || _root && _root.schema == _schema;
if (_root.schema != root.schema) return compile.call(self, _schema, _root, localRefs, baseId);
var $async = true === _schema.$async;
var sourceCode = validateGenerator({
isTop: true,
schema: _schema,
isRoot: isRoot,
baseId: baseId,
root: _root,
schemaPath: '',
errSchemaPath: '#',
errorPath: '""',
MissingRefError: errorClasses.MissingRef,
RULES: RULES,
validate: validateGenerator,
util: util,
resolve: resolve,
resolveRef: resolveRef,
usePattern: usePattern,
useDefault: useDefault,
useCustomRule: useCustomRule,
opts: opts,
formats: formats,
logger: self.logger,
self: self
});
sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode;
if (opts.processCode) sourceCode = opts.processCode(sourceCode, _schema);
var validate;
try {
var makeValidate = new Function('self', 'RULES', 'formats', 'root', 'refVal', 'defaults', 'customRules', 'equal', 'ucs2length', 'ValidationError', sourceCode);
validate = makeValidate(self, RULES, formats, root, refVal, defaults, customRules, equal, ucs2length, ValidationError);
refVal[0] = validate;
} catch (e) {
self.logger.error('Error compiling schema, function code:', sourceCode);
throw e;
}
validate.schema = _schema;
validate.errors = null;
validate.refs = refs;
validate.refVal = refVal;
validate.root = isRoot ? validate : _root;
if ($async) validate.$async = true;
if (true === opts.sourceCode) validate.source = {
code: sourceCode,
patterns: patterns,
defaults: defaults
};
return validate;
}
function resolveRef(baseId, ref, isRoot) {
ref = resolve.url(baseId, ref);
var refIndex = refs[ref];
var _refVal, refCode;
if (void 0 !== refIndex) {
_refVal = refVal[refIndex];
refCode = 'refVal[' + refIndex + ']';
return resolvedRef(_refVal, refCode);
}
if (!isRoot && root.refs) {
var rootRefId = root.refs[ref];
if (void 0 !== rootRefId) {
_refVal = root.refVal[rootRefId];
refCode = addLocalRef(ref, _refVal);
return resolvedRef(_refVal, refCode);
}
}
refCode = addLocalRef(ref);
var v = resolve.call(self, localCompile, root, ref);
if (void 0 === v) {
var localSchema = localRefs && localRefs[ref];
if (localSchema) v = resolve.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self, localSchema, root, localRefs, baseId);
}
if (void 0 === v) removeLocalRef(ref);
else {
replaceLocalRef(ref, v);
return resolvedRef(v, refCode);
}
}
function addLocalRef(ref, v) {
var refId = refVal.length;
refVal[refId] = v;
refs[ref] = refId;
return 'refVal' + refId;
}
function removeLocalRef(ref) {
delete refs[ref];
}
function replaceLocalRef(ref, v) {
var refId = refs[ref];
refVal[refId] = v;
}
function resolvedRef(refVal, code) {
return 'object' == typeof refVal || 'boolean' == typeof refVal ? {
code: code,
schema: refVal,
inline: true
} : {
code: code,
$async: refVal && !!refVal.$async
};
}
function usePattern(regexStr) {
var index = patternsHash[regexStr];
if (void 0 === index) {
index = patternsHash[regexStr] = patterns.length;
patterns[index] = regexStr;
}
return 'pattern' + index;
}
function useDefault(value) {
switch(typeof value){
case 'boolean':
case 'number':
return '' + value;
case 'string':
return util.toQuotedString(value);
case 'object':
if (null === value) return 'null';
var valueStr = stableStringify(value);
var index = defaultsHash[valueStr];
if (void 0 === index) {
index = defaultsHash[valueStr] = defaults.length;
defaults[index] = value;
}
return 'default' + index;
}
}
function useCustomRule(rule, schema, parentSchema, it) {
if (false !== self._opts.validateSchema) {
var deps = rule.definition.dependencies;
if (deps && !deps.every(function(keyword) {
return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
})) throw new Error('parent schema must have all required keywords: ' + deps.join(','));
var validateSchema = rule.definition.validateSchema;
if (validateSchema) {
var valid = validateSchema(schema);
if (!valid) {
var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
if ('log' == self._opts.validateSchema) self.logger.error(message);
else throw new Error(message);
}
}
}
var compile = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro;
var validate;
if (compile) validate = compile.call(self, schema, parentSchema, it);
else if (macro) {
validate = macro.call(self, schema, parentSchema, it);
if (false !== opts.validateSchema) self.validateSchema(validate, true);
} else if (inline) validate = inline.call(self, it, rule.keyword, schema, parentSchema);
else {
validate = rule.definition.validate;
if (!validate) return;
}
if (void 0 === validate) throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
var index = customRules.length;
customRules[index] = validate;
return {
code: 'customRule' + index,
validate: validate
};
}
}
function checkCompiling(schema, root, baseId) {
var index = compIndex.call(this, schema, root, baseId);
if (index >= 0) return {
index: index,
compiling: true
};
index = this._compilations.length;
this._compilations[index] = {
schema: schema,
root: root,
baseId: baseId
};
return {
index: index,
compiling: false
};
}
function endCompiling(schema, root, baseId) {
var i = compIndex.call(this, schema, root, baseId);
if (i >= 0) this._compilations.splice(i, 1);
}
function compIndex(schema, root, baseId) {
for(var i = 0; i < this._compilations.length; i++){
var c = this._compilations[i];
if (c.schema == schema && c.root == root && c.baseId == baseId) return i;
}
return -1;
}
function patternCode(i, patterns) {
return 'var pattern' + i + ' = new RegExp(' + util.toQuotedString(patterns[i]) + ');';
}
function defaultCode(i) {
return 'var default' + i + ' = defaults[' + i + '];';
}
function refValCode(i, refVal) {
return void 0 === refVal[i] ? '' : 'var refVal' + i + ' = refVal[' + i + '];';
}
function customRuleCode(i) {
return 'var customRule' + i + ' = customRules[' + i + '];';
}
function vars(arr, statement) {
if (!arr.length) return '';
var code = '';
for(var i = 0; i < arr.length; i++)code += statement(i, arr);
return code;
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/resolve.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var URI = __webpack_require__("./node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/dist/es5/uri.all.js"), equal = __webpack_require__("./node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"), util = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js"), SchemaObject = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/schema_obj.js"), traverse = __webpack_require__("./node_modules/.pnpm/json-schema-traverse@0.4.1/node_modules/json-schema-traverse/index.js");
module1.exports = resolve;
resolve.normalizeId = normalizeId;
resolve.fullPath = getFullPath;
resolve.url = resolveUrl;
resolve.ids = resolveIds;
resolve.inlineRef = inlineRef;
resolve.schema = resolveSchema;
function resolve(compile, root, ref) {
var refVal = this._refs[ref];
if ('string' == typeof refVal) if (!this._refs[refVal]) return resolve.call(this, compile, root, refVal);
else refVal = this._refs[refVal];
refVal = refVal || this._schemas[ref];
if (refVal instanceof SchemaObject) return inlineRef(refVal.schema, this._opts.inlineRefs) ? refVal.schema : refVal.validate || this._compile(refVal);
var res = resolveSchema.call(this, root, ref);
var schema, v, baseId;
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
if (schema instanceof SchemaObject) v = schema.validate || compile.call(this, schema.schema, root, void 0, baseId);
else if (void 0 !== schema) v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, void 0, baseId);
return v;
}
function resolveSchema(root, ref) {
var p = URI.parse(ref), refPath = _getFullPath(p), baseId = getFullPath(this._getId(root.schema));
if (0 === Object.keys(root.schema).length || refPath !== baseId) {
var id = normalizeId(refPath);
var refVal = this._refs[id];
if ('string' == typeof refVal) return resolveRecursive.call(this, root, refVal, p);
if (refVal instanceof SchemaObject) {
if (!refVal.validate) this._compile(refVal);
root = refVal;
} else {
refVal = this._schemas[id];
if (!(refVal instanceof SchemaObject)) return;
if (!refVal.validate) this._compile(refVal);
if (id == normalizeId(ref)) return {
schema: refVal,
root: root,
baseId: baseId
};
root = refVal;
}
if (!root.schema) return;
baseId = getFullPath(this._getId(root.schema));
}
return getJsonPointer.call(this, p, baseId, root.schema, root);
}
function resolveRecursive(root, ref, parsedRef) {
var res = resolveSchema.call(this, root, ref);
if (res) {
var schema = res.schema;
var baseId = res.baseId;
root = res.root;
var id = this._getId(schema);
if (id) baseId = resolveUrl(baseId, id);
return getJsonPointer.call(this, parsedRef, baseId, schema, root);
}
}
var PREVENT_SCOPE_CHANGE = util.toHash([
'properties',
'patternProperties',
'enum',
'dependencies',
'definitions'
]);
function getJsonPointer(parsedRef, baseId, schema, root) {
parsedRef.fragment = parsedRef.fragment || '';
if ('/' != parsedRef.fragment.slice(0, 1)) return;
var parts = parsedRef.fragment.split('/');
for(var i = 1; i < parts.length; i++){
var part = parts[i];
if (part) {
part = util.unescapeFragment(part);
schema = schema[part];
if (void 0 === schema) break;
var id;
if (!PREVENT_SCOPE_CHANGE[part]) {
id = this._getId(schema);
if (id) baseId = resolveUrl(baseId, id);
if (schema.$ref) {
var $ref = resolveUrl(baseId, schema.$ref);
var res = resolveSchema.call(this, root, $ref);
if (res) {
schema = res.schema;
root = res.root;
baseId = res.baseId;
}
}
}
}
}
if (void 0 !== schema && schema !== root.schema) return {
schema: schema,
root: root,
baseId: baseId
};
}
var SIMPLE_INLINED = util.toHash([
'type',
'format',
'pattern',
'maxLength',
'minLength',
'maxProperties',
'minProperties',
'maxItems',
'minItems',
'maximum',
'minimum',
'uniqueItems',
'multipleOf',
'required',
'enum'
]);
function inlineRef(schema, limit) {
if (false === limit) return false;
if (void 0 === limit || true === limit) return checkNoRef(schema);
if (limit) return countKeys(schema) <= limit;
}
function checkNoRef(schema) {
var item;
if (Array.isArray(schema)) for(var i = 0; i < schema.length; i++){
item = schema[i];
if ('object' == typeof item && !checkNoRef(item)) return false;
}
else for(var key in schema){
if ('$ref' == key) return false;
item = schema[key];
if ('object' == typeof item && !checkNoRef(item)) return false;
}
return true;
}
function countKeys(schema) {
var count = 0, item;
if (Array.isArray(schema)) for(var i = 0; i < schema.length; i++){
item = schema[i];
if ('object' == typeof item) count += countKeys(item);
if (count == 1 / 0) return 1 / 0;
}
else for(var key in schema){
if ('$ref' == key) return 1 / 0;
if (SIMPLE_INLINED[key]) count++;
else {
item = schema[key];
if ('object' == typeof item) count += countKeys(item) + 1;
if (count == 1 / 0) return 1 / 0;
}
}
return count;
}
function getFullPath(id, normalize) {
if (false !== normalize) id = normalizeId(id);
var p = URI.parse(id);
return _getFullPath(p);
}
function _getFullPath(p) {
return URI.serialize(p).split('#')[0] + '#';
}
var TRAILING_SLASH_HASH = /#\/?$/;
function normalizeId(id) {
return id ? id.replace(TRAILING_SLASH_HASH, '') : '';
}
function resolveUrl(baseId, id) {
id = normalizeId(id);
return URI.resolve(baseId, id);
}
function resolveIds(schema) {
var schemaId = normalizeId(this._getId(schema));
var baseIds = {
'': schemaId
};
var fullPaths = {
'': getFullPath(schemaId, false)
};
var localRefs = {};
var self = this;
traverse(schema, {
allKeys: true
}, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
if ('' === jsonPtr) return;
var id = self._getId(sch);
var baseId = baseIds[parentJsonPtr];
var fullPath = fullPaths[parentJsonPtr] + '/' + parentKeyword;
if (void 0 !== keyIndex) fullPath += '/' + ('number' == typeof keyIndex ? keyIndex : util.escapeFragment(keyIndex));
if ('string' == typeof id) {
id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
var refVal = self._refs[id];
if ('string' == typeof refVal) refVal = self._refs[refVal];
if (refVal && refVal.schema) {
if (!equal(sch, refVal.schema)) throw new Error('id "' + id + '" resolves to more than one schema');
} else if (id != normalizeId(fullPath)) if ('#' == id[0]) {
if (localRefs[id] && !equal(sch, localRefs[id])) throw new Error('id "' + id + '" resolves to more than one schema');
localRefs[id] = sch;
} else self._refs[id] = fullPath;
}
baseIds[jsonPtr] = baseId;
fullPaths[jsonPtr] = fullPath;
});
return localRefs;
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/rules.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var ruleModules = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/index.js"), toHash = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js").toHash;
module1.exports = function() {
var RULES = [
{
type: 'number',
rules: [
{
maximum: [
'exclusiveMaximum'
]
},
{
minimum: [
'exclusiveMinimum'
]
},
'multipleOf',
'format'
]
},
{
type: 'string',
rules: [
'maxLength',
'minLength',
'pattern',
'format'
]
},
{
type: 'array',
rules: [
'maxItems',
'minItems',
'items',
'contains',
'uniqueItems'
]
},
{
type: 'object',
rules: [
'maxProperties',
'minProperties',
'required',
'dependencies',
'propertyNames',
{
properties: [
'additionalProperties',
'patternProperties'
]
}
]
},
{
rules: [
'$ref',
'const',
'enum',
'not',
'anyOf',
'oneOf',
'allOf',
'if'
]
}
];
var ALL = [
'type',
'$comment'
];
var KEYWORDS = [
'$schema',
'$id',
'id',
'$data',
'$async',
'title',
"description",
'default',
'definitions',
'examples',
'readOnly',
'writeOnly',
'contentMediaType',
'contentEncoding',
'additionalItems',
'then',
'else'
];
var TYPES = [
'number',
'integer',
'string',
'array',
'object',
'boolean',
'null'
];
RULES.all = toHash(ALL);
RULES.types = toHash(TYPES);
RULES.forEach(function(group) {
group.rules = group.rules.map(function(keyword) {
var implKeywords;
if ('object' == typeof keyword) {
var key = Object.keys(keyword)[0];
implKeywords = keyword[key];
keyword = key;
implKeywords.forEach(function(k) {
ALL.push(k);
RULES.all[k] = true;
});
}
ALL.push(keyword);
var rule = RULES.all[keyword] = {
keyword: keyword,
code: ruleModules[keyword],
implements: implKeywords
};
return rule;
});
RULES.all.$comment = {
keyword: '$comment',
code: ruleModules.$comment
};
if (group.type) RULES.types[group.type] = group;
});
RULES.keywords = toHash(ALL.concat(KEYWORDS));
RULES.custom = {};
return RULES;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/schema_obj.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var util = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js");
module1.exports = SchemaObject;
function SchemaObject(obj) {
util.copy(obj, this);
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/ucs2length.js": function(module1) {
"use strict";
module1.exports = function(str) {
var length = 0, len = str.length, pos = 0, value;
while(pos < len){
length++;
value = str.charCodeAt(pos++);
if (value >= 0xD800 && value <= 0xDBFF && pos < len) {
value = str.charCodeAt(pos);
if ((0xFC00 & value) == 0xDC00) pos++;
}
}
return length;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
module1.exports = {
copy: copy,
checkDataType: checkDataType,
checkDataTypes: checkDataTypes,
coerceToTypes: coerceToTypes,
toHash: toHash,
getProperty: getProperty,
escapeQuotes: escapeQuotes,
equal: __webpack_require__("./node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"),
ucs2length: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/ucs2length.js"),
varOccurences: varOccurences,
varReplace: varReplace,
schemaHasRules: schemaHasRules,
schemaHasRulesExcept: schemaHasRulesExcept,
schemaUnknownRules: schemaUnknownRules,
toQuotedString: toQuotedString,
getPathExpr: getPathExpr,
getPath: getPath,
getData: getData,
unescapeFragment: unescapeFragment,
unescapeJsonPointer: unescapeJsonPointer,
escapeFragment: escapeFragment,
escapeJsonPointer: escapeJsonPointer
};
function copy(o, to) {
to = to || {};
for(var key in o)to[key] = o[key];
return to;
}
function checkDataType(dataType, data, strictNumbers, negate) {
var EQUAL = negate ? ' !== ' : ' === ', AND = negate ? ' || ' : ' && ', OK = negate ? '!' : '', NOT = negate ? '' : '!';
switch(dataType){
case 'null':
return data + EQUAL + 'null';
case 'array':
return OK + 'Array.isArray(' + data + ')';
case 'object':
return '(' + OK + data + AND + 'typeof ' + data + EQUAL + '"object"' + AND + NOT + 'Array.isArray(' + data + '))';
case 'integer':
return '(typeof ' + data + EQUAL + '"number"' + AND + NOT + '(' + data + ' % 1)' + AND + data + EQUAL + data + (strictNumbers ? AND + OK + 'isFinite(' + data + ')' : '') + ')';
case 'number':
return '(typeof ' + data + EQUAL + '"' + dataType + '"' + (strictNumbers ? AND + OK + 'isFinite(' + data + ')' : '') + ')';
default:
return 'typeof ' + data + EQUAL + '"' + dataType + '"';
}
}
function checkDataTypes(dataTypes, data, strictNumbers) {
switch(dataTypes.length){
case 1:
return checkDataType(dataTypes[0], data, strictNumbers, true);
default:
var code = '';
var types = toHash(dataTypes);
if (types.array && types.object) {
code = types.null ? '(' : '(!' + data + ' || ';
code += 'typeof ' + data + ' !== "object")';
delete types.null;
delete types.array;
delete types.object;
}
if (types.number) delete types.integer;
for(var t in types)code += (code ? ' && ' : '') + checkDataType(t, data, strictNumbers, true);
return code;
}
}
var COERCE_TO_TYPES = toHash([
'string',
'number',
'integer',
'boolean',
'null'
]);
function coerceToTypes(optionCoerceTypes, dataTypes) {
if (Array.isArray(dataTypes)) {
var types = [];
for(var i = 0; i < dataTypes.length; i++){
var t = dataTypes[i];
if (COERCE_TO_TYPES[t]) types[types.length] = t;
else if ('array' === optionCoerceTypes && 'array' === t) types[types.length] = t;
}
if (types.length) return types;
} else if (COERCE_TO_TYPES[dataTypes]) return [
dataTypes
];
else if ('array' === optionCoerceTypes && 'array' === dataTypes) return [
'array'
];
}
function toHash(arr) {
var hash = {};
for(var i = 0; i < arr.length; i++)hash[arr[i]] = true;
return hash;
}
var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
var SINGLE_QUOTE = /'|\\/g;
function getProperty(key) {
return 'number' == typeof key ? '[' + key + ']' : IDENTIFIER.test(key) ? '.' + key : "['" + escapeQuotes(key) + "']";
}
function escapeQuotes(str) {
return str.replace(SINGLE_QUOTE, '\\$&').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\f/g, '\\f').replace(/\t/g, '\\t');
}
function varOccurences(str, dataVar) {
dataVar += '[^0-9]';
var matches = str.match(new RegExp(dataVar, 'g'));
return matches ? matches.length : 0;
}
function varReplace(str, dataVar, expr) {
dataVar += '([^0-9])';
expr = expr.replace(/\$/g, '$$$$');
return str.replace(new RegExp(dataVar, 'g'), expr + '$1');
}
function schemaHasRules(schema, rules) {
if ('boolean' == typeof schema) return !schema;
for(var key in schema)if (rules[key]) return true;
}
function schemaHasRulesExcept(schema, rules, exceptKeyword) {
if ('boolean' == typeof schema) return !schema && 'not' != exceptKeyword;
for(var key in schema)if (key != exceptKeyword && rules[key]) return true;
}
function schemaUnknownRules(schema, rules) {
if ('boolean' == typeof schema) return;
for(var key in schema)if (!rules[key]) return key;
}
function toQuotedString(str) {
return '\'' + escapeQuotes(str) + '\'';
}
function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
var path = jsonPointers ? '\'/\' + ' + expr + (isNumber ? '' : '.replace(/~/g, \'~0\').replace(/\\//g, \'~1\')') : isNumber ? '\'[\' + ' + expr + ' + \']\'' : '\'[\\\'\' + ' + expr + ' + \'\\\']\'';
return joinPaths(currentPath, path);
}
function getPath(currentPath, prop, jsonPointers) {
var path = jsonPointers ? toQuotedString('/' + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
return joinPaths(currentPath, path);
}
var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
function getData($data, lvl, paths) {
var up, jsonPointer, data, matches;
if ('' === $data) return 'rootData';
if ('/' == $data[0]) {
if (!JSON_POINTER.test($data)) throw new Error('Invalid JSON-pointer: ' + $data);
jsonPointer = $data;
data = 'rootData';
} else {
matches = $data.match(RELATIVE_JSON_POINTER);
if (!matches) throw new Error('Invalid JSON-pointer: ' + $data);
up = +matches[1];
jsonPointer = matches[2];
if ('#' == jsonPointer) {
if (up >= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
return paths[lvl - up];
}
if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
data = 'data' + (lvl - up || '');
if (!jsonPointer) return data;
}
var expr = data;
var segments = jsonPointer.split('/');
for(var i = 0; i < segments.length; i++){
var segment = segments[i];
if (segment) {
data += getProperty(unescapeJsonPointer(segment));
expr += ' && ' + data;
}
}
return expr;
}
function joinPaths(a, b) {
if ('""' == a) return b;
return (a + ' + ' + b).replace(/([^\\])' \+ '/g, '$1');
}
function unescapeFragment(str) {
return unescapeJsonPointer(decodeURIComponent(str));
}
function escapeFragment(str) {
return encodeURIComponent(escapeJsonPointer(str));
}
function escapeJsonPointer(str) {
return str.replace(/~/g, '~0').replace(/\//g, '~1');
}
function unescapeJsonPointer(str) {
return str.replace(/~1/g, '/').replace(/~0/g, '~');
}
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/data.js": function(module1) {
"use strict";
var KEYWORDS = [
'multipleOf',
'maximum',
'exclusiveMaximum',
'minimum',
'exclusiveMinimum',
'maxLength',
'minLength',
'pattern',
'additionalItems',
'maxItems',
'minItems',
'uniqueItems',
'maxProperties',
'minProperties',
'required',
'additionalProperties',
'enum',
'format',
'const'
];
module1.exports = function(metaSchema, keywordsJsonPointers) {
for(var i = 0; i < keywordsJsonPointers.length; i++){
metaSchema = JSON.parse(JSON.stringify(metaSchema));
var segments = keywordsJsonPointers[i].split('/');
var keywords = metaSchema;
var j;
for(j = 1; j < segments.length; j++)keywords = keywords[segments[j]];
for(j = 0; j < KEYWORDS.length; j++){
var key = KEYWORDS[j];
var schema = keywords[key];
if (schema) keywords[key] = {
anyOf: [
schema,
{
$ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#'
}
]
};
}
}
return metaSchema;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/definition_schema.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var metaSchema = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/refs/json-schema-draft-07.json");
module1.exports = {
$id: 'https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js',
definitions: {
simpleTypes: metaSchema.definitions.simpleTypes
},
type: 'object',
dependencies: {
schema: [
'validate'
],
$data: [
'validate'
],
statements: [
'inline'
],
valid: {
not: {
required: [
'macro'
]
}
}
},
properties: {
type: metaSchema.properties.type,
schema: {
type: 'boolean'
},
statements: {
type: 'boolean'
},
dependencies: {
type: 'array',
items: {
type: 'string'
}
},
metaSchema: {
type: 'object'
},
modifying: {
type: 'boolean'
},
valid: {
type: 'boolean'
},
$data: {
type: 'boolean'
},
async: {
type: 'boolean'
},
errors: {
anyOf: [
{
type: 'boolean'
},
{
const: 'full'
}
]
}
}
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limit.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
var $isMax = 'maximum' == $keyword, $exclusiveKeyword = $isMax ? 'exclusiveMaximum' : 'exclusiveMinimum', $schemaExcl = it.schema[$exclusiveKeyword], $isDataExcl = it.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? '<' : '>', $notOp = $isMax ? '>' : '<', $errorKeyword = void 0;
if (!($isData || 'number' == typeof $schema || void 0 === $schema)) throw new Error($keyword + ' must be number');
if (!($isDataExcl || void 0 === $schemaExcl || 'number' == typeof $schemaExcl || 'boolean' == typeof $schemaExcl)) throw new Error($exclusiveKeyword + ' must be number or boolean');
if ($isDataExcl) {
var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr), $exclusive = 'exclusive' + $lvl, $exclType = 'exclType' + $lvl, $exclIsNumber = 'exclIsNumber' + $lvl, $opExpr = 'op' + $lvl, $opStr = '\' + ' + $opExpr + ' + \'';
out += ' var schemaExcl' + $lvl + ' = ' + $schemaValueExcl + '; ';
$schemaValueExcl = 'schemaExcl' + $lvl;
out += ' var ' + $exclusive + '; var ' + $exclType + ' = typeof ' + $schemaValueExcl + '; if (' + $exclType + ' != \'boolean\' && ' + $exclType + ' != \'undefined\' && ' + $exclType + ' != \'number\') { ';
var $errorKeyword = $exclusiveKeyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
if (false !== it.opts.messages) out += ' , message: \'' + $exclusiveKeyword + ' should be boolean\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } else if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
out += ' ' + $exclType + ' == \'number\' ? ( (' + $exclusive + ' = ' + $schemaValue + ' === undefined || ' + $schemaValueExcl + ' ' + $op + '= ' + $schemaValue + ') ? ' + $data + ' ' + $notOp + '= ' + $schemaValueExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) : ( (' + $exclusive + ' = ' + $schemaValueExcl + ' === true) ? ' + $data + ' ' + $notOp + '= ' + $schemaValue + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { var op' + $lvl + ' = ' + $exclusive + ' ? \'' + $op + '\' : \'' + $op + '=\'; ';
if (void 0 === $schema) {
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaValueExcl;
$isData = $isDataExcl;
}
} else {
var $exclIsNumber = 'number' == typeof $schemaExcl, $opStr = $op;
if ($exclIsNumber && $isData) {
var $opExpr = '\'' + $opStr + '\'';
out += ' if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
out += ' ( ' + $schemaValue + ' === undefined || ' + $schemaExcl + ' ' + $op + '= ' + $schemaValue + ' ? ' + $data + ' ' + $notOp + '= ' + $schemaExcl + ' : ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' ) || ' + $data + ' !== ' + $data + ') { ';
} else {
if ($exclIsNumber && void 0 === $schema) {
$exclusive = true;
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$schemaValue = $schemaExcl;
$notOp += '=';
} else {
if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
$exclusive = true;
$errorKeyword = $exclusiveKeyword;
$errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
$notOp += '=';
} else {
$exclusive = false;
$opStr += '=';
}
}
var $opExpr = '\'' + $opStr + '\'';
out += ' if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
out += ' ' + $data + ' ' + $notOp + ' ' + $schemaValue + ' || ' + $data + ' !== ' + $data + ') { ';
}
}
$errorKeyword = $errorKeyword || $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { comparison: ' + $opExpr + ', limit: ' + $schemaValue + ', exclusive: ' + $exclusive + ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should be ' + $opStr + ' ';
if ($isData) out += '\' + ' + $schemaValue;
else out += '' + $schemaValue + '\'';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + $schema;
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitItems.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
if (!($isData || 'number' == typeof $schema)) throw new Error($keyword + ' must be number');
var $op = 'maxItems' == $keyword ? '>' : '<';
out += 'if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
out += ' ' + $data + '.length ' + $op + ' ' + $schemaValue + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should NOT have ';
if ('maxItems' == $keyword) out += 'more';
else out += 'fewer';
out += ' than ';
if ($isData) out += '\' + ' + $schemaValue + ' + \'';
else out += '' + $schema;
out += ' items\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + $schema;
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += '} ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitLength.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
if (!($isData || 'number' == typeof $schema)) throw new Error($keyword + ' must be number');
var $op = 'maxLength' == $keyword ? '>' : '<';
out += 'if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
if (false === it.opts.unicode) out += ' ' + $data + '.length ';
else out += ' ucs2length(' + $data + ') ';
out += ' ' + $op + ' ' + $schemaValue + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should NOT be ';
if ('maxLength' == $keyword) out += 'longer';
else out += 'shorter';
out += ' than ';
if ($isData) out += '\' + ' + $schemaValue + ' + \'';
else out += '' + $schema;
out += ' characters\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + $schema;
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += '} ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitProperties.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
if (!($isData || 'number' == typeof $schema)) throw new Error($keyword + ' must be number');
var $op = 'maxProperties' == $keyword ? '>' : '<';
out += 'if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'number\') || ';
out += ' Object.keys(' + $data + ').length ' + $op + ' ' + $schemaValue + ') { ';
var $errorKeyword = $keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schemaValue + ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should NOT have ';
if ('maxProperties' == $keyword) out += 'more';
else out += 'fewer';
out += ' than ';
if ($isData) out += '\' + ' + $schemaValue + ' + \'';
else out += '' + $schema;
out += ' properties\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + $schema;
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += '} ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/allOf.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $currentBaseId = $it.baseId, $allSchemasEmpty = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1, l1 = arr1.length - 1;
while($i < l1){
$sch = arr1[$i += 1];
if (it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all)) {
$allSchemasEmpty = false;
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
}
}
if ($breakOnError) if ($allSchemasEmpty) out += ' if (true) { ';
else out += ' ' + $closingBraces.slice(0, -1) + ' ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/anyOf.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $noEmptySchema = $schema.every(function($sch) {
return it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all);
});
if ($noEmptySchema) {
var $currentBaseId = $it.baseId;
out += ' var ' + $errs + ' = errors; var ' + $valid + ' = false; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1, l1 = arr1.length - 1;
while($i < l1){
$sch = arr1[$i += 1];
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
out += ' ' + $valid + ' = ' + $valid + ' || ' + $nextValid + '; if (!' + $valid + ') { ';
$closingBraces += '}';
}
}
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + $closingBraces + ' if (!' + $valid + ') { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
if (false !== it.opts.messages) out += ' , message: \'should match some schema in anyOf\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError(vErrors); ';
else out += ' validate.errors = vErrors; return false; ';
out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
if (it.opts.allErrors) out += ' } ';
} else if ($breakOnError) out += ' if (true) { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/comment.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $schema = it.schema[$keyword];
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
it.opts.allErrors;
var $comment = it.util.toQuotedString($schema);
if (true === it.opts.$comment) out += ' console.log(' + $comment + ');';
else if ('function' == typeof it.opts.$comment) out += ' self._opts.$comment(' + $comment + ', ' + it.util.toQuotedString($errSchemaPath) + ', validate.root.schema);';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/const.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.$data && $schema && $schema.$data;
if ($isData) out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
if (!$isData) out += ' var schema' + $lvl + ' = validate.schema' + $schemaPath + ';';
out += 'var ' + $valid + ' = equal(' + $data + ', schema' + $lvl + '); if (!' + $valid + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValue: schema' + $lvl + ' } ';
if (false !== it.opts.messages) out += ' , message: \'should be equal to constant\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' }';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/contains.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId, $nonEmptySchema = it.opts.strictKeywords ? 'object' == typeof $schema && Object.keys($schema).length > 0 || false === $schema : it.util.schemaHasRules($schema, it.RULES.all);
out += 'var ' + $errs + ' = errors;var ' + $valid + ';';
if ($nonEmptySchema) {
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + $nextValid + ' = false; for (var ' + $idx + ' = 0; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
out += ' if (' + $nextValid + ') break; } ';
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + $closingBraces + ' if (!' + $nextValid + ') {';
} else out += ' if (' + $data + '.length == 0) {';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
if (false !== it.opts.messages) out += ' , message: \'should contain a valid item\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } else { ';
if ($nonEmptySchema) out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
if (it.opts.allErrors) out += ' } ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/custom.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
var $rule = this, $definition = 'definition' + $lvl, $rDef = $rule.definition, $closingBraces = '';
var $compile, $inline, $macro, $ruleValidate, $validateCode;
if ($isData && $rDef.$data) {
$validateCode = 'keywordValidate' + $lvl;
var $validateSchema = $rDef.validateSchema;
out += ' var ' + $definition + ' = RULES.custom[\'' + $keyword + '\'].definition; var ' + $validateCode + ' = ' + $definition + '.validate;';
} else {
$ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
if (!$ruleValidate) return;
$schemaValue = 'validate.schema' + $schemaPath;
$validateCode = $ruleValidate.code;
$compile = $rDef.compile;
$inline = $rDef.inline;
$macro = $rDef.macro;
}
var $ruleErrs = $validateCode + '.errors', $i = 'i' + $lvl, $ruleErr = 'ruleErr' + $lvl, $asyncKeyword = $rDef.async;
if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
if (!($inline || $macro)) out += '' + $ruleErrs + ' = null;';
out += 'var ' + $errs + ' = errors;var ' + $valid + ';';
if ($isData && $rDef.$data) {
$closingBraces += '}';
out += ' if (' + $schemaValue + ' === undefined) { ' + $valid + ' = true; } else { ';
if ($validateSchema) {
$closingBraces += '}';
out += ' ' + $valid + ' = ' + $definition + '.validateSchema(' + $schemaValue + '); if (' + $valid + ') { ';
}
}
if ($inline) if ($rDef.statements) out += ' ' + $ruleValidate.validate + ' ';
else out += ' ' + $valid + ' = ' + $ruleValidate.validate + '; ';
else if ($macro) {
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
$it.schema = $ruleValidate.validate;
$it.schemaPath = '';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' ' + $code;
} else {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
out += ' ' + $validateCode + '.call( ';
if (it.opts.passContext) out += 'this';
else out += 'self';
if ($compile || false === $rDef.schema) out += ' , ' + $data + ' ';
else out += ' , ' + $schemaValue + ' , ' + $data + ' , validate.schema' + it.schemaPath + ' ';
out += ' , (dataPath || \'\')';
if ('""' != it.errorPath) out += ' + ' + it.errorPath;
var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' , ' + $parentData + ' , ' + $parentDataProperty + ' , rootData ) ';
var def_callRuleValidate = out;
out = $$outStack.pop();
if (false === $rDef.errors) {
out += ' ' + $valid + ' = ';
if ($asyncKeyword) out += 'await ';
out += '' + def_callRuleValidate + '; ';
} else if ($asyncKeyword) {
$ruleErrs = 'customErrors' + $lvl;
out += ' var ' + $ruleErrs + ' = null; try { ' + $valid + ' = await ' + def_callRuleValidate + '; } catch (e) { ' + $valid + ' = false; if (e instanceof ValidationError) ' + $ruleErrs + ' = e.errors; else throw e; } ';
} else out += ' ' + $ruleErrs + ' = null; ' + $valid + ' = ' + def_callRuleValidate + '; ';
}
if ($rDef.modifying) out += ' if (' + $parentData + ') ' + $data + ' = ' + $parentData + '[' + $parentDataProperty + '];';
out += '' + $closingBraces;
if ($rDef.valid) {
if ($breakOnError) out += ' if (true) { ';
} else {
out += ' if ( ';
if (void 0 === $rDef.valid) {
out += ' !';
if ($macro) out += '' + $nextValid;
else out += '' + $valid;
} else out += ' ' + !$rDef.valid + ' ';
out += ') { ';
$errorKeyword = $rule.keyword;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { keyword: \'' + $rule.keyword + '\' } ';
if (false !== it.opts.messages) out += ' , message: \'should pass "' + $rule.keyword + '" keyword validation\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
var def_customError = out;
out = $$outStack.pop();
if ($inline) if ($rDef.errors) {
if ('full' != $rDef.errors) {
out += ' for (var ' + $i + '=' + $errs + '; ' + $i + '<errors; ' + $i + '++) { var ' + $ruleErr + ' = vErrors[' + $i + ']; if (' + $ruleErr + '.dataPath === undefined) ' + $ruleErr + '.dataPath = (dataPath || \'\') + ' + it.errorPath + '; if (' + $ruleErr + '.schemaPath === undefined) { ' + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
if (it.opts.verbose) out += ' ' + $ruleErr + '.schema = ' + $schemaValue + '; ' + $ruleErr + '.data = ' + $data + '; ';
out += ' } ';
}
} else if (false === $rDef.errors) out += ' ' + def_customError + ' ';
else {
out += ' if (' + $errs + ' == errors) { ' + def_customError + ' } else { for (var ' + $i + '=' + $errs + '; ' + $i + '<errors; ' + $i + '++) { var ' + $ruleErr + ' = vErrors[' + $i + ']; if (' + $ruleErr + '.dataPath === undefined) ' + $ruleErr + '.dataPath = (dataPath || \'\') + ' + it.errorPath + '; if (' + $ruleErr + '.schemaPath === undefined) { ' + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; } ';
if (it.opts.verbose) out += ' ' + $ruleErr + '.schema = ' + $schemaValue + '; ' + $ruleErr + '.data = ' + $data + '; ';
out += ' } } ';
}
else if ($macro) {
out += ' var err = ';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { keyword: \'' + $rule.keyword + '\' } ';
if (false !== it.opts.messages) out += ' , message: \'should pass "' + $rule.keyword + '" keyword validation\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError(vErrors); ';
else out += ' validate.errors = vErrors; return false; ';
} else if (false === $rDef.errors) out += ' ' + def_customError + ' ';
else {
out += ' if (Array.isArray(' + $ruleErrs + ')) { if (vErrors === null) vErrors = ' + $ruleErrs + '; else vErrors = vErrors.concat(' + $ruleErrs + '); errors = vErrors.length; for (var ' + $i + '=' + $errs + '; ' + $i + '<errors; ' + $i + '++) { var ' + $ruleErr + ' = vErrors[' + $i + ']; if (' + $ruleErr + '.dataPath === undefined) ' + $ruleErr + '.dataPath = (dataPath || \'\') + ' + it.errorPath + '; ' + $ruleErr + '.schemaPath = "' + $errSchemaPath + '"; ';
if (it.opts.verbose) out += ' ' + $ruleErr + '.schema = ' + $schemaValue + '; ' + $ruleErr + '.data = ' + $data + '; ';
out += ' } } else { ' + def_customError + ' } ';
}
out += ' } ';
if ($breakOnError) out += ' else { ';
}
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/dependencies.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it.opts.ownProperties;
for($property in $schema)if ('__proto__' != $property) {
var $sch = $schema[$property];
var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
$deps[$property] = $sch;
}
out += 'var ' + $errs + ' = errors;';
var $currentErrorPath = it.errorPath;
out += 'var missing' + $lvl + ';';
for(var $property in $propertyDeps){
$deps = $propertyDeps[$property];
if ($deps.length) {
out += ' if ( ' + $data + it.util.getProperty($property) + ' !== undefined ';
if ($ownProperties) out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') ';
if ($breakOnError) {
out += ' && ( ';
var arr1 = $deps;
if (arr1) {
var $propertyKey, $i = -1, l1 = arr1.length - 1;
while($i < l1){
$propertyKey = arr1[$i += 1];
if ($i) out += ' || ';
var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
out += ' ( ( ' + $useData + ' === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) ';
}
}
out += ')) { ';
var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes(1 == $deps.length ? $deps[0] : $deps.join(", ")) + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should have ';
if (1 == $deps.length) out += 'property ' + it.util.escapeQuotes($deps[0]);
else out += 'properties ' + it.util.escapeQuotes($deps.join(", "));
out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
} else {
out += ' ) { ';
var arr2 = $deps;
if (arr2) {
var $propertyKey, i2 = -1, l2 = arr2.length - 1;
while(i2 < l2){
$propertyKey = arr2[i2 += 1];
var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
if (it.opts._errorDataPathProperty) it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
out += ' if ( ' + $useData + ' === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ') { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { property: \'' + it.util.escapeQuotes($property) + '\', missingProperty: \'' + $missingProperty + '\', depsCount: ' + $deps.length + ', deps: \'' + it.util.escapeQuotes(1 == $deps.length ? $deps[0] : $deps.join(", ")) + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should have ';
if (1 == $deps.length) out += 'property ' + it.util.escapeQuotes($deps[0]);
else out += 'properties ' + it.util.escapeQuotes($deps.join(", "));
out += ' when property ' + it.util.escapeQuotes($property) + ' is present\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
}
}
}
out += ' } ';
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
}
}
it.errorPath = $currentErrorPath;
var $currentBaseId = $it.baseId;
for(var $property in $schemaDeps){
var $sch = $schemaDeps[$property];
if (it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all)) {
out += ' ' + $nextValid + ' = true; if ( ' + $data + it.util.getProperty($property) + ' !== undefined ';
if ($ownProperties) out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($property) + '\') ';
out += ') { ';
$it.schema = $sch;
$it.schemaPath = $schemaPath + it.util.getProperty($property);
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
out += ' } ';
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
}
if ($breakOnError) out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/enum.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.$data && $schema && $schema.$data;
if ($isData) out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
var $i = 'i' + $lvl, $vSchema = 'schema' + $lvl;
if (!$isData) out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + ';';
out += 'var ' + $valid + ';';
if ($isData) out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {';
out += '' + $valid + ' = false;for (var ' + $i + '=0; ' + $i + '<' + $vSchema + '.length; ' + $i + '++) if (equal(' + $data + ', ' + $vSchema + '[' + $i + '])) { ' + $valid + ' = true; break; }';
if ($isData) out += ' } ';
out += ' if (!' + $valid + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { allowedValues: schema' + $lvl + ' } ';
if (false !== it.opts.messages) out += ' , message: \'should be equal to one of the allowed values\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' }';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/format.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
if (false === it.opts.format) {
if ($breakOnError) out += ' if (true) { ';
return out;
}
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
var $unknownFormats = it.opts.unknownFormats, $allowUnknown = Array.isArray($unknownFormats);
if ($isData) {
var $format = 'format' + $lvl, $isObject = 'isObject' + $lvl, $formatType = 'formatType' + $lvl;
out += ' var ' + $format + ' = formats[' + $schemaValue + ']; var ' + $isObject + ' = typeof ' + $format + ' == \'object\' && !(' + $format + ' instanceof RegExp) && ' + $format + '.validate; var ' + $formatType + ' = ' + $isObject + ' && ' + $format + '.type || \'string\'; if (' + $isObject + ') { ';
if (it.async) out += ' var async' + $lvl + ' = ' + $format + '.async; ';
out += ' ' + $format + ' = ' + $format + '.validate; } if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || ';
out += ' (';
if ('ignore' != $unknownFormats) {
out += ' (' + $schemaValue + ' && !' + $format + ' ';
if ($allowUnknown) out += ' && self._opts.unknownFormats.indexOf(' + $schemaValue + ') == -1 ';
out += ') || ';
}
out += ' (' + $format + ' && ' + $formatType + ' == \'' + $ruleType + '\' && !(typeof ' + $format + ' == \'function\' ? ';
if (it.async) out += ' (async' + $lvl + ' ? await ' + $format + '(' + $data + ') : ' + $format + '(' + $data + ')) ';
else out += ' ' + $format + '(' + $data + ') ';
out += ' : ' + $format + '.test(' + $data + '))))) {';
} else {
var $format = it.formats[$schema];
if (!$format) if ('ignore' == $unknownFormats) {
it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
if ($breakOnError) out += ' if (true) { ';
return out;
} else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
if ($breakOnError) out += ' if (true) { ';
return out;
} else throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
var $isObject = 'object' == typeof $format && !($format instanceof RegExp) && $format.validate;
var $formatType = $isObject && $format.type || 'string';
if ($isObject) {
var $async = true === $format.async;
$format = $format.validate;
}
if ($formatType != $ruleType) {
if ($breakOnError) out += ' if (true) { ';
return out;
}
if ($async) {
if (!it.async) throw new Error('async format in sync schema');
var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
out += ' if (!(await ' + $formatRef + '(' + $data + '))) { ';
} else {
out += ' if (! ';
var $formatRef = 'formats' + it.util.getProperty($schema);
if ($isObject) $formatRef += '.validate';
if ('function' == typeof $format) out += ' ' + $formatRef + '(' + $data + ') ';
else out += ' ' + $formatRef + '.test(' + $data + ') ';
out += ') { ';
}
}
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { format: ';
if ($isData) out += '' + $schemaValue;
else out += '' + it.util.toQuotedString($schema);
out += ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should match format "';
if ($isData) out += '\' + ' + $schemaValue + ' + \'';
else out += '' + it.util.escapeQuotes($schema);
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + it.util.toQuotedString($schema);
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/if.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
var $thenSch = it.schema['then'], $elseSch = it.schema['else'], $thenPresent = void 0 !== $thenSch && (it.opts.strictKeywords ? 'object' == typeof $thenSch && Object.keys($thenSch).length > 0 || false === $thenSch : it.util.schemaHasRules($thenSch, it.RULES.all)), $elsePresent = void 0 !== $elseSch && (it.opts.strictKeywords ? 'object' == typeof $elseSch && Object.keys($elseSch).length > 0 || false === $elseSch : it.util.schemaHasRules($elseSch, it.RULES.all)), $currentBaseId = $it.baseId;
if ($thenPresent || $elsePresent) {
var $ifClause;
$it.createErrors = false;
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + $errs + ' = errors; var ' + $valid + ' = true; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
$it.createErrors = true;
out += ' errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
it.compositeRule = $it.compositeRule = $wasComposite;
if ($thenPresent) {
out += ' if (' + $nextValid + ') { ';
$it.schema = it.schema['then'];
$it.schemaPath = it.schemaPath + '.then';
$it.errSchemaPath = it.errSchemaPath + '/then';
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
out += ' ' + $valid + ' = ' + $nextValid + '; ';
if ($thenPresent && $elsePresent) {
$ifClause = 'ifClause' + $lvl;
out += ' var ' + $ifClause + ' = \'then\'; ';
} else $ifClause = '\'then\'';
out += ' } ';
if ($elsePresent) out += ' else { ';
} else out += ' if (!' + $nextValid + ') { ';
if ($elsePresent) {
$it.schema = it.schema['else'];
$it.schemaPath = it.schemaPath + '.else';
$it.errSchemaPath = it.errSchemaPath + '/else';
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
out += ' ' + $valid + ' = ' + $nextValid + '; ';
if ($thenPresent && $elsePresent) {
$ifClause = 'ifClause' + $lvl;
out += ' var ' + $ifClause + ' = \'else\'; ';
} else $ifClause = '\'else\'';
out += ' } ';
}
out += ' if (!' + $valid + ') { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { failingKeyword: ' + $ifClause + ' } ';
if (false !== it.opts.messages) out += ' , message: \'should match "\' + ' + $ifClause + ' + \'" schema\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError(vErrors); ';
else out += ' validate.errors = vErrors; return false; ';
out += ' } ';
if ($breakOnError) out += ' else { ';
} else if ($breakOnError) out += ' if (true) { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
module1.exports = {
$ref: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/ref.js"),
allOf: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/allOf.js"),
anyOf: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/anyOf.js"),
$comment: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/comment.js"),
const: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/const.js"),
contains: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/contains.js"),
dependencies: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/dependencies.js"),
enum: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/enum.js"),
format: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/format.js"),
if: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/if.js"),
items: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/items.js"),
maximum: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limit.js"),
minimum: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limit.js"),
maxItems: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitItems.js"),
minItems: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitItems.js"),
maxLength: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitLength.js"),
minLength: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitLength.js"),
maxProperties: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitProperties.js"),
minProperties: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitProperties.js"),
multipleOf: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/multipleOf.js"),
not: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/not.js"),
oneOf: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/oneOf.js"),
pattern: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/pattern.js"),
properties: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/properties.js"),
propertyNames: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/propertyNames.js"),
required: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/required.js"),
uniqueItems: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/uniqueItems.js"),
validate: __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/validate.js")
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/items.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $idx = 'i' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $currentBaseId = it.baseId;
out += 'var ' + $errs + ' = errors;var ' + $valid + ';';
if (Array.isArray($schema)) {
var $additionalItems = it.schema.additionalItems;
if (false === $additionalItems) {
out += ' ' + $valid + ' = ' + $data + '.length <= ' + $schema.length + '; ';
var $currErrSchemaPath = $errSchemaPath;
$errSchemaPath = it.errSchemaPath + '/additionalItems';
out += ' if (!' + $valid + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { limit: ' + $schema.length + ' } ';
if (false !== it.opts.messages) out += ' , message: \'should NOT have more than ' + $schema.length + ' items\' ';
if (it.opts.verbose) out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } ';
$errSchemaPath = $currErrSchemaPath;
if ($breakOnError) {
$closingBraces += '}';
out += ' else { ';
}
}
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1, l1 = arr1.length - 1;
while($i < l1){
$sch = arr1[$i += 1];
if (it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all)) {
out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $i + ') { ';
var $passData = $data + '[' + $i + ']';
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
$it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
$it.dataPathArr[$dataNxt] = $i;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
out += ' } ';
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
}
}
if ('object' == typeof $additionalItems && (it.opts.strictKeywords ? 'object' == typeof $additionalItems && Object.keys($additionalItems).length > 0 || false === $additionalItems : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
$it.schema = $additionalItems;
$it.schemaPath = it.schemaPath + '.additionalItems';
$it.errSchemaPath = it.errSchemaPath + '/additionalItems';
out += ' ' + $nextValid + ' = true; if (' + $data + '.length > ' + $schema.length + ') { for (var ' + $idx + ' = ' + $schema.length + '; ' + $idx + ' < ' + $data + '.length; ' + $idx + '++) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
if ($breakOnError) out += ' if (!' + $nextValid + ') break; ';
out += ' } } ';
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
} else if (it.opts.strictKeywords ? 'object' == typeof $schema && Object.keys($schema).length > 0 || false === $schema : it.util.schemaHasRules($schema, it.RULES.all)) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' for (var ' + $idx + " = 0; " + $idx + ' < ' + $data + '.length; ' + $idx + '++) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
var $passData = $data + '[' + $idx + ']';
$it.dataPathArr[$dataNxt] = $idx;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
if ($breakOnError) out += ' if (!' + $nextValid + ') break; ';
out += ' }';
}
if ($breakOnError) out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/multipleOf.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
if (!($isData || 'number' == typeof $schema)) throw new Error($keyword + ' must be number');
out += 'var division' + $lvl + ';if (';
if ($isData) out += ' ' + $schemaValue + ' !== undefined && ( typeof ' + $schemaValue + ' != \'number\' || ';
out += ' (division' + $lvl + ' = ' + $data + ' / ' + $schemaValue + ', ';
if (it.opts.multipleOfPrecision) out += ' Math.abs(Math.round(division' + $lvl + ') - division' + $lvl + ') > 1e-' + it.opts.multipleOfPrecision + ' ';
else out += ' division' + $lvl + ' !== parseInt(division' + $lvl + ') ';
out += ' ) ';
if ($isData) out += ' ) ';
out += ' ) { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { multipleOf: ' + $schemaValue + ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should be multiple of ';
if ($isData) out += '\' + ' + $schemaValue;
else out += '' + $schemaValue + '\'';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + $schema;
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += '} ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/not.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
if (it.opts.strictKeywords ? 'object' == typeof $schema && Object.keys($schema).length > 0 || false === $schema : it.util.schemaHasRules($schema, it.RULES.all)) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
out += ' var ' + $errs + ' = errors; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.createErrors = false;
var $allErrorsOption;
if ($it.opts.allErrors) {
$allErrorsOption = $it.opts.allErrors;
$it.opts.allErrors = false;
}
out += ' ' + it.validate($it) + ' ';
$it.createErrors = true;
if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' if (' + $nextValid + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
if (false !== it.opts.messages) out += ' , message: \'should NOT be valid\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; } ';
if (it.opts.allErrors) out += ' } ';
} else {
out += ' var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
if (false !== it.opts.messages) out += ' , message: \'should NOT be valid\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if ($breakOnError) out += ' if (false) { ';
}
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/oneOf.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $currentBaseId = $it.baseId, $prevValid = 'prevValid' + $lvl, $passingSchemas = 'passingSchemas' + $lvl;
out += 'var ' + $errs + ' = errors , ' + $prevValid + ' = false , ' + $valid + ' = false , ' + $passingSchemas + ' = null; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var arr1 = $schema;
if (arr1) {
var $sch, $i = -1, l1 = arr1.length - 1;
while($i < l1){
$sch = arr1[$i += 1];
if (it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
$it.schemaPath = $schemaPath + '[' + $i + ']';
$it.errSchemaPath = $errSchemaPath + '/' + $i;
out += ' ' + it.validate($it) + ' ';
$it.baseId = $currentBaseId;
} else out += ' var ' + $nextValid + ' = true; ';
if ($i) {
out += ' if (' + $nextValid + ' && ' + $prevValid + ') { ' + $valid + ' = false; ' + $passingSchemas + ' = [' + $passingSchemas + ', ' + $i + ']; } else { ';
$closingBraces += '}';
}
out += ' if (' + $nextValid + ') { ' + $valid + ' = ' + $prevValid + ' = true; ' + $passingSchemas + ' = ' + $i + '; }';
}
}
it.compositeRule = $it.compositeRule = $wasComposite;
out += '' + $closingBraces + 'if (!' + $valid + ') { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { passingSchemas: ' + $passingSchemas + ' } ';
if (false !== it.opts.messages) out += ' , message: \'should match exactly one schema in oneOf\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError(vErrors); ';
else out += ' validate.errors = vErrors; return false; ';
out += '} else { errors = ' + $errs + '; if (vErrors !== null) { if (' + $errs + ') vErrors.length = ' + $errs + '; else vErrors = null; }';
if (it.opts.allErrors) out += ' } ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/pattern.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
out += 'if ( ';
if ($isData) out += ' (' + $schemaValue + ' !== undefined && typeof ' + $schemaValue + ' != \'string\') || ';
out += ' !' + $regexp + '.test(' + $data + ') ) { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { pattern: ';
if ($isData) out += '' + $schemaValue;
else out += '' + it.util.toQuotedString($schema);
out += ' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should match pattern "';
if ($isData) out += '\' + ' + $schemaValue + ' + \'';
else out += '' + it.util.escapeQuotes($schema);
out += '"\' ';
}
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + it.util.toQuotedString($schema);
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += '} ';
if ($breakOnError) out += ' else { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/properties.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl;
var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = false === $aProperties, $additionalIsSchema = 'object' == typeof $aProperties && Object.keys($aProperties).length, $removeAdditional = it.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
var $required = it.schema.required;
if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
function notProto(p) {
return '__proto__' !== p;
}
out += 'var ' + $errs + ' = errors;var ' + $nextValid + ' = true;';
if ($ownProperties) out += ' var ' + $dataProperties + ' = undefined;';
if ($checkAdditional) {
if ($ownProperties) out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; ';
else out += ' for (var ' + $key + ' in ' + $data + ') { ';
if ($someProperties) {
out += ' var isAdditional' + $lvl + ' = !(false ';
if ($schemaKeys.length) if ($schemaKeys.length > 8) out += ' || validate.schema' + $schemaPath + '.hasOwnProperty(' + $key + ') ';
else {
var arr1 = $schemaKeys;
if (arr1) {
var $propertyKey, i1 = -1, l1 = arr1.length - 1;
while(i1 < l1){
$propertyKey = arr1[i1 += 1];
out += ' || ' + $key + ' == ' + it.util.toQuotedString($propertyKey) + ' ';
}
}
}
if ($pPropertyKeys.length) {
var arr2 = $pPropertyKeys;
if (arr2) {
var $pProperty, $i = -1, l2 = arr2.length - 1;
while($i < l2){
$pProperty = arr2[$i += 1];
out += ' || ' + it.usePattern($pProperty) + '.test(' + $key + ') ';
}
}
}
out += ' ); if (isAdditional' + $lvl + ') { ';
}
if ('all' == $removeAdditional) out += ' delete ' + $data + '[' + $key + ']; ';
else {
var $currentErrorPath = it.errorPath;
var $additionalProperty = '\' + ' + $key + ' + \'';
if (it.opts._errorDataPathProperty) it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
if ($noAdditional) if ($removeAdditional) out += ' delete ' + $data + '[' + $key + ']; ';
else {
out += ' ' + $nextValid + ' = false; ';
var $currErrSchemaPath = $errSchemaPath;
$errSchemaPath = it.errSchemaPath + '/additionalProperties';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { additionalProperty: \'' + $additionalProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is an invalid additional property';
else out += 'should NOT have additional properties';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
$errSchemaPath = $currErrSchemaPath;
if ($breakOnError) out += ' break; ';
}
else if ($additionalIsSchema) if ('failing' == $removeAdditional) {
out += ' var ' + $errs + ' = errors; ';
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
$it.schema = $aProperties;
$it.schemaPath = it.schemaPath + '.additionalProperties';
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
$it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
out += ' if (!' + $nextValid + ') { errors = ' + $errs + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + $data + '[' + $key + ']; } ';
it.compositeRule = $it.compositeRule = $wasComposite;
} else {
$it.schema = $aProperties;
$it.schemaPath = it.schemaPath + '.additionalProperties';
$it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
$it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
if ($breakOnError) out += ' if (!' + $nextValid + ') break; ';
}
it.errorPath = $currentErrorPath;
}
if ($someProperties) out += ' } ';
out += ' } ';
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
var $useDefaults = it.opts.useDefaults && !it.compositeRule;
if ($schemaKeys.length) {
var arr3 = $schemaKeys;
if (arr3) {
var $propertyKey, i3 = -1, l3 = arr3.length - 1;
while(i3 < l3){
$propertyKey = arr3[i3 += 1];
var $sch = $schema[$propertyKey];
if (it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all)) {
var $prop = it.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && void 0 !== $sch.default;
$it.schema = $sch;
$it.schemaPath = $schemaPath + $prop;
$it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
$it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
$it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) {
$code = it.util.varReplace($code, $nextData, $passData);
var $useData = $passData;
} else {
var $useData = $nextData;
out += ' var ' + $nextData + ' = ' + $passData + '; ';
}
if ($hasDefault) out += ' ' + $code + ' ';
else {
if ($requiredHash && $requiredHash[$propertyKey]) {
out += ' if ( ' + $useData + ' === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ') { ' + $nextValid + ' = false; ';
var $currentErrorPath = it.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it.util.escapeQuotes($propertyKey);
if (it.opts._errorDataPathProperty) it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
$errSchemaPath = it.errSchemaPath + '/required';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is a required property';
else out += 'should have required property \\\'' + $missingProperty + '\\\'';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
$errSchemaPath = $currErrSchemaPath;
it.errorPath = $currentErrorPath;
out += ' } else { ';
} else if ($breakOnError) {
out += ' if ( ' + $useData + ' === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ') { ' + $nextValid + ' = true; } else { ';
} else {
out += ' if (' + $useData + ' !== undefined ';
if ($ownProperties) out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ' ) { ';
}
out += ' ' + $code + ' } ';
}
}
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
}
}
if ($pPropertyKeys.length) {
var arr4 = $pPropertyKeys;
if (arr4) {
var $pProperty, i4 = -1, l4 = arr4.length - 1;
while(i4 < l4){
$pProperty = arr4[i4 += 1];
var $sch = $pProperties[$pProperty];
if (it.opts.strictKeywords ? 'object' == typeof $sch && Object.keys($sch).length > 0 || false === $sch : it.util.schemaHasRules($sch, it.RULES.all)) {
$it.schema = $sch;
$it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
$it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
if ($ownProperties) out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; ';
else out += ' for (var ' + $key + ' in ' + $data + ') { ';
out += ' if (' + it.usePattern($pProperty) + '.test(' + $key + ')) { ';
$it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
var $passData = $data + '[' + $key + ']';
$it.dataPathArr[$dataNxt] = $key;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
if ($breakOnError) out += ' if (!' + $nextValid + ') break; ';
out += ' } ';
if ($breakOnError) out += ' else ' + $nextValid + ' = true; ';
out += ' } ';
if ($breakOnError) {
out += ' if (' + $nextValid + ') { ';
$closingBraces += '}';
}
}
}
}
}
if ($breakOnError) out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/propertyNames.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $errs = 'errs__' + $lvl;
var $it = it.util.copy(it);
var $closingBraces = '';
$it.level++;
var $nextValid = 'valid' + $it.level;
out += 'var ' + $errs + ' = errors;';
if (it.opts.strictKeywords ? 'object' == typeof $schema && Object.keys($schema).length > 0 || false === $schema : it.util.schemaHasRules($schema, it.RULES.all)) {
$it.schema = $schema;
$it.schemaPath = $schemaPath;
$it.errSchemaPath = $errSchemaPath;
var $key = 'key' + $lvl, $idx = 'idx' + $lvl, $i = 'i' + $lvl, $invalidName = '\' + ' + $key + ' + \'', $dataNxt = $it.dataLevel = it.dataLevel + 1, $nextData = 'data' + $dataNxt, $dataProperties = 'dataProperties' + $lvl, $ownProperties = it.opts.ownProperties, $currentBaseId = it.baseId;
if ($ownProperties) out += ' var ' + $dataProperties + ' = undefined; ';
if ($ownProperties) out += ' ' + $dataProperties + ' = ' + $dataProperties + ' || Object.keys(' + $data + '); for (var ' + $idx + '=0; ' + $idx + '<' + $dataProperties + '.length; ' + $idx + '++) { var ' + $key + ' = ' + $dataProperties + '[' + $idx + ']; ';
else out += ' for (var ' + $key + ' in ' + $data + ') { ';
out += ' var startErrs' + $lvl + ' = errors; ';
var $passData = $key;
var $wasComposite = it.compositeRule;
it.compositeRule = $it.compositeRule = true;
var $code = it.validate($it);
$it.baseId = $currentBaseId;
if (it.util.varOccurences($code, $nextData) < 2) out += ' ' + it.util.varReplace($code, $nextData, $passData) + ' ';
else out += ' var ' + $nextData + ' = ' + $passData + '; ' + $code + ' ';
it.compositeRule = $it.compositeRule = $wasComposite;
out += ' if (!' + $nextValid + ') { for (var ' + $i + '=startErrs' + $lvl + '; ' + $i + '<errors; ' + $i + '++) { vErrors[' + $i + '].propertyName = ' + $key + '; } var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'propertyNames' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { propertyName: \'' + $invalidName + '\' } ';
if (false !== it.opts.messages) out += ' , message: \'property name \\\'' + $invalidName + '\\\' is invalid\' ';
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError(vErrors); ';
else out += ' validate.errors = vErrors; return false; ';
if ($breakOnError) out += ' break; ';
out += ' } }';
}
if ($breakOnError) out += ' ' + $closingBraces + ' if (' + $errs + ' == errors) {';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/ref.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $async, $refCode;
if ('#' == $schema || '#/' == $schema) if (it.isRoot) {
$async = it.async;
$refCode = 'validate';
} else {
$async = true === it.root.schema.$async;
$refCode = 'root.refVal[0]';
}
else {
var $refVal = it.resolveRef(it.baseId, $schema, it.isRoot);
if (void 0 === $refVal) {
var $message = it.MissingRefError.message(it.baseId, $schema);
if ('fail' == it.opts.missingRefs) {
it.logger.error($message);
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { ref: \'' + it.util.escapeQuotes($schema) + '\' } ';
if (false !== it.opts.messages) out += ' , message: \'can\\\'t resolve reference ' + it.util.escapeQuotes($schema) + '\' ';
if (it.opts.verbose) out += ' , schema: ' + it.util.toQuotedString($schema) + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
if ($breakOnError) out += ' if (false) { ';
} else if ('ignore' == it.opts.missingRefs) {
it.logger.warn($message);
if ($breakOnError) out += ' if (true) { ';
} else throw new it.MissingRefError(it.baseId, $schema, $message);
} else if ($refVal.inline) {
var $it = it.util.copy(it);
$it.level++;
var $nextValid = 'valid' + $it.level;
$it.schema = $refVal.schema;
$it.schemaPath = '';
$it.errSchemaPath = $schema;
var $code = it.validate($it).replace(/validate\.schema/g, $refVal.code);
out += ' ' + $code + ' ';
if ($breakOnError) out += ' if (' + $nextValid + ') { ';
} else {
$async = true === $refVal.$async || it.async && false !== $refVal.$async;
$refCode = $refVal.code;
}
}
if ($refCode) {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (it.opts.passContext) out += ' ' + $refCode + '.call(this, ';
else out += ' ' + $refCode + '( ';
out += ' ' + $data + ', (dataPath || \'\')';
if ('""' != it.errorPath) out += ' + ' + it.errorPath;
var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' , ' + $parentData + ' , ' + $parentDataProperty + ', rootData) ';
var __callValidate = out;
out = $$outStack.pop();
if ($async) {
if (!it.async) throw new Error('async schema referenced by sync schema');
if ($breakOnError) out += ' var ' + $valid + '; ';
out += ' try { await ' + __callValidate + '; ';
if ($breakOnError) out += ' ' + $valid + ' = true; ';
out += ' } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ';
if ($breakOnError) out += ' ' + $valid + ' = false; ';
out += ' } ';
if ($breakOnError) out += ' if (' + $valid + ') { ';
} else {
out += ' if (!' + __callValidate + ') { if (vErrors === null) vErrors = ' + $refCode + '.errors; else vErrors = vErrors.concat(' + $refCode + '.errors); errors = vErrors.length; } ';
if ($breakOnError) out += ' else { ';
}
}
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/required.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.$data && $schema && $schema.$data;
if ($isData) out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
var $vSchema = 'schema' + $lvl;
if (!$isData) if ($schema.length < it.opts.loopRequired && it.schema.properties && Object.keys(it.schema.properties).length) {
var $required = [];
var arr1 = $schema;
if (arr1) {
var $property, i1 = -1, l1 = arr1.length - 1;
while(i1 < l1){
$property = arr1[i1 += 1];
var $propertySch = it.schema.properties[$property];
if (!($propertySch && (it.opts.strictKeywords ? 'object' == typeof $propertySch && Object.keys($propertySch).length > 0 || false === $propertySch : it.util.schemaHasRules($propertySch, it.RULES.all)))) $required[$required.length] = $property;
}
}
} else var $required = $schema;
if ($isData || $required.length) {
var $currentErrorPath = it.errorPath, $loopRequired = $isData || $required.length >= it.opts.loopRequired, $ownProperties = it.opts.ownProperties;
if ($breakOnError) {
out += ' var missing' + $lvl + '; ';
if ($loopRequired) {
if (!$isData) out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; ';
var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
out += ' var ' + $valid + ' = true; ';
if ($isData) out += ' if (schema' + $lvl + ' === undefined) ' + $valid + ' = true; else if (!Array.isArray(schema' + $lvl + ')) ' + $valid + ' = false; else {';
out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { ' + $valid + ' = ' + $data + '[' + $vSchema + '[' + $i + ']] !== undefined ';
if ($ownProperties) out += ' && Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) ';
out += '; if (!' + $valid + ') break; } ';
if ($isData) out += ' } ';
out += ' if (!' + $valid + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is a required property';
else out += 'should have required property \\\'' + $missingProperty + '\\\'';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } else { ';
} else {
out += ' if ( ';
var arr2 = $required;
if (arr2) {
var $propertyKey, $i = -1, l2 = arr2.length - 1;
while($i < l2){
$propertyKey = arr2[$i += 1];
if ($i) out += ' || ';
var $prop = it.util.getProperty($propertyKey), $useData = $data + $prop;
out += ' ( ( ' + $useData + ' === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ') && (missing' + $lvl + ' = ' + it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop) + ') ) ';
}
}
out += ') { ';
var $propertyPath = 'missing' + $lvl, $missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is a required property';
else out += 'should have required property \\\'' + $missingProperty + '\\\'';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } else { ';
}
} else if ($loopRequired) {
if (!$isData) out += ' var ' + $vSchema + ' = validate.schema' + $schemaPath + '; ';
var $i = 'i' + $lvl, $propertyPath = 'schema' + $lvl + '[' + $i + ']', $missingProperty = '\' + ' + $propertyPath + ' + \'';
if (it.opts._errorDataPathProperty) it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
if ($isData) {
out += ' if (' + $vSchema + ' && !Array.isArray(' + $vSchema + ')) { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is a required property';
else out += 'should have required property \\\'' + $missingProperty + '\\\'';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + $vSchema + ' !== undefined) { ';
}
out += ' for (var ' + $i + ' = 0; ' + $i + ' < ' + $vSchema + '.length; ' + $i + '++) { if (' + $data + '[' + $vSchema + '[' + $i + ']] === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', ' + $vSchema + '[' + $i + ']) ';
out += ') { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is a required property';
else out += 'should have required property \\\'' + $missingProperty + '\\\'';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
if ($isData) out += ' } ';
} else {
var arr3 = $required;
if (arr3) {
var $propertyKey, i3 = -1, l3 = arr3.length - 1;
while(i3 < l3){
$propertyKey = arr3[i3 += 1];
var $prop = it.util.getProperty($propertyKey), $missingProperty = it.util.escapeQuotes($propertyKey), $useData = $data + $prop;
if (it.opts._errorDataPathProperty) it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
out += ' if ( ' + $useData + ' === undefined ';
if ($ownProperties) out += ' || ! Object.prototype.hasOwnProperty.call(' + $data + ', \'' + it.util.escapeQuotes($propertyKey) + '\') ';
out += ') { var err = ';
if (false !== it.createErrors) {
out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { missingProperty: \'' + $missingProperty + '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'';
if (it.opts._errorDataPathProperty) out += 'is a required property';
else out += 'should have required property \\\'' + $missingProperty + '\\\'';
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
}
}
}
it.errorPath = $currentErrorPath;
} else if ($breakOnError) out += ' if (true) {';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/uniqueItems.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = ' ';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
var $isData = it.opts.$data && $schema && $schema.$data, $schemaValue;
if ($isData) {
out += ' var schema' + $lvl + ' = ' + it.util.getData($schema.$data, $dataLvl, it.dataPathArr) + '; ';
$schemaValue = 'schema' + $lvl;
} else $schemaValue = $schema;
if (($schema || $isData) && false !== it.opts.uniqueItems) {
if ($isData) out += ' var ' + $valid + '; if (' + $schemaValue + ' === false || ' + $schemaValue + ' === undefined) ' + $valid + ' = true; else if (typeof ' + $schemaValue + ' != \'boolean\') ' + $valid + ' = false; else { ';
out += ' var i = ' + $data + '.length , ' + $valid + ' = true , j; if (i > 1) { ';
var $itemType = it.schema.items && it.schema.items.type, $typeIsArray = Array.isArray($itemType);
if (!$itemType || 'object' == $itemType || 'array' == $itemType || $typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0)) out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + $data + '[i], ' + $data + '[j])) { ' + $valid + ' = false; break outer; } } } ';
else {
out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + $data + '[i]; ';
var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
out += ' if (' + it.util[$method]($itemType, 'item', it.opts.strictNumbers, true) + ') continue; ';
if ($typeIsArray) out += ' if (typeof item == \'string\') item = \'"\' + item; ';
out += ' if (typeof itemIndices[item] == \'number\') { ' + $valid + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
}
out += ' } ';
if ($isData) out += ' } ';
out += ' if (!' + $valid + ') { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { i: i, j: j } ';
if (false !== it.opts.messages) out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
if (it.opts.verbose) {
out += ' , schema: ';
if ($isData) out += 'validate.schema' + $schemaPath;
else out += '' + $schema;
out += ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
}
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } ';
if ($breakOnError) out += ' else { ';
} else if ($breakOnError) out += ' if (true) { ';
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/validate.js": function(module1) {
"use strict";
module1.exports = function(it, $keyword, $ruleType) {
var out = '';
var $async = true === it.schema.$async, $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'), $id = it.self._getId(it.schema);
if (it.opts.strictKeywords) {
var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
if ($unknownKwd) {
var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
if ('log' === it.opts.strictKeywords) it.logger.warn($keywordsMsg);
else throw new Error($keywordsMsg);
}
}
if (it.isTop) {
out += ' var validate = ';
if ($async) {
it.async = true;
out += 'async ';
}
out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
if ($id && (it.opts.sourceCode || it.opts.processCode)) out += " /*# sourceURL=" + $id + " */ ";
}
if ('boolean' == typeof it.schema || !($refKeywords || it.schema.$ref)) {
var $keyword = 'false schema';
var $lvl = it.level;
var $dataLvl = it.dataLevel;
var $schema = it.schema[$keyword];
var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
var $breakOnError = !it.opts.allErrors;
var $errorKeyword;
var $data = 'data' + ($dataLvl || '');
var $valid = 'valid' + $lvl;
if (false === it.schema) {
if (it.isTop) $breakOnError = true;
else out += ' var ' + $valid + ' = false; ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: {} ';
if (false !== it.opts.messages) out += ' , message: \'boolean schema is false\' ';
if (it.opts.verbose) out += ' , schema: false , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
} else if (it.isTop) if ($async) out += ' return data; ';
else out += ' validate.errors = null; return true; ';
else out += ' var ' + $valid + ' = true; ';
if (it.isTop) out += ' }; return validate; ';
return out;
}
if (it.isTop) {
var $top = it.isTop, $lvl = it.level = 0, $dataLvl = it.dataLevel = 0, $data = 'data';
it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
it.baseId = it.baseId || it.rootId;
delete it.isTop;
it.dataPathArr = [
""
];
if (void 0 !== it.schema.default && it.opts.useDefaults && it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored in the schema root';
if ('log' === it.opts.strictDefaults) it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
out += ' var vErrors = null; ';
out += ' var errors = 0; ';
out += ' if (rootData === undefined) rootData = data; ';
} else {
var $lvl = it.level, $dataLvl = it.dataLevel, $data = 'data' + ($dataLvl || '');
if ($id) it.baseId = it.resolve.url(it.baseId, $id);
if ($async && !it.async) throw new Error('async schema in sync schema');
out += ' var errs_' + $lvl + ' = errors;';
}
var $valid = 'valid' + $lvl, $breakOnError = !it.opts.allErrors, $closingBraces1 = '', $closingBraces2 = '';
var $errorKeyword;
var $typeSchema = it.schema.type, $typeIsArray = Array.isArray($typeSchema);
if ($typeSchema && it.opts.nullable && true === it.schema.nullable) {
if ($typeIsArray) {
if (-1 == $typeSchema.indexOf('null')) $typeSchema = $typeSchema.concat('null');
} else if ('null' != $typeSchema) {
$typeSchema = [
$typeSchema,
'null'
];
$typeIsArray = true;
}
}
if ($typeIsArray && 1 == $typeSchema.length) {
$typeSchema = $typeSchema[0];
$typeIsArray = false;
}
if (it.schema.$ref && $refKeywords) {
if ('fail' == it.opts.extendRefs) throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
else if (true !== it.opts.extendRefs) {
$refKeywords = false;
it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
}
}
if (it.schema.$comment && it.opts.$comment) out += ' ' + it.RULES.all.$comment.code(it, '$comment');
if ($typeSchema) {
if (it.opts.coerceTypes) var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
var $rulesGroup = it.RULES.types[$typeSchema];
if ($coerceToTypes || $typeIsArray || true === $rulesGroup || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type';
var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type', $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
out += ' if (' + it.util[$method]($typeSchema, $data, it.opts.strictNumbers, true) + ') { ';
if ($coerceToTypes) {
var $dataType = 'dataType' + $lvl, $coerced = 'coerced' + $lvl;
out += ' var ' + $dataType + ' = typeof ' + $data + '; var ' + $coerced + ' = undefined; ';
if ('array' == it.opts.coerceTypes) out += ' if (' + $dataType + ' == \'object\' && Array.isArray(' + $data + ') && ' + $data + '.length == 1) { ' + $data + ' = ' + $data + '[0]; ' + $dataType + ' = typeof ' + $data + '; if (' + it.util.checkDataType(it.schema.type, $data, it.opts.strictNumbers) + ') ' + $coerced + ' = ' + $data + '; } ';
out += ' if (' + $coerced + ' !== undefined) ; ';
var arr1 = $coerceToTypes;
if (arr1) {
var $type, $i = -1, l1 = arr1.length - 1;
while($i < l1){
$type = arr1[$i += 1];
if ('string' == $type) out += ' else if (' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\') ' + $coerced + ' = \'\' + ' + $data + '; else if (' + $data + ' === null) ' + $coerced + ' = \'\'; ';
else if ('number' == $type || 'integer' == $type) {
out += ' else if (' + $dataType + ' == \'boolean\' || ' + $data + ' === null || (' + $dataType + ' == \'string\' && ' + $data + ' && ' + $data + ' == +' + $data + ' ';
if ('integer' == $type) out += ' && !(' + $data + ' % 1)';
out += ')) ' + $coerced + ' = +' + $data + '; ';
} else if ('boolean' == $type) out += ' else if (' + $data + ' === \'false\' || ' + $data + ' === 0 || ' + $data + ' === null) ' + $coerced + ' = false; else if (' + $data + ' === \'true\' || ' + $data + ' === 1) ' + $coerced + ' = true; ';
else if ('null' == $type) out += ' else if (' + $data + ' === \'\' || ' + $data + ' === 0 || ' + $data + ' === false) ' + $coerced + ' = null; ';
else if ('array' == it.opts.coerceTypes && 'array' == $type) out += ' else if (' + $dataType + ' == \'string\' || ' + $dataType + ' == \'number\' || ' + $dataType + ' == \'boolean\' || ' + $data + ' == null) ' + $coerced + ' = [' + $data + ']; ';
}
}
out += ' else { ';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \'';
if ($typeIsArray) out += '' + $typeSchema.join(",");
else out += '' + $typeSchema;
out += '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should be ';
if ($typeIsArray) out += '' + $typeSchema.join(",");
else out += '' + $typeSchema;
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } if (' + $coerced + ' !== undefined) { ';
var $parentData = $dataLvl ? 'data' + ($dataLvl - 1 || '') : 'parentData', $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
out += ' ' + $data + ' = ' + $coerced + '; ';
if (!$dataLvl) out += 'if (' + $parentData + ' !== undefined)';
out += ' ' + $parentData + '[' + $parentDataProperty + '] = ' + $coerced + '; } ';
} else {
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \'';
if ($typeIsArray) out += '' + $typeSchema.join(",");
else out += '' + $typeSchema;
out += '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should be ';
if ($typeIsArray) out += '' + $typeSchema.join(",");
else out += '' + $typeSchema;
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
}
out += ' } ';
}
}
if (it.schema.$ref && !$refKeywords) {
out += ' ' + it.RULES.all.$ref.code(it, '$ref') + ' ';
if ($breakOnError) {
out += ' } if (errors === ';
if ($top) out += '0';
else out += 'errs_' + $lvl;
out += ') { ';
$closingBraces2 += '}';
}
} else {
var arr2 = it.RULES;
if (arr2) {
var $rulesGroup, i2 = -1, l2 = arr2.length - 1;
while(i2 < l2){
$rulesGroup = arr2[i2 += 1];
if ($shouldUseGroup($rulesGroup)) {
if ($rulesGroup.type) out += ' if (' + it.util.checkDataType($rulesGroup.type, $data, it.opts.strictNumbers) + ') { ';
if (it.opts.useDefaults) {
if ('object' == $rulesGroup.type && it.schema.properties) {
var $schema = it.schema.properties, $schemaKeys = Object.keys($schema);
var arr3 = $schemaKeys;
if (arr3) {
var $propertyKey, i3 = -1, l3 = arr3.length - 1;
while(i3 < l3){
$propertyKey = arr3[i3 += 1];
var $sch = $schema[$propertyKey];
if (void 0 !== $sch.default) {
var $passData = $data + it.util.getProperty($propertyKey);
if (it.compositeRule) {
if (it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored for: ' + $passData;
if ('log' === it.opts.strictDefaults) it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
} else {
out += ' if (' + $passData + ' === undefined ';
if ('empty' == it.opts.useDefaults) out += ' || ' + $passData + ' === null || ' + $passData + ' === \'\' ';
out += ' ) ' + $passData + ' = ';
if ('shared' == it.opts.useDefaults) out += ' ' + it.useDefault($sch.default) + ' ';
else out += ' ' + JSON.stringify($sch.default) + ' ';
out += '; ';
}
}
}
}
} else if ('array' == $rulesGroup.type && Array.isArray(it.schema.items)) {
var arr4 = it.schema.items;
if (arr4) {
var $sch, $i = -1, l4 = arr4.length - 1;
while($i < l4){
$sch = arr4[$i += 1];
if (void 0 !== $sch.default) {
var $passData = $data + '[' + $i + ']';
if (it.compositeRule) {
if (it.opts.strictDefaults) {
var $defaultMsg = 'default is ignored for: ' + $passData;
if ('log' === it.opts.strictDefaults) it.logger.warn($defaultMsg);
else throw new Error($defaultMsg);
}
} else {
out += ' if (' + $passData + ' === undefined ';
if ('empty' == it.opts.useDefaults) out += ' || ' + $passData + ' === null || ' + $passData + ' === \'\' ';
out += ' ) ' + $passData + ' = ';
if ('shared' == it.opts.useDefaults) out += ' ' + it.useDefault($sch.default) + ' ';
else out += ' ' + JSON.stringify($sch.default) + ' ';
out += '; ';
}
}
}
}
}
}
var arr5 = $rulesGroup.rules;
if (arr5) {
var $rule, i5 = -1, l5 = arr5.length - 1;
while(i5 < l5){
$rule = arr5[i5 += 1];
if ($shouldUseRule($rule)) {
var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
if ($code) {
out += ' ' + $code + ' ';
if ($breakOnError) $closingBraces1 += '}';
}
}
}
}
if ($breakOnError) {
out += ' ' + $closingBraces1 + ' ';
$closingBraces1 = '';
}
if ($rulesGroup.type) {
out += ' } ';
if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
out += ' else { ';
var $schemaPath = it.schemaPath + '.type', $errSchemaPath = it.errSchemaPath + '/type';
var $$outStack = $$outStack || [];
$$outStack.push(out);
out = '';
if (false !== it.createErrors) {
out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + it.errorPath + ' , schemaPath: ' + it.util.toQuotedString($errSchemaPath) + ' , params: { type: \'';
if ($typeIsArray) out += '' + $typeSchema.join(",");
else out += '' + $typeSchema;
out += '\' } ';
if (false !== it.opts.messages) {
out += ' , message: \'should be ';
if ($typeIsArray) out += '' + $typeSchema.join(",");
else out += '' + $typeSchema;
out += '\' ';
}
if (it.opts.verbose) out += ' , schema: validate.schema' + $schemaPath + ' , parentSchema: validate.schema' + it.schemaPath + ' , data: ' + $data + ' ';
out += ' } ';
} else out += ' {} ';
var __err = out;
out = $$outStack.pop();
if (!it.compositeRule && $breakOnError) if (it.async) out += ' throw new ValidationError([' + __err + ']); ';
else out += ' validate.errors = [' + __err + ']; return false; ';
else out += ' var err = ' + __err + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
out += ' } ';
}
}
if ($breakOnError) {
out += ' if (errors === ';
if ($top) out += '0';
else out += 'errs_' + $lvl;
out += ') { ';
$closingBraces2 += '}';
}
}
}
}
}
if ($breakOnError) out += ' ' + $closingBraces2 + ' ';
if ($top) {
if ($async) {
out += ' if (errors === 0) return data; ';
out += ' else throw new ValidationError(vErrors); ';
} else {
out += ' validate.errors = vErrors; ';
out += ' return errors === 0; ';
}
out += ' }; return validate;';
} else out += ' var ' + $valid + ' = errors === errs_' + $lvl + ';';
function $shouldUseGroup($rulesGroup) {
var rules = $rulesGroup.rules;
for(var i = 0; i < rules.length; i++)if ($shouldUseRule(rules[i])) return true;
}
function $shouldUseRule($rule) {
return void 0 !== it.schema[$rule.keyword] || $rule.implements && $ruleImplementsSomeKeyword($rule);
}
function $ruleImplementsSomeKeyword($rule) {
var impl = $rule.implements;
for(var i = 0; i < impl.length; i++)if (void 0 !== it.schema[impl[i]]) return true;
}
return out;
};
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/keyword.js": function(module1, __unused_webpack_exports, __webpack_require__) {
"use strict";
var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
var customRuleCode = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/custom.js");
var definitionSchema = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/definition_schema.js");
module1.exports = {
add: addKeyword,
get: getKeyword,
remove: removeKeyword,
validate: validateKeyword
};
function addKeyword(keyword, definition) {
var RULES = this.RULES;
if (RULES.keywords[keyword]) throw new Error('Keyword ' + keyword + ' is already defined');
if (!IDENTIFIER.test(keyword)) throw new Error('Keyword ' + keyword + ' is not a valid identifier');
if (definition) {
this.validateKeyword(definition, true);
var dataType = definition.type;
if (Array.isArray(dataType)) for(var i = 0; i < dataType.length; i++)_addRule(keyword, dataType[i], definition);
else _addRule(keyword, dataType, definition);
var metaSchema = definition.metaSchema;
if (metaSchema) {
if (definition.$data && this._opts.$data) metaSchema = {
anyOf: [
metaSchema,
{
$ref: 'https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#'
}
]
};
definition.validateSchema = this.compile(metaSchema, true);
}
}
RULES.keywords[keyword] = RULES.all[keyword] = true;
function _addRule(keyword, dataType, definition) {
var ruleGroup;
for(var i = 0; i < RULES.length; i++){
var rg = RULES[i];
if (rg.type == dataType) {
ruleGroup = rg;
break;
}
}
if (!ruleGroup) {
ruleGroup = {
type: dataType,
rules: []
};
RULES.push(ruleGroup);
}
var rule = {
keyword: keyword,
definition: definition,
custom: true,
code: customRuleCode,
implements: definition.implements
};
ruleGroup.rules.push(rule);
RULES.custom[keyword] = rule;
}
return this;
}
function getKeyword(keyword) {
var rule = this.RULES.custom[keyword];
return rule ? rule.definition : this.RULES.keywords[keyword] || false;
}
function removeKeyword(keyword) {
var RULES = this.RULES;
delete RULES.keywords[keyword];
delete RULES.all[keyword];
delete RULES.custom[keyword];
for(var i = 0; i < RULES.length; i++){
var rules = RULES[i].rules;
for(var j = 0; j < rules.length; j++)if (rules[j].keyword == keyword) {
rules.splice(j, 1);
break;
}
}
return this;
}
function validateKeyword(definition, throwError) {
validateKeyword.errors = null;
var v = this._validateKeyword = this._validateKeyword || this.compile(definitionSchema, true);
if (v(definition)) return true;
validateKeyword.errors = v.errors;
if (!throwError) return false;
throw new Error('custom keyword definition is invalid: ' + this.errorsText(v.errors));
}
},
"./node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js": function(module1) {
"use strict";
module1.exports = function equal(a, b) {
if (a === b) return true;
if (a && b && 'object' == typeof a && 'object' == typeof b) {
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; 0 !== i--;)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; 0 !== i--;)if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false;
for(i = length; 0 !== i--;){
var key = keys[i];
if (!equal(a[key], b[key])) return false;
}
return true;
}
return a !== a && b !== b;
};
},
"./node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js": function(module1) {
"use strict";
module1.exports = function(data, opts) {
if (!opts) opts = {};
if ('function' == typeof opts) opts = {
cmp: opts
};
var cycles = 'boolean' == typeof opts.cycles ? opts.cycles : false;
var cmp = opts.cmp && function(f) {
return function(node) {
return function(a, b) {
var aobj = {
key: a,
value: node[a]
};
var bobj = {
key: b,
value: node[b]
};
return f(aobj, bobj);
};
};
}(opts.cmp);
var seen = [];
return function stringify(node) {
if (node && node.toJSON && 'function' == typeof node.toJSON) node = node.toJSON();
if (void 0 === node) return;
if ('number' == typeof node) return isFinite(node) ? '' + node : 'null';
if ('object' != typeof node) return JSON.stringify(node);
var i, out;
if (Array.isArray(node)) {
out = '[';
for(i = 0; i < node.length; i++){
if (i) out += ',';
out += stringify(node[i]) || 'null';
}
return out + ']';
}
if (null === node) return 'null';
if (-1 !== seen.indexOf(node)) {
if (cycles) return JSON.stringify('__cycle__');
throw new TypeError('Converting circular structure to JSON');
}
var seenIndex = seen.push(node) - 1;
var keys = Object.keys(node).sort(cmp && cmp(node));
out = '';
for(i = 0; i < keys.length; i++){
var key = keys[i];
var value = stringify(node[key]);
if (value) {
if (out) out += ',';
out += JSON.stringify(key) + ':' + value;
}
}
seen.splice(seenIndex, 1);
return '{' + out + '}';
}(data);
};
},
"./node_modules/.pnpm/json-schema-traverse@0.4.1/node_modules/json-schema-traverse/index.js": function(module1) {
"use strict";
var traverse = module1.exports = function(schema, opts, cb) {
if ('function' == typeof opts) {
cb = opts;
opts = {};
}
cb = opts.cb || cb;
var pre = 'function' == typeof cb ? 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
};
traverse.arrayKeywords = {
items: true,
allOf: true,
anyOf: true,
oneOf: true
};
traverse.propsKeywords = {
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 && 'object' == typeof schema && !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 && 'object' == typeof sch) 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');
}
},
"./node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/dist/es5/uri.all.js": function(__unused_webpack_module, exports1) {
/** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js */ (function(global1, factory) {
factory(exports1);
})(0, function(exports1) {
'use strict';
function merge() {
for(var _len = arguments.length, sets = Array(_len), _key = 0; _key < _len; _key++)sets[_key] = arguments[_key];
if (!(sets.length > 1)) return sets[0];
sets[0] = sets[0].slice(0, -1);
var xl = sets.length - 1;
for(var x = 1; x < xl; ++x)sets[x] = sets[x].slice(1, -1);
sets[xl] = sets[xl].slice(1);
return sets.join('');
}
function subexp(str) {
return "(?:" + str + ")";
}
function typeOf(o) {
return void 0 === o ? "undefined" : null === o ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
}
function toUpperCase(str) {
return str.toUpperCase();
}
function toArray(obj) {
return null != obj ? obj instanceof Array ? obj : "number" != typeof obj.length || obj.split || obj.setInterval || obj.call ? [
obj
] : Array.prototype.slice.call(obj) : [];
}
function assign(target, source) {
var obj = target;
if (source) for(var key in source)obj[key] = source[key];
return obj;
}
function buildExps(isIRI) {
var ALPHA$$ = "[A-Za-z]", DIGIT$$ = "[0-9]", HEXDIG$$ = merge(DIGIT$$, "[A-Fa-f]"), PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$ = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET_RELAXED$ = (subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("0?[1-9]" + DIGIT$$) + "|0?0?" + DIGIT$$)), IPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$ + "\\." + DEC_OCTET_RELAXED$), H16$ = subexp(HEXDIG$$ + "{1,4}"), LS32$ = subexp(subexp(H16$ + "\\:" + H16$) + "|" + IPV4ADDRESS$), IPV6ADDRESS1$ = subexp(subexp(H16$ + "\\:") + "{6}" + LS32$), IPV6ADDRESS2$ = subexp("\\:\\:" + subexp(H16$ + "\\:") + "{5}" + LS32$), IPV6ADDRESS3$ = subexp(subexp(H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{4}" + LS32$), IPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,1}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{3}" + LS32$), IPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,2}" + H16$) + "?\\:\\:" + subexp(H16$ + "\\:") + "{2}" + LS32$), IPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,3}" + H16$) + "?\\:\\:" + H16$ + "\\:" + LS32$), IPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,4}" + H16$) + "?\\:\\:" + LS32$), IPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,5}" + H16$) + "?\\:\\:" + H16$), IPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + "\\:") + "{0,6}" + H16$) + "?\\:\\:"), IPV6ADDRESS$ = subexp([
IPV6ADDRESS1$,
IPV6ADDRESS2$,
IPV6ADDRESS3$,
IPV6ADDRESS4$,
IPV6ADDRESS5$,
IPV6ADDRESS6$,
IPV6ADDRESS7$,
IPV6ADDRESS8$,
IPV6ADDRESS9$
].join("|")), ZONEID$ = subexp(subexp(UNRESERVED$$ + "|" + PCT_ENCODED$) + "+"), IPV6ADDRZ_RELAXED$ = (subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + ZONEID$)), IPVFUTURE$ = subexp("[vV]" + HEXDIG$$ + "+\\." + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), REG_NAME$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$)) + "*"), HOST$ = subexp(IP_LITERAL$ + "|" + IPV4ADDRESS$ + "(?!" + REG_NAME$ + ")|" + REG_NAME$), PORT$ = subexp(DIGIT$$ + "*"), AUTHORITY$ = subexp(subexp(USERINFO$ + "@") + "?" + HOST$ + subexp("\\:" + PORT$) + "?"), PCHAR$ = subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + "|" + merge(UNRESERVED$$, SUB_DELIMS$$, "[\\@]")) + "+"), PATH_ABEMPTY$ = subexp(subexp("\\/" + SEGMENT$) + "*"), PATH_ABSOLUTE$ = subexp("\\/" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + "?"), PATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), PATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), PATH_EMPTY$ = "(?!" + PCHAR$ + ")", QUERY$ = (subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), subexp(subexp(PCHAR$ + "|" + merge("[\\/\\?]", IPRIVATE$$)) + "*")), FRAGMENT$ = subexp(subexp(PCHAR$ + "|[\\/\\?]") + "*"), HIER_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?"), RELATIVE_PART$ = subexp(subexp("\\/\\/" + AUTHORITY$ + PATH_ABEMPTY$) + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$), RELATIVE$ = subexp(RELATIVE_PART$ + subexp("\\?" + QUERY$) + "?" + subexp("\\#" + FRAGMENT$) + "?");
subexp(URI$ + "|" + RELATIVE$), subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")"), subexp("\\?(" + QUERY$ + ")"), subexp("\\#(" + FRAGMENT$ + ")"), subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")"), subexp("\\?(" + QUERY$ + ")"), subexp("\\#(" + FRAGMENT$ + ")"), subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")"), subexp("\\?(" + QUERY$ + ")"), subexp("\\#(" + FRAGMENT$ + ")"), subexp("(" + USERINFO$ + ")@"), subexp("\\:(" + PORT$ + ")");
return {
NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$, SUB_DELIMS$$), "g"),
NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
ESCAPE: new RegExp(merge("[^]", UNRESERVED$$, SUB_DELIMS$$), "g"),
UNRESERVED: new RegExp(UNRESERVED$$, "g"),
OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$, RESERVED$$), "g"),
PCT_ENCODED: new RegExp(PCT_ENCODED$, "g"),
IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$ + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$")
};
}
var URI_PROTOCOL = buildExps(false);
var IRI_PROTOCOL = buildExps(true);
var slicedToArray = function() {
function sliceIterator(arr, i) {
var _arr = [];
var _n = true;
var _d = false;
var _e = void 0;
try {
for(var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true){
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally{
try {
if (!_n && _i["return"]) _i["return"]();
} finally{
if (_d) throw _e;
}
}
return _arr;
}
return function(arr, i) {
if (Array.isArray(arr)) return arr;
if (Symbol.iterator in Object(arr)) return sliceIterator(arr, i);
throw new TypeError("Invalid attempt to destructure non-iterable instance");
};
}();
var toConsumableArray = function(arr) {
if (!Array.isArray(arr)) return Array.from(arr);
for(var i = 0, arr2 = Array(arr.length); i < arr.length; i++)arr2[i] = arr[i];
return arr2;
};
var maxInt = 2147483647;
var base = 36;
var tMin = 1;
var tMax = 26;
var skew = 38;
var damp = 700;
var initialBias = 72;
var initialN = 128;
var delimiter = '-';
var regexPunycode = /^xn--/;
var regexNonASCII = /[^\0-\x7E]/;
var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g;
var errors = {
overflow: 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
};
var baseMinusTMin = base - tMin;
var floor = Math.floor;
var stringFromCharCode = String.fromCharCode;
function error$1(type) {
throw new RangeError(errors[type]);
}
function map(array, fn) {
var result = [];
var length = array.length;
while(length--)result[length] = fn(array[length]);
return result;
}
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
result = parts[0] + '@';
string = parts[1];
}
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
function ucs2decode(string) {
var output = [];
var counter = 0;
var length = string.length;
while(counter < length){
var value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
var extra = string.charCodeAt(counter++);
if ((0xFC00 & extra) == 0xDC00) output.push(((0x3FF & value) << 10) + (0x3FF & extra) + 0x10000);
else {
output.push(value);
counter--;
}
} else output.push(value);
}
return output;
}
var ucs2encode = function(array) {
return String.fromCodePoint.apply(String, toConsumableArray(array));
};
var basicToDigit = function(codePoint) {
if (codePoint - 0x30 < 0x0A) return codePoint - 0x16;
if (codePoint - 0x41 < 0x1A) return codePoint - 0x41;
if (codePoint - 0x61 < 0x1A) return codePoint - 0x61;
return base;
};
var digitToBasic = function(digit, flag) {
return digit + 22 + 75 * (digit < 26) - ((0 != flag) << 5);
};
var adapt = function(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for(; delta > baseMinusTMin * tMax >> 1; k += base)delta = floor(delta / baseMinusTMin);
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
};
var decode = function(input) {
var output = [];
var inputLength = input.length;
var i = 0;
var n = initialN;
var bias = initialBias;
var basic = input.lastIndexOf(delimiter);
if (basic < 0) basic = 0;
for(var j = 0; j < basic; ++j){
if (input.charCodeAt(j) >= 0x80) error$1('not-basic');
output.push(input.charCodeAt(j));
}
for(var index = basic > 0 ? basic + 1 : 0; index < inputLength;){
var oldi = i;
for(var w = 1, k = base;; k += base){
if (index >= inputLength) error$1('invalid-input');
var digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) error$1('overflow');
i += digit * w;
var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (digit < t) break;
var baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) error$1('overflow');
w *= baseMinusT;
}
var out = output.length + 1;
bias = adapt(i - oldi, out, 0 == oldi);
if (floor(i / out) > maxInt - n) error$1('overflow');
n += floor(i / out);
i %= out;
output.splice(i++, 0, n);
}
return String.fromCodePoint.apply(String, output);
};
var encode = function(input) {
var output = [];
input = ucs2decode(input);
var inputLength = input.length;
var n = initialN;
var delta = 0;
var bias = initialBias;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = void 0;
try {
for(var _iterator = input[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
var _currentValue2 = _step.value;
if (_currentValue2 < 0x80) output.push(stringFromCharCode(_currentValue2));
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally{
try {
if (!_iteratorNormalCompletion && _iterator.return) _iterator.return();
} finally{
if (_didIteratorError) throw _iteratorError;
}
}
var basicLength = output.length;
var handledCPCount = basicLength;
if (basicLength) output.push(delimiter);
while(handledCPCount < inputLength){
var m = maxInt;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = void 0;
try {
for(var _iterator2 = input[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true){
var currentValue = _step2.value;
if (currentValue >= n && currentValue < m) m = currentValue;
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally{
try {
if (!_iteratorNormalCompletion2 && _iterator2.return) _iterator2.return();
} finally{
if (_didIteratorError2) throw _iteratorError2;
}
}
var handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) error$1('overflow');
delta += (m - n) * handledCPCountPlusOne;
n = m;
var _iteratorNormalCompletion3 = true;
var _didIteratorError3 = false;
var _iteratorError3 = void 0;
try {
for(var _iterator3 = input[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true){
var _currentValue = _step3.value;
if (_currentValue < n && ++delta > maxInt) error$1('overflow');
if (_currentValue == n) {
var q = delta;
for(var k = base;; k += base){
var t = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
if (q < t) break;
var qMinusT = q - t;
var baseMinusT = base - t;
output.push(stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)));
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
} catch (err) {
_didIteratorError3 = true;
_iteratorError3 = err;
} finally{
try {
if (!_iteratorNormalCompletion3 && _iterator3.return) _iterator3.return();
} finally{
if (_didIteratorError3) throw _iteratorError3;
}
}
++delta;
++n;
}
return output.join('');
};
var toUnicode = function(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
});
};
var toASCII = function(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string) ? 'xn--' + encode(string) : string;
});
};
var punycode = {
version: '2.1.0',
ucs2: {
decode: ucs2decode,
encode: ucs2encode
},
decode: decode,
encode: encode,
toASCII: toASCII,
toUnicode: toUnicode
};
var SCHEMES = {};
function pctEncChar(chr) {
var c = chr.charCodeAt(0);
var e = void 0;
e = c < 16 ? "%0" + c.toString(16).toUpperCase() : c < 128 ? "%" + c.toString(16).toUpperCase() : c < 2048 ? "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (63 & c | 128).toString(16).toUpperCase() : "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (63 & c | 128).toString(16).toUpperCase();
return e;
}
function pctDecChars(str) {
var newStr = "";
var i = 0;
var il = str.length;
while(i < il){
var c = parseInt(str.substr(i + 1, 2), 16);
if (c < 128) {
newStr += String.fromCharCode(c);
i += 3;
} else if (c >= 194 && c < 224) {
if (il - i >= 6) {
var c2 = parseInt(str.substr(i + 4, 2), 16);
newStr += String.fromCharCode((31 & c) << 6 | 63 & c2);
} else newStr += str.substr(i, 6);
i += 6;
} else if (c >= 224) {
if (il - i >= 9) {
var _c = parseInt(str.substr(i + 4, 2), 16);
var c3 = parseInt(str.substr(i + 7, 2), 16);
newStr += String.fromCharCode((15 & c) << 12 | (63 & _c) << 6 | 63 & c3);
} else newStr += str.substr(i, 9);
i += 9;
} else {
newStr += str.substr(i, 3);
i += 3;
}
}
return newStr;
}
function _normalizeComponentEncoding(components, protocol) {
function decodeUnreserved(str) {
var decStr = pctDecChars(str);
return decStr.match(protocol.UNRESERVED) ? decStr : str;
}
if (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, "");
if (void 0 !== components.userinfo) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (void 0 !== components.host) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (void 0 !== components.path) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (void 0 !== components.query) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
if (void 0 !== components.fragment) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
return components;
}
function _stripLeadingZeros(str) {
return str.replace(/^0*(.*)/, "$1") || "0";
}
function _normalizeIPv4(host, protocol) {
var matches = host.match(protocol.IPV4ADDRESS) || [];
var _matches = slicedToArray(matches, 2), address = _matches[1];
if (address) return address.split(".").map(_stripLeadingZeros).join(".");
return host;
}
function _normalizeIPv6(host, protocol) {
var matches = host.match(protocol.IPV6ADDRESS) || [];
var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2];
if (!address) return host;
var _address$toLowerCase$ = address.toLowerCase().split('::').reverse(), _address$toLowerCase$2 = slicedToArray(_address$toLowerCase$, 2), last = _address$toLowerCase$2[0], first = _address$toLowerCase$2[1];
var firstFields = first ? first.split(":").map(_stripLeadingZeros) : [];
var lastFields = last.split(":").map(_stripLeadingZeros);
var isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);
var fieldCount = isLastFieldIPv4Address ? 7 : 8;
var lastFieldsStart = lastFields.length - fieldCount;
var fields = Array(fieldCount);
for(var x = 0; x < fieldCount; ++x)fields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';
if (isLastFieldIPv4Address) fields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);
var allZeroFields = fields.reduce(function(acc, field, index) {
if (!field || "0" === field) {
var lastLongest = acc[acc.length - 1];
if (lastLongest && lastLongest.index + lastLongest.length === index) lastLongest.length++;
else acc.push({
index: index,
length: 1
});
}
return acc;
}, []);
var longestZeroFields = allZeroFields.sort(function(a, b) {
return b.length - a.length;
})[0];
var newHost = void 0;
if (longestZeroFields && longestZeroFields.length > 1) {
var newFirst = fields.slice(0, longestZeroFields.index);
var newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);
newHost = newFirst.join(":") + "::" + newLast.join(":");
} else newHost = fields.join(":");
if (zone) newHost += "%" + zone;
return newHost;
}
var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
var NO_MATCH_IS_UNDEFINED = void 0 === "".match(/(){0}/)[1];
function parse(uriString) {
var options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
var components = {};
var protocol = false !== options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
if ("suffix" === options.reference) uriString = (options.scheme ? options.scheme + ":" : "") + "//" + uriString;
var matches = uriString.match(URI_PARSE);
if (matches) {
if (NO_MATCH_IS_UNDEFINED) {
components.scheme = matches[1];
components.userinfo = matches[3];
components.host = matches[4];
components.port = parseInt(matches[5], 10);
components.path = matches[6] || "";
components.query = matches[7];
components.fragment = matches[8];
if (isNaN(components.port)) components.port = matches[5];
} else {
components.scheme = matches[1] || void 0;
components.userinfo = -1 !== uriString.indexOf("@") ? matches[3] : void 0;
components.host = -1 !== uriString.indexOf("//") ? matches[4] : void 0;
components.port = parseInt(matches[5], 10);
components.path = matches[6] || "";
components.query = -1 !== uriString.indexOf("?") ? matches[7] : void 0;
components.fragment = -1 !== uriString.indexOf("#") ? matches[8] : void 0;
if (isNaN(components.port)) components.port = uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/) ? matches[4] : void 0;
}
if (components.host) components.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);
if (void 0 !== components.scheme || void 0 !== components.userinfo || void 0 !== components.host || void 0 !== components.port || components.path || void 0 !== components.query) if (void 0 === components.scheme) components.reference = "relative";
else if (void 0 === components.fragment) components.reference = "absolute";
else components.reference = "uri";
else components.reference = "same-document";
if (options.reference && "suffix" !== options.reference && options.reference !== components.reference) components.error = components.error || "URI is not a " + options.reference + " reference.";
var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
if (options.unicodeSupport || schemeHandler && schemeHandler.unicodeSupport) _normalizeComponentEncoding(components, protocol);
else {
if (components.host && (options.domainHost || schemeHandler && schemeHandler.domainHost)) try {
components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
} catch (e) {
components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e;
}
_normalizeComponentEncoding(components, URI_PROTOCOL);
}
if (schemeHandler && schemeHandler.parse) schemeHandler.parse(components, options);
} else components.error = components.error || "URI can not be parsed.";
return components;
}
function _recomposeAuthority(components, options) {
var protocol = false !== options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
var uriTokens = [];
if (void 0 !== components.userinfo) {
uriTokens.push(components.userinfo);
uriTokens.push("@");
}
if (void 0 !== components.host) uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_, $1, $2) {
return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
}));
if ("number" == typeof components.port || "string" == typeof components.port) {
uriTokens.push(":");
uriTokens.push(String(components.port));
}
return uriTokens.length ? uriTokens.join("") : void 0;
}
var RDS1 = /^\.\.?\//;
var RDS2 = /^\/\.(\/|$)/;
var RDS3 = /^\/\.\.(\/|$)/;
var RDS5 = /^\/?(?:.|\n)*?(?=\/|$)/;
function removeDotSegments(input) {
var 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 {
var im = input.match(RDS5);
if (im) {
var s = im[0];
input = input.slice(s.length);
output.push(s);
} else throw new Error("Unexpected dot segment condition");
}
return output.join("");
}
function serialize(components) {
var options = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
var protocol = options.iri ? IRI_PROTOCOL : URI_PROTOCOL;
var uriTokens = [];
var schemeHandler = SCHEMES[(options.scheme || components.scheme || "").toLowerCase()];
if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);
if (components.host) {
if (protocol.IPV6ADDRESS.test(components.host)) ;
else if (options.domainHost || schemeHandler && schemeHandler.domainHost) try {
components.host = options.iri ? punycode.toUnicode(components.host) : punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
} catch (e) {
components.error = components.error || "Host's domain name can not be converted to " + (options.iri ? "Unicode" : "ASCII") + " via punycode: " + e;
}
}
_normalizeComponentEncoding(components, protocol);
if ("suffix" !== options.reference && components.scheme) {
uriTokens.push(components.scheme);
uriTokens.push(":");
}
var authority = _recomposeAuthority(components, options);
if (void 0 !== authority) {
if ("suffix" !== options.reference) uriTokens.push("//");
uriTokens.push(authority);
if (components.path && "/" !== components.path.charAt(0)) uriTokens.push("/");
}
if (void 0 !== components.path) {
var s = components.path;
if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) s = removeDotSegments(s);
if (void 0 === authority) s = s.replace(/^\/\//, "/%2F");
uriTokens.push(s);
}
if (void 0 !== components.query) {
uriTokens.push("?");
uriTokens.push(components.query);
}
if (void 0 !== components.fragment) {
uriTokens.push("#");
uriTokens.push(components.fragment);
}
return uriTokens.join("");
}
function resolveComponents(base, relative) {
var options = arguments.length > 2 && void 0 !== arguments[2] ? arguments[2] : {};
var skipNormalization = arguments[3];
var target = {};
if (!skipNormalization) {
base = parse(serialize(base, options), options);
relative = parse(serialize(relative, options), options);
}
options = options || {};
if (!options.tolerant && relative.scheme) {
target.scheme = relative.scheme;
target.userinfo = relative.userinfo;
target.host = relative.host;
target.port = relative.port;
target.path = removeDotSegments(relative.path || "");
target.query = relative.query;
} else {
if (void 0 !== relative.userinfo || void 0 !== relative.host || void 0 !== relative.port) {
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) {
if ("/" === relative.path.charAt(0)) target.path = removeDotSegments(relative.path);
else {
if (void 0 === base.userinfo && void 0 === base.host && void 0 === base.port || base.path) if (base.path) target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative.path;
else target.path = relative.path;
else target.path = "/" + relative.path;
target.path = removeDotSegments(target.path);
}
target.query = relative.query;
} else {
target.path = base.path;
if (void 0 !== relative.query) target.query = relative.query;
else target.query = base.query;
}
target.userinfo = base.userinfo;
target.host = base.host;
target.port = base.port;
}
target.scheme = base.scheme;
}
target.fragment = relative.fragment;
return target;
}
function resolve(baseURI, relativeURI, options) {
var schemelessOptions = assign({
scheme: 'null'
}, options);
return serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
}
function normalize(uri, options) {
if ("string" == typeof uri) uri = serialize(parse(uri, options), options);
else if ("object" === typeOf(uri)) uri = parse(serialize(uri, options), options);
return uri;
}
function equal(uriA, uriB, options) {
if ("string" == typeof uriA) uriA = serialize(parse(uriA, options), options);
else if ("object" === typeOf(uriA)) uriA = serialize(uriA, options);
if ("string" == typeof uriB) uriB = serialize(parse(uriB, options), options);
else if ("object" === typeOf(uriB)) uriB = serialize(uriB, options);
return uriA === uriB;
}
function escapeComponent(str, options) {
return str && str.toString().replace(options && options.iri ? IRI_PROTOCOL.ESCAPE : URI_PROTOCOL.ESCAPE, pctEncChar);
}
function unescapeComponent(str, options) {
return str && str.toString().replace(options && options.iri ? IRI_PROTOCOL.PCT_ENCODED : URI_PROTOCOL.PCT_ENCODED, pctDecChars);
}
var handler = {
scheme: "http",
domainHost: true,
parse: function(components, options) {
if (!components.host) components.error = components.error || "HTTP URIs must have a host.";
return components;
},
serialize: function(components, options) {
var secure = "https" === String(components.scheme).toLowerCase();
if (components.port === (secure ? 443 : 80) || "" === components.port) components.port = void 0;
if (!components.path) components.path = "/";
return components;
}
};
var handler$1 = {
scheme: "https",
domainHost: handler.domainHost,
parse: handler.parse,
serialize: handler.serialize
};
function isSecure(wsComponents) {
return 'boolean' == typeof wsComponents.secure ? wsComponents.secure : "wss" === String(wsComponents.scheme).toLowerCase();
}
var handler$2 = {
scheme: "ws",
domainHost: true,
parse: function(components, options) {
var wsComponents = components;
wsComponents.secure = isSecure(wsComponents);
wsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');
wsComponents.path = void 0;
wsComponents.query = void 0;
return wsComponents;
},
serialize: function(wsComponents, options) {
if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || "" === wsComponents.port) wsComponents.port = void 0;
if ('boolean' == typeof wsComponents.secure) {
wsComponents.scheme = wsComponents.secure ? 'wss' : 'ws';
wsComponents.secure = void 0;
}
if (wsComponents.resourceName) {
var _wsComponents$resourc = wsComponents.resourceName.split('?'), _wsComponents$resourc2 = slicedToArray(_wsComponents$resourc, 2), path = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
wsComponents.path = path && '/' !== path ? path : void 0;
wsComponents.query = query;
wsComponents.resourceName = void 0;
}
wsComponents.fragment = void 0;
return wsComponents;
}
};
var handler$3 = {
scheme: "wss",
domainHost: handler$2.domainHost,
parse: handler$2.parse,
serialize: handler$2.serialize
};
var O = {};
var isIRI = true;
var UNRESERVED$$ = "[A-Za-z0-9\\-\\.\\_\\~" + (isIRI ? "\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF" : "") + "]";
var HEXDIG$$ = "[0-9A-Fa-f]";
var PCT_ENCODED$ = subexp(subexp("%[EFef]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$ + "%" + HEXDIG$$ + HEXDIG$$) + "|" + subexp("%" + HEXDIG$$ + HEXDIG$$));
var ATEXT$$ = "[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]";
var QTEXT$$ = "[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]";
var VCHAR$$ = merge(QTEXT$$, "[\\\"\\\\]");
var SOME_DELIMS$$ = "[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]";
var UNRESERVED = new RegExp(UNRESERVED$$, "g");
var PCT_ENCODED = new RegExp(PCT_ENCODED$, "g");
var NOT_LOCAL_PART = new RegExp(merge("[^]", ATEXT$$, "[\\.]", '[\\"]', VCHAR$$), "g");
var NOT_HFNAME = new RegExp(merge("[^]", UNRESERVED$$, SOME_DELIMS$$), "g");
var NOT_HFVALUE = NOT_HFNAME;
function decodeUnreserved(str) {
var decStr = pctDecChars(str);
return decStr.match(UNRESERVED) ? decStr : str;
}
var handler$4 = {
scheme: "mailto",
parse: function(components, options) {
var mailtoComponents = components;
var to = mailtoComponents.to = mailtoComponents.path ? mailtoComponents.path.split(",") : [];
mailtoComponents.path = void 0;
if (mailtoComponents.query) {
var unknownHeaders = false;
var headers = {};
var hfields = mailtoComponents.query.split("&");
for(var x = 0, xl = hfields.length; x < xl; ++x){
var hfield = hfields[x].split("=");
switch(hfield[0]){
case "to":
var toAddrs = hfield[1].split(",");
for(var _x = 0, _xl = toAddrs.length; _x < _xl; ++_x)to.push(toAddrs[_x]);
break;
case "subject":
mailtoComponents.subject = unescapeComponent(hfield[1], options);
break;
case "body":
mailtoComponents.body = unescapeComponent(hfield[1], options);
break;
default:
unknownHeaders = true;
headers[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);
break;
}
}
if (unknownHeaders) mailtoComponents.headers = headers;
}
mailtoComponents.query = void 0;
for(var _x2 = 0, _xl2 = to.length; _x2 < _xl2; ++_x2){
var addr = to[_x2].split("@");
addr[0] = unescapeComponent(addr[0]);
if (options.unicodeSupport) addr[1] = unescapeComponent(addr[1], options).toLowerCase();
else try {
addr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());
} catch (e) {
mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e;
}
to[_x2] = addr.join("@");
}
return mailtoComponents;
},
serialize: function(mailtoComponents, options) {
var components = mailtoComponents;
var to = toArray(mailtoComponents.to);
if (to) {
for(var x = 0, xl = to.length; x < xl; ++x){
var toAddr = String(to[x]);
var atIdx = toAddr.lastIndexOf("@");
var localPart = toAddr.slice(0, atIdx).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);
var domain = toAddr.slice(atIdx + 1);
try {
domain = options.iri ? punycode.toUnicode(domain) : punycode.toASCII(unescapeComponent(domain, options).toLowerCase());
} catch (e) {
components.error = components.error || "Email address's domain name can not be converted to " + (options.iri ? "Unicode" : "ASCII") + " via punycode: " + e;
}
to[x] = localPart + "@" + domain;
}
components.path = to.join(",");
}
var headers = mailtoComponents.headers = mailtoComponents.headers || {};
if (mailtoComponents.subject) headers["subject"] = mailtoComponents.subject;
if (mailtoComponents.body) headers["body"] = mailtoComponents.body;
var fields = [];
for(var name in headers)if (headers[name] !== O[name]) fields.push(name.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) + "=" + headers[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar));
if (fields.length) components.query = fields.join("&");
return components;
}
};
var URN_PARSE = /^([^\:]+)\:(.*)/;
var handler$5 = {
scheme: "urn",
parse: function(components, options) {
var matches = components.path && components.path.match(URN_PARSE);
var urnComponents = components;
if (matches) {
var scheme = options.scheme || urnComponents.scheme || "urn";
var nid = matches[1].toLowerCase();
var nss = matches[2];
var urnScheme = scheme + ":" + (options.nid || nid);
var schemeHandler = SCHEMES[urnScheme];
urnComponents.nid = nid;
urnComponents.nss = nss;
urnComponents.path = void 0;
if (schemeHandler) urnComponents = schemeHandler.parse(urnComponents, options);
} else urnComponents.error = urnComponents.error || "URN can not be parsed.";
return urnComponents;
},
serialize: function(urnComponents, options) {
var scheme = options.scheme || urnComponents.scheme || "urn";
var nid = urnComponents.nid;
var urnScheme = scheme + ":" + (options.nid || nid);
var schemeHandler = SCHEMES[urnScheme];
if (schemeHandler) urnComponents = schemeHandler.serialize(urnComponents, options);
var uriComponents = urnComponents;
var nss = urnComponents.nss;
uriComponents.path = (nid || options.nid) + ":" + nss;
return uriComponents;
}
};
var UUID = /^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;
var handler$6 = {
scheme: "urn:uuid",
parse: function(urnComponents, options) {
var uuidComponents = urnComponents;
uuidComponents.uuid = uuidComponents.nss;
uuidComponents.nss = void 0;
if (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) uuidComponents.error = uuidComponents.error || "UUID is not valid.";
return uuidComponents;
},
serialize: function(uuidComponents, options) {
var urnComponents = uuidComponents;
urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
return urnComponents;
}
};
SCHEMES[handler.scheme] = handler;
SCHEMES[handler$1.scheme] = handler$1;
SCHEMES[handler$2.scheme] = handler$2;
SCHEMES[handler$3.scheme] = handler$3;
SCHEMES[handler$4.scheme] = handler$4;
SCHEMES[handler$5.scheme] = handler$5;
SCHEMES[handler$6.scheme] = handler$6;
exports1.SCHEMES = SCHEMES;
exports1.pctEncChar = pctEncChar;
exports1.pctDecChars = pctDecChars;
exports1.parse = parse;
exports1.removeDotSegments = removeDotSegments;
exports1.serialize = serialize;
exports1.resolveComponents = resolveComponents;
exports1.resolve = resolve;
exports1.normalize = normalize;
exports1.equal = equal;
exports1.escapeComponent = escapeComponent;
exports1.unescapeComponent = unescapeComponent;
Object.defineProperty(exports1, '__esModule', {
value: true
});
});
},
"node:child_process": function(module1) {
"use strict";
module1.exports = __WEBPACK_EXTERNAL_MODULE_node_child_process__;
},
"node:fs": function(module1) {
"use strict";
module1.exports = __WEBPACK_EXTERNAL_MODULE_node_fs__;
},
"node:path": function(module1) {
"use strict";
module1.exports = __WEBPACK_EXTERNAL_MODULE_node_path__;
},
"node:process": function(module1) {
"use strict";
module1.exports = __WEBPACK_EXTERNAL_MODULE_node_process__;
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/refs/data.json": function(module1) {
"use strict";
module1.exports = JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#","description":"Meta-schema for $data reference (JSON Schema extension proposal)","type":"object","required":["$data"],"properties":{"$data":{"type":"string","anyOf":[{"format":"relative-json-pointer"},{"format":"json-pointer"}]}},"additionalProperties":false}');
},
"./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/refs/json-schema-draft-07.json": function(module1) {
"use strict";
module1.exports = JSON.parse('{"$schema":"http://json-schema.org/draft-07/schema#","$id":"http://json-schema.org/draft-07/schema#","title":"Core schema meta-schema","definitions":{"schemaArray":{"type":"array","minItems":1,"items":{"$ref":"#"}},"nonNegativeInteger":{"type":"integer","minimum":0},"nonNegativeIntegerDefault0":{"allOf":[{"$ref":"#/definitions/nonNegativeInteger"},{"default":0}]},"simpleTypes":{"enum":["array","boolean","integer","null","number","object","string"]},"stringArray":{"type":"array","items":{"type":"string"},"uniqueItems":true,"default":[]}},"type":["object","boolean"],"properties":{"$id":{"type":"string","format":"uri-reference"},"$schema":{"type":"string","format":"uri"},"$ref":{"type":"string","format":"uri-reference"},"$comment":{"type":"string"},"title":{"type":"string"},"description":{"type":"string"},"default":true,"readOnly":{"type":"boolean","default":false},"examples":{"type":"array","items":true},"multipleOf":{"type":"number","exclusiveMinimum":0},"maximum":{"type":"number"},"exclusiveMaximum":{"type":"number"},"minimum":{"type":"number"},"exclusiveMinimum":{"type":"number"},"maxLength":{"$ref":"#/definitions/nonNegativeInteger"},"minLength":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"pattern":{"type":"string","format":"regex"},"additionalItems":{"$ref":"#"},"items":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/schemaArray"}],"default":true},"maxItems":{"$ref":"#/definitions/nonNegativeInteger"},"minItems":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"uniqueItems":{"type":"boolean","default":false},"contains":{"$ref":"#"},"maxProperties":{"$ref":"#/definitions/nonNegativeInteger"},"minProperties":{"$ref":"#/definitions/nonNegativeIntegerDefault0"},"required":{"$ref":"#/definitions/stringArray"},"additionalProperties":{"$ref":"#"},"definitions":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"properties":{"type":"object","additionalProperties":{"$ref":"#"},"default":{}},"patternProperties":{"type":"object","additionalProperties":{"$ref":"#"},"propertyNames":{"format":"regex"},"default":{}},"dependencies":{"type":"object","additionalProperties":{"anyOf":[{"$ref":"#"},{"$ref":"#/definitions/stringArray"}]}},"propertyNames":{"$ref":"#"},"const":true,"enum":{"type":"array","items":true,"minItems":1,"uniqueItems":true},"type":{"anyOf":[{"$ref":"#/definitions/simpleTypes"},{"type":"array","items":{"$ref":"#/definitions/simpleTypes"},"minItems":1,"uniqueItems":true}]},"format":{"type":"string"},"contentMediaType":{"type":"string"},"contentEncoding":{"type":"string"},"if":{"$ref":"#"},"then":{"$ref":"#"},"else":{"$ref":"#"},"allOf":{"$ref":"#/definitions/schemaArray"},"anyOf":{"$ref":"#/definitions/schemaArray"},"oneOf":{"$ref":"#/definitions/schemaArray"},"not":{"$ref":"#"}},"default":true}');
}
};
var __webpack_module_cache__ = {};
function __webpack_require__(moduleId) {
var cachedModule = __webpack_module_cache__[moduleId];
if (void 0 !== cachedModule) return cachedModule.exports;
var module1 = __webpack_module_cache__[moduleId] = {
exports: {}
};
__webpack_modules__[moduleId].call(module1.exports, module1, module1.exports, __webpack_require__);
return module1.exports;
}
(()=>{
__webpack_require__.n = (module1)=>{
var getter = module1 && module1.__esModule ? ()=>module1['default'] : ()=>module1;
__webpack_require__.d(getter, {
a: getter
});
return getter;
};
})();
(()=>{
__webpack_require__.d = (exports1, definition)=>{
for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
enumerable: true,
get: definition[key]
});
};
})();
(()=>{
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
var __webpack_exports__ = {};
(()=>{
"use strict";
function K(e, t) {
let n = e.env?.[t];
return "string" == typeof n && "0" !== n;
}
var N = {
UnknownCommand: -5,
InvalidArgument: -4,
ContextLoadError: -3,
CommandLoadError: -2,
InternalError: -1,
Success: 0,
CommandRunError: 1
};
function I(e) {
return e.replace(/-./g, (t)=>t[1].toUpperCase());
}
function F(e) {
return Array.from(e).map((t, n)=>{
let a = t.toUpperCase(), r = t.toLowerCase();
return 0 === n || a !== t || a === r ? t : `-${r}`;
}).join("");
}
function we(e) {
let t = new Map;
return {
get: (...n)=>t.get(n.join(",")) ?? e,
set: (n, ...a)=>{
t.set(a.join(","), n);
}
};
}
function Xe(e, t, n) {
let { threshold: a, weights: r } = n;
if (e === t) return 0;
let i = Math.abs(e.length - t.length);
if ("number" == typeof a && i > a) return 1 / 0;
let o = we(1 / 0);
o.set(0, -1, -1);
for(let s = 0; s < t.length; ++s)o.set((s + 1) * r.insertion, -1, s);
for(let s = 0; s < e.length; ++s)o.set((s + 1) * r.deletion, s, -1);
let d = -1 / 0;
for(let s = 0; s < e.length; ++s){
let u = 1 / 0;
for(let l = 0; l <= t.length - 1; ++l){
let p = e[s] === t[l] ? 0 : 1, c = [
o.get(s - 1, l) + r.deletion,
o.get(s, l - 1) + r.insertion,
o.get(s - 1, l - 1) + p * r.substitution
];
e[s] === t[l - 1] && e[s - 1] === t[l] && c.push(o.get(s - 2, l - 2) + p * r.transposition);
let f = Math.min(...c);
o.set(f, s, l), f < u && (u = f);
}
if (u > a) {
if (d > a) return 1 / 0;
d = u;
} else d = -1 / 0;
}
let m = o.get(e.length - 1, t.length - 1);
return m > a ? 1 / 0 : m;
}
function $e(e, t, n) {
let a = e[1] - t[1];
if (0 !== a) return a;
let r = e[0].startsWith(n), i = t[0].startsWith(n);
return r && !i ? -1 : !r && i ? 1 : e[0].localeCompare(t[0]);
}
function M(e, t, n) {
let a = t.map((i)=>[
i,
Xe(e, i, n)
]).filter(([, i])=>i <= n.threshold), r = Math.min(...a.map(([, i])=>i));
return a.filter(([, i])=>i === r).sort((i, o)=>$e(i, o, e)).map(([i])=>i);
}
var C = class extends Error {
};
function q(e) {
return e instanceof Error ? e.stack ?? String(e) : String(e);
}
function Le(e, t) {
let n = [], a = Math.max(e.length, t.length);
for(let r = 0; r < a; ++r)n[r] = Math.max(e[r], t[r]);
return n;
}
function $(e, t) {
if (0 === e.length) return [];
let n = Array(Math.max(...e.map((r)=>r.length))).fill(0, 0), a = e.reduce((r, i)=>{
let o = i.map((d)=>d.length);
return Le(r, o);
}, n);
return e.map((r)=>{
let i = (r[0] ?? "").padEnd(a[0]);
return r.slice(1).reduce((o, d, m, s)=>{
let u = s.length === m + 1 ? d : d.padEnd(a[m + 1]);
return [
...o,
t?.[m] ?? " ",
u
];
}, [
i
]).join("").trimEnd();
});
}
function V(e, t) {
if (e.length <= 1) return e[0] ?? "";
if (2 === e.length) return e.join(` ${t.conjunction} `);
let n = e.slice(0, e.length - 1).join(", ");
return t.serialComma && (n += ","), [
n,
t.conjunction,
e[e.length - 1]
].join(" ");
}
function ke(e, t) {
return e.reduce((n, a)=>{
let r = t(a), i = n[r] ?? [];
return i.push(a), n[r] = i, n;
}, {});
}
function dist_me(e, t) {
return ke(e, (n)=>n[t]);
}
async function z(e) {
let t = await Promise.allSettled(e), n = dist_me(t, "status");
return n.rejected && n.rejected.length > 0 ? {
status: "rejected",
reasons: n.rejected.map((a)=>a.reason)
} : {
status: "fulfilled",
value: n.fulfilled?.map((a)=>a.value) ?? []
};
}
var Me = new Set([
"true",
"t",
"yes",
"y",
"on",
"1"
]), De = new Set([
"false",
"f",
"no",
"n",
"off",
"0"
]), re = (e)=>{
let t = e.toLowerCase();
if (Me.has(t)) return !0;
if (De.has(t)) return !1;
throw new SyntaxError(`Cannot convert ${e} to a boolean`);
};
var oe = (e)=>{
let t = Number(e);
if (Number.isNaN(t)) throw new SyntaxError(`Cannot convert ${e} to a number`);
return t;
};
var A = class extends C {
_brand;
};
function se(e, t) {
let n = e.constructor.name, a = t[n];
return a ? a(e) : e.message;
}
function Ge(e, t, n) {
return Object.fromEntries(Object.entries(t).map(([a, r])=>{
let i = r, o = e[i];
if (!o) {
let d = B(i, n);
throw new L(d, [], a);
}
return [
a,
[
i,
o
]
];
}));
}
var L = class extends A {
input;
corrections;
aliasName;
constructor(t, n, a){
let r = `No flag registered for --${t}`;
if (a) r += ` (aliased from -${a})`;
else if (n.length > 0) {
let i = V(n.map((o)=>`--${o}`), {
kind: "conjunctive",
conjunction: "or",
serialComma: !0
});
r += `, did you mean ${i}?`;
}
super(r), this.input = t, this.corrections = n, this.aliasName = a;
}
}, G = class extends A {
input;
constructor(t){
super(`No alias registered for -${t}`), this.input = t;
}
};
function ae(e, t) {
return e.placeholder ? e.placeholder : "number" == typeof t ? `arg${t}` : "args";
}
function B(e, t) {
return "allow-kebab-for-camel" === t ? F(e) : e;
}
var j = class extends A {
externalFlagNameOrPlaceholder;
input;
exception;
constructor(t, n, a){
super(`Failed to parse "${n}" for ${t}: ${a instanceof Error ? a.message : String(a)}`), this.externalFlagNameOrPlaceholder = t, this.input = n, this.exception = a;
}
};
function D(e, t, n, a) {
try {
return t.parse.call(a, n);
} catch (r) {
throw new j(e, n, r);
}
}
var W = class extends A {
externalFlagName;
input;
values;
constructor(t, n, a, r){
let i = `Expected "${n}" to be one of (${a.join("|")})`;
if (r.length > 0) {
let o = V(r.map((d)=>`"${d}"`), {
kind: "conjunctive",
conjunction: "or",
serialComma: !0
});
i += `, did you mean ${o}?`;
}
super(i), this.externalFlagName = t, this.input = n, this.values = a;
}
}, w = class extends A {
externalFlagName;
nextFlagName;
constructor(t, n){
let a = `Expected input for flag --${t}`;
n && (a += ` but encountered --${n} instead`), super(a), this.externalFlagName = t, this.nextFlagName = n;
}
}, H = class extends A {
expectedCount;
input;
constructor(t, n){
super(`Too many arguments, expected ${t} but encountered "${n}"`), this.expectedCount = t, this.input = n;
}
}, dist_ = class extends A {
placeholder;
limit;
constructor(t, n){
let a;
n ? (a = `Expected at least ${n[0]} argument(s) for ${t}`, 0 === n[1] ? a += " but found none" : a += ` but only found ${n[1]}`) : a = `Expected argument for ${t}`, super(a), this.placeholder = t, this.limit = n;
}
};
function de(e) {
if (e.startsWith("no") && e.length > 2) {
if ("-" === e[2]) return e.slice(4);
let t = e[2], n = t.toUpperCase();
return t !== n ? void 0 : t.toLowerCase() + e.slice(3);
}
}
function pe(e, t, n) {
let a = e, r = t[a];
if (!r) {
let o = de(a);
if (o && (r = t[o], r && "boolean" == r.kind)) return {
namedFlag: [
o,
r
],
negated: !0
};
}
let i = I(e);
if ("allow-kebab-for-camel" === n.caseStyle && !r) {
if (r = t[i]) return {
namedFlag: [
i,
r
]
};
let o = de(i);
if (o && (r = t[o], r && "boolean" == r.kind)) return {
namedFlag: [
o,
r
],
negated: !0
};
}
if (!r) {
if (i in t) throw new L(e, [
i
]);
let o = F(e);
if (o in t) throw new L(e, [
o
]);
let d = M(a, Object.keys(t), n.distanceOptions);
throw new L(e, d);
}
return {
namedFlag: [
a,
r
]
};
}
function ue(e) {
return "boolean" === e.namedFlag[1].kind || "counter" === e.namedFlag[1].kind;
}
var ce = /^-([a-z]+)$/i, je = /^--([a-z][a-z-.\d_]+)$/i;
function Ue(e, t, n, a) {
let r = ce.exec(e);
if (r) {
let o = r[1];
return Array.from(o).map((d)=>{
let m = d, s = n[m];
if (!s) throw new G(m);
return {
namedFlag: s
};
});
}
let i = je.exec(e);
if (i) {
let o = i[1];
return [
pe(o, t, a)
];
}
return [];
}
var qe = /^--([a-z][a-z-.\d_]+)=(.+)$/i, Ve = /^-([a-z])=(.+)$/i, J = class extends A {
externalFlagName;
valueText;
constructor(t, n){
super(`Cannot negate flag --${t} and pass "${n}" as value`), this.externalFlagName = t, this.valueText = n;
}
};
function We(e, t, n, a) {
let r = qe.exec(e);
if (r) {
let o = r[1], { namedFlag: d, negated: m } = pe(o, t, a), s = r[2];
if (m) throw new J(o, s);
return [
d,
s
];
}
let i = Ve.exec(e);
if (i) {
let o = i[1], d = n[o];
if (!d) throw new G(o);
let m = i[2];
return [
d,
m
];
}
}
async function He(e, t, n, a, r) {
if (!n) {
if ("default" in t && typeof t.default < "u") return "boolean" === t.kind || "enum" === t.kind ? t.default : D(e, t, t.default, r);
if (t.optional) return;
if ("boolean" === t.kind) return !1;
if ("counter" === t.kind) return 0;
throw new w(e);
}
if ("counter" === t.kind) return n.reduce((o, d)=>{
try {
return o + oe.call(r, d);
} catch (m) {
throw new j(e, d, m);
}
}, 0);
if ("variadic" in t && t.variadic) {
if ("enum" === t.kind) {
for (let o of n)if (!t.values.includes(o)) {
let d = M(o, t.values, a.distanceOptions);
throw new W(e, o, t.values, d);
}
return n;
}
return Promise.all(n.map((o)=>D(e, t, o, r)));
}
let i = n[0];
if ("boolean" === t.kind) try {
return re.call(r, i);
} catch (o) {
throw new j(e, i, o);
}
if ("enum" === t.kind) {
if (!t.values.includes(i)) {
let o = M(i, t.values, a.distanceOptions);
throw new W(e, i, t.values, o);
}
return i;
}
return D(e, t, i, r);
}
var Y = class extends A {
externalFlagName;
previousInput;
input;
constructor(t, n, a){
super(`Too many arguments for --${t}, encountered "${a}" after "${n}"`), this.externalFlagName = t, this.previousInput = n, this.input = a;
}
};
function fe(e) {
return "counter" === e.kind ? !0 : "variadic" in e ? !!e.variadic : !1;
}
function v(e, t, [n, a], r) {
let i = e.get(n) ?? [];
if (i.length > 0 && !fe(a)) {
let o = B(n, t);
throw new Y(o, i[0], r);
}
if ("variadic" in a && "string" == typeof a.variadic) {
let o = r.split(a.variadic);
e.set(n, [
...i,
...o
]);
} else e.set(n, [
...i,
r
]);
}
function ie(e, t, n) {
if (t.get(n)) {
let r = e[n];
return !fe(r);
}
return !1;
}
function Q(e, t) {
let { flags: n = {}, aliases: a = {}, positional: r = {
kind: "tuple",
parameters: []
} } = e, i = Ge(n, a, t.caseStyle), o = [], d = new Map, m = 0, s, u = !1;
return {
next: (l)=>{
if (!u && t.allowArgumentEscapeSequence && "--" === l) {
if (s) if ("parsed" === s[1].kind && s[1].inferEmpty) v(d, t.caseStyle, s, ""), s = void 0;
else {
let p = B(s[0], t.caseStyle);
throw new w(p);
}
u = !0;
return;
}
if (!u) {
let p = We(l, n, i, t);
if (p) {
if (s) if ("parsed" === s[1].kind && s[1].inferEmpty) v(d, t.caseStyle, s, ""), s = void 0;
else {
let f = B(s[0], t.caseStyle), T = B(p[0][0], t.caseStyle);
throw new w(f, T);
}
v(d, t.caseStyle, ...p);
return;
}
let c = Ue(l, n, i, t);
if (c.length > 0) {
if (s) if ("parsed" === s[1].kind && s[1].inferEmpty) v(d, t.caseStyle, s, ""), s = void 0;
else {
let f = B(s[0], t.caseStyle), T = B(c[0].namedFlag[0], t.caseStyle);
throw new w(f, T);
}
if (c.every(ue)) for (let f of c)"boolean" === f.namedFlag[1].kind ? v(d, t.caseStyle, f.namedFlag, f.negated ? "false" : "true") : v(d, t.caseStyle, f.namedFlag, "1");
else if (c.length > 1) {
let f = c.find((E)=>!ue(E)), T = B(f.namedFlag[0], t.caseStyle);
throw new w(T);
} else s = c[0].namedFlag;
return;
}
}
if (s) v(d, t.caseStyle, s, l), s = void 0;
else {
if ("tuple" === r.kind) {
if (m >= r.parameters.length) throw new H(r.parameters.length, l);
} else if ("number" == typeof r.maximum && m >= r.maximum) throw new H(r.maximum, l);
o[m] = l, ++m;
}
},
parseArguments: async (l)=>{
let p = [], c;
"array" === r.kind ? ("number" == typeof r.minimum && m < r.minimum && p.push(new dist_(ae(r.parameter), [
r.minimum,
m
])), c = z(o.map(async (g, x)=>{
let y = ae(r.parameter, x + 1);
return D(y, r.parameter, g, l);
}))) : c = z(r.parameters.map(async (g, x)=>{
let y = ae(g, x + 1), h = o[x];
if ("string" != typeof h) {
if ("string" == typeof g.default) return D(y, g, g.default, l);
if (g.optional) return;
throw new dist_(y);
}
return D(y, g, h, l);
})), s && "parsed" === s[1].kind && s[1].inferEmpty && (v(d, t.caseStyle, s, ""), s = void 0);
let f = z(Object.entries(n).map(async (g)=>{
let [x, y] = g, h = B(x, t.caseStyle);
if (s && s[0] === x) throw new w(h);
let b = d.get(x), X = await He(h, y, b, t, l);
return [
x,
X
];
})), [T, E] = await Promise.all([
c,
f
]);
if ("rejected" === T.status) for (let g of T.reasons)p.push(g);
if ("rejected" === E.status) for (let g of E.reasons)p.push(g);
if (p.length > 0) return {
success: !1,
errors: p
};
if ("rejected" === T.status) throw new C("Unknown failure while scanning positional arguments");
if ("rejected" === E.status) throw new C("Unknown failure while scanning flag arguments");
return {
success: !0,
arguments: [
Object.fromEntries(E.value),
...T.value
]
};
},
proposeCompletions: async ({ partial: l, completionConfig: p, text: c, context: f, includeVersionFlag: T })=>{
if (s) return ge(s[1], f, l);
let E = [];
if (!u) {
let S = ce.exec(l);
if (p.includeAliases) {
if ("" === l || "-" === l) {
let g = Object.entries(a).filter((x)=>!ie(n, d, x[1]));
for (let [x] of g){
let y = i[x];
y && E.push({
kind: "argument:flag",
completion: `-${x}`,
brief: y[1].brief
});
}
} else if (S) {
let g = Array.from(S[1]);
if (g.includes("h")) return [];
if (T && g.includes("v")) return [];
let x = new Map(d);
for (let b of g){
let X = i[b];
if (!X) throw new G(b);
v(x, t.caseStyle, X, "boolean" === X[1].kind ? "true" : "1");
}
let y = g[g.length - 1];
if (y) {
let b = i[y];
b && E.push({
kind: "argument:flag",
completion: l,
brief: b[1].brief
});
}
let h = Object.entries(a).filter((b)=>!ie(n, x, b[1]));
for (let [b] of h){
let X = i[b];
X && E.push({
kind: "argument:flag",
completion: `${l}${b}`,
brief: X[1].brief
});
}
}
}
if ("" === l || "-" === l || l.startsWith("--")) {
t.allowArgumentEscapeSequence && E.push({
kind: "argument:flag",
completion: "--",
brief: c.briefs.argumentEscapeSequence
});
let g = Object.entries(n).filter(([y])=>!ie(n, d, y));
"allow-kebab-for-camel" === t.caseStyle && (g = g.map(([y, h])=>[
F(y),
h
]));
let x = g.map(([y, h])=>[
`--${y}`,
h
]).filter(([y])=>y.startsWith(l));
E.push(...x.map(([y, h])=>({
kind: "argument:flag",
completion: y,
brief: h.brief
})));
}
}
if ("array" === r.kind) {
if (r.parameter.proposeCompletions && ("number" != typeof r.maximum || m < r.maximum)) {
let S = await r.parameter.proposeCompletions.call(f, l);
E.push(...S.map((g)=>({
kind: "argument:value",
completion: g,
brief: r.parameter.brief
})));
}
} else {
let S = r.parameters[m];
if (S?.proposeCompletions) {
let g = await S.proposeCompletions.call(f, l);
E.push(...g.map((x)=>({
kind: "argument:value",
completion: x,
brief: S.brief
})));
}
}
return E.filter(({ completion: S })=>S.startsWith(l));
}
};
}
async function ge(e, t, n) {
if ("string" == typeof e.variadic && n.endsWith(e.variadic)) return ge(e, t, "");
let a;
return "enum" === e.kind ? a = e.values : e.proposeCompletions ? a = await e.proposeCompletions.call(t, n) : a = [], a.map((r)=>({
kind: "argument:value",
completion: r,
brief: e.brief
})).filter(({ completion: r })=>r.startsWith(n));
}
function Ce(e, t, n) {
let a = "allow-kebab-for-camel" === t ? "convert-camel-to-kebab" : t, r = e.getAllEntries();
return n.includeHiddenRoutes || (r = r.filter((i)=>!i.hidden)), r.flatMap((i)=>{
let o = i.name[a];
return n.includeAliases ? [
o,
...i.aliases
] : [
o
];
});
}
var ye = {
headers: {
usage: "USAGE",
aliases: "ALIASES",
commands: "COMMANDS",
flags: "FLAGS",
arguments: "ARGUMENTS"
},
keywords: {
default: "default =",
separator: "separator ="
},
briefs: {
help: "Print help information and exit",
helpAll: "Print help information (including hidden commands/flags) and exit",
version: "Print version information and exit",
argumentEscapeSequence: "All subsequent inputs should be interpreted as arguments"
},
noCommandRegisteredForInput: ({ input: e, corrections: t })=>{
let n = `No command registered for \`${e}\``;
if (!(t.length > 0)) return n;
{
let a = V(t, {
kind: "conjunctive",
conjunction: "or",
serialComma: !0
});
return `${n}, did you mean ${a}?`;
}
},
noTextAvailableForLocale: ({ requestedLocale: e, defaultLocale: t })=>`Application does not support "${e}" locale, defaulting to "${t}"`,
exceptionWhileParsingArguments: (e)=>e instanceof A ? se(e, {}) : `Unable to parse arguments, ${q(e)}`,
exceptionWhileLoadingCommandFunction: (e)=>`Unable to load command function, ${q(e)}`,
exceptionWhileLoadingCommandContext: (e)=>`Unable to load command context, ${q(e)}`,
exceptionWhileRunningCommand: (e)=>`Command failed, ${q(e)}`,
commandErrorResult: (e)=>e.message,
currentVersionIsNotLatest: ({ currentVersion: e, latestVersion: t, upgradeCommand: n })=>n ? `Latest available version is ${t} (currently running ${e}), upgrade with "${n}"` : `Latest available version is ${t} (currently running ${e})`
};
function xe(e) {
if (e.startsWith("en")) return ye;
}
function P(e, t, n) {
return !n.disableAnsiColor && !K(e, "STRICLI_NO_COLOR") && (t.getColorDepth?.(e.env) ?? 1) >= 4;
}
async function Te({ loader: e, parameters: t }, { context: n, inputs: a, scannerConfig: r, errorFormatting: i, documentationConfig: o, determineExitCode: d }) {
let m = e(), s;
try {
let l = Q(t, r);
for (let c of a)l.next(c);
let p = await l.parseArguments(n);
if (p.success) s = p.arguments;
else {
let c = P(n.process, n.process.stderr, o);
for (let f of p.errors){
let T = i.exceptionWhileParsingArguments(f, c);
n.process.stderr.write(c ? `\x1B[1m\x1B[31m${T}\x1B[39m\x1B[22m
` : `${T}
`);
}
return N.InvalidArgument;
}
} catch (l) {
let p = P(n.process, n.process.stderr, o), c = i.exceptionWhileParsingArguments(l, p);
return n.process.stderr.write(p ? `\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
` : `${c}
`), N.InvalidArgument;
}
let u;
try {
let l = await m;
"function" == typeof l ? u = l : u = l.default;
} catch (l) {
let p = P(n.process, n.process.stderr, o), c = i.exceptionWhileLoadingCommandFunction(l, p);
return n.process.stderr.write(p ? `\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
` : `${c}
`), N.CommandLoadError;
}
try {
let l = await u.call(n, ...s);
if (l instanceof Error) {
let p = P(n.process, n.process.stderr, o), c = i.commandErrorResult(l, p);
return n.process.stderr.write(p ? `\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
` : `${c}
`), d ? d(l) : N.CommandRunError;
}
} catch (l) {
let p = P(n.process, n.process.stderr, o), c = i.exceptionWhileRunningCommand(l, p);
return n.process.stderr.write(p ? `\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m
` : `${c}
`), d ? d(l) : N.CommandRunError;
}
return N.Success;
}
var R = Symbol("RouteMap");
var O = Symbol("Command");
function Z(e, t, n) {
let a = [
...n
], r = [], i, o = e, d, m = !0, s = !1;
return {
next: (u)=>{
if ("--help" === u || "-h" === u) {
s = !0, d || (d = o);
return;
}
if ("--helpAll" === u || "--help-all" === u || "-H" === u) {
s = "all", d || (d = o);
return;
}
if (d) return void r.push(u);
if (o.kind === O) {
d = o, r.push(u);
return;
}
let l = I(u), p = u, c = o.getRoutingTargetForInput(p);
if ("allow-kebab-for-camel" === t.caseStyle && !c && (c = o.getRoutingTargetForInput(l), c && (p = l)), !c) {
let f = o.getDefaultCommand();
if (f) {
m = !1, i = [
o,
""
], r.push(u), o = f;
return;
}
return {
input: u,
routeMap: o
};
}
m = !1, i = [
o,
u
], o = c, a.push(u);
},
finish: ()=>{
if (d = d ?? o, d.kind === R && !s) {
let l = d.getDefaultCommand();
l && (i = [
d,
""
], d = l, m = !1);
}
let u = i ? i[0].getOtherAliasesForInput(i[1], t.caseStyle) : {
original: [],
"convert-camel-to-kebab": []
};
return {
target: d,
unprocessedInputs: r,
helpRequested: s,
prefix: a,
rootLevel: m,
aliases: u
};
}
};
}
async function Fe({ root: e, defaultText: t, config: n }, a, r) {
let i = t;
if (r.locale) {
let l = n.localization.loadText(r.locale);
if (l) i = l;
else {
let p = P(r.process, r.process.stderr, n.documentation), c = i.noTextAvailableForLocale({
requestedLocale: r.locale,
defaultLocale: n.localization.defaultLocale,
ansiColor: p
});
r.process.stderr.write(p ? `\x1B[1m\x1B[33m${c}\x1B[39m\x1B[22m
` : `${c}
`);
}
}
if (n.versionInfo?.getLatestVersion && !K(r.process, "STRICLI_SKIP_VERSION_CHECK")) {
let l;
"currentVersion" in n.versionInfo ? l = n.versionInfo.currentVersion : l = await n.versionInfo.getCurrentVersion.call(r);
let p = await n.versionInfo.getLatestVersion.call(r, l);
if (p && l !== p) {
let c = P(r.process, r.process.stderr, n.documentation), f = i.currentVersionIsNotLatest({
currentVersion: l,
latestVersion: p,
upgradeCommand: n.versionInfo.upgradeCommand,
ansiColor: c
});
r.process.stderr.write(c ? `\x1B[1m\x1B[33m${f}\x1B[39m\x1B[22m
` : `${f}
`);
}
}
let o = a.slice();
if (n.versionInfo && ("--version" === o[0] || "-v" === o[0])) {
let l;
return "currentVersion" in n.versionInfo ? l = n.versionInfo.currentVersion : l = await n.versionInfo.getCurrentVersion.call(r), r.process.stdout.write(l + `
`), N.Success;
}
let d = Z(e, n.scanner, [
n.name
]), m;
for(; o.length > 0 && !m;){
let l = o.shift();
m = d.next(l);
}
if (m) {
let l = Ce(m.routeMap, n.scanner.caseStyle, n.completion), p = M(m.input, l, n.scanner.distanceOptions).map((T)=>`\`${T}\``), c = P(r.process, r.process.stderr, n.documentation), f = i.noCommandRegisteredForInput({
input: m.input,
corrections: p,
ansiColor: c
});
return r.process.stderr.write(c ? `\x1B[1m\x1B[31m${f}\x1B[39m\x1B[22m
` : `${f}
`), N.UnknownCommand;
}
let s = d.finish();
if (s.helpRequested || s.target.kind === R) {
let l = P(r.process, r.process.stdout, n.documentation);
return r.process.stdout.write(s.target.formatHelp({
prefix: s.prefix,
includeVersionFlag: !!n.versionInfo && s.rootLevel,
includeArgumentEscapeSequenceFlag: n.scanner.allowArgumentEscapeSequence,
includeHelpAllFlag: "all" === s.helpRequested || n.documentation.alwaysShowHelpAllFlag,
includeHidden: "all" === s.helpRequested,
config: n.documentation,
aliases: s.aliases[n.documentation.caseStyle],
text: i,
ansiColor: l
})), N.Success;
}
let u;
if ("forCommand" in r) try {
u = await r.forCommand({
prefix: s.prefix
});
} catch (l) {
let p = P(r.process, r.process.stderr, n.documentation), c = i.exceptionWhileLoadingCommandContext(l, p);
return r.process.stderr.write(p ? `\x1B[1m\x1B[31m${c}\x1B[39m\x1B[22m` : c), N.ContextLoadError;
}
else u = r;
return Te(s.target, {
context: u,
inputs: s.unprocessedInputs,
scannerConfig: n.scanner,
documentationConfig: n.documentation,
errorFormatting: i,
determineExitCode: n.determineExitCode
});
}
function U(e, t) {
return "convert-camel-to-kebab" === t ? F(e) : e;
}
function Ee(e, t) {
return "convert-camel-to-kebab" === t ? `no-${F(e)}` : `no${e[0].toUpperCase()}${e.slice(1)}`;
}
function Ae(e) {
let t = e.scanner?.caseStyle ?? "original", n;
if (e.documentation?.caseStyle) {
if ("original" === t && "convert-camel-to-kebab" === e.documentation.caseStyle) throw new C("Cannot convert route and flag names on display but scan as original");
n = e.documentation.caseStyle;
} else "allow-kebab-for-camel" === t ? n = "convert-camel-to-kebab" : n = t;
let a = {
caseStyle: t,
allowArgumentEscapeSequence: e.scanner?.allowArgumentEscapeSequence ?? !1,
distanceOptions: e.scanner?.distanceOptions ?? {
threshold: 7,
weights: {
insertion: 1,
deletion: 3,
substitution: 2,
transposition: 0
}
}
}, r = {
alwaysShowHelpAllFlag: e.documentation?.alwaysShowHelpAllFlag ?? !1,
useAliasInUsageLine: e.documentation?.useAliasInUsageLine ?? !1,
onlyRequiredInUsageLine: e.documentation?.onlyRequiredInUsageLine ?? !1,
caseStyle: n,
disableAnsiColor: e.documentation?.disableAnsiColor ?? !1
}, i = {
includeAliases: e.completion?.includeAliases ?? r.useAliasInUsageLine,
includeHiddenRoutes: e.completion?.includeHiddenRoutes ?? !1,
...e.completion
};
return {
...e,
scanner: a,
completion: i,
documentation: r,
localization: {
defaultLocale: "en",
loadText: xe,
...e.localization
}
};
}
function dist_e(e, t) {
let n = Ae(t);
if (e.kind === O && n.versionInfo) {
if (e.usesFlag("version")) throw new C("Unable to use command with flag --version as root when version info is supplied");
if (e.usesFlag("v")) throw new C("Unable to use command with alias -v as root when version info is supplied");
}
let a = n.localization.loadText(n.localization.defaultLocale);
if (!a) throw new C(`No text available for the default locale "${n.localization.defaultLocale}"`);
return {
root: e,
config: n,
defaultText: a
};
}
function le(e) {
return "default" in e && typeof e.default < "u";
}
function dist_k(e) {
return e.optional ?? le(e);
}
function Pe(e) {
return `(${e})`;
}
function Se(e) {
return `[${e}]`;
}
function Re(e) {
return `${e}...`;
}
function Qe(e) {
return `<${e}>`;
}
function Ze(e) {
return `[<${e}>]`;
}
function en(e) {
return `<${e}>...`;
}
function ee(e, t) {
let n = Object.entries(e.flags ?? {}).filter(([, i])=>!(i.hidden || t.config.onlyRequiredInUsageLine && dist_k(i))).map(([i, o])=>{
let d = "convert-camel-to-kebab" === t.config.caseStyle ? `--${F(i)}` : `--${i}`;
if (e.aliases && t.config.useAliasInUsageLine) {
let s = Object.entries(e.aliases).filter((u)=>u[1] === i);
1 === s.length && s[0] && (d = `-${s[0][0]}`);
}
if ("boolean" === o.kind) return [
o,
d
];
if ("enum" === o.kind && "string" != typeof o.placeholder) return [
o,
`${d} ${o.values.join("|")}`
];
let m = o.placeholder ?? "value";
return [
o,
`${d} ${m}`
];
}).map(([i, o])=>"parsed" === i.kind && i.variadic ? dist_k(i) ? Re(Se(o)) : Re(Pe(o)) : dist_k(i) ? Se(o) : Pe(o)), a = [], r = e.positional;
if (r) if ("array" === r.kind) a = [
en(r.parameter.placeholder ?? "args")
];
else {
let i = r.parameters;
t.config.onlyRequiredInUsageLine && (i = i.filter((o)=>!o.optional && typeof o.default > "u")), a = i.map((o, d)=>{
let m = o.placeholder ?? `arg${d + 1}`;
return o.optional || typeof o.default < "u" ? Ze(m) : Qe(m);
});
}
return [
...t.prefix,
...n,
...a
].join(" ");
}
function ne(e, t, n) {
let { keywords: a, briefs: r } = n.text, i = Object.entries(e).filter(([, m])=>!(m.hidden && !n.includeHidden)), o = i.some(([, m])=>dist_k(m)), d = i.map(([m, s])=>{
let u = Object.entries(t).filter((f)=>f[1] === m).map(([f])=>`-${f}`), l = "--" + U(m, n.config.caseStyle);
if ("boolean" === s.kind && !1 !== s.default) {
let f = Ee(m, n.config.caseStyle);
l = `${l}/--${f}`;
}
dist_k(s) ? l = `[${l}]` : o && (l = ` ${l}`), "parsed" === s.kind && s.variadic && (l = `${l}...`);
let p = [];
if ("enum" === s.kind) {
let f = s.values.join("|");
p.push(f);
}
if (le(s)) {
let f = n.ansiColor ? `\x1B[90m${a.default}\x1B[39m` : a.default;
p.push(`${f} ${"" === s.default ? '""' : String(s.default)}`);
}
if ("variadic" in s && "string" == typeof s.variadic) {
let f = n.ansiColor ? `\x1B[90m${a.separator}\x1B[39m` : a.separator;
p.push(`${f} ${s.variadic}`);
}
let c = p.length > 0 ? `[${p.join(", ")}]` : void 0;
return {
aliases: u.join(" "),
flagName: l,
brief: s.brief,
suffix: c,
hidden: s.hidden
};
});
if (d.push({
aliases: "-h",
flagName: o ? " --help" : "--help",
brief: r.help
}), n.includeHelpAllFlag) {
let m = U("helpAll", n.config.caseStyle);
d.push({
aliases: "-H",
flagName: o ? ` --${m}` : `--${m}`,
brief: r.helpAll,
hidden: !n.config.alwaysShowHelpAllFlag
});
}
return n.includeVersionFlag && d.push({
aliases: "-v",
flagName: o ? " --version" : "--version",
brief: r.version
}), n.includeArgumentEscapeSequenceFlag && d.push({
aliases: "",
flagName: o ? " --" : "--",
brief: r.argumentEscapeSequence
}), $(d.map((m)=>n.ansiColor ? [
m.hidden ? `\x1B[90m${m.aliases}\x1B[39m` : `\x1B[97m${m.aliases}\x1B[39m`,
m.hidden ? `\x1B[90m${m.flagName}\x1B[39m` : `\x1B[97m${m.flagName}\x1B[39m`,
m.hidden ? `\x1B[90m${m.brief}\x1B[39m` : `\x1B[03m${m.brief}\x1B[23m`,
m.suffix ?? ""
] : [
m.aliases,
m.flagName,
m.brief,
m.suffix ?? ""
]), [
" ",
" ",
" "
]);
}
function* te(e) {
if (yield e.config.useAliasInUsageLine ? "-h" : "--help", e.includeHelpAllFlag) {
let t = U("helpAll", e.config.caseStyle);
yield e.config.useAliasInUsageLine ? "-H" : `--${t}`;
}
e.includeVersionFlag && (yield e.config.useAliasInUsageLine ? "-v" : "--version");
}
function Oe(e, t) {
if ("array" === e.kind) {
let r = e.parameter.placeholder ?? "args", i = t.ansiColor ? `\x1B[97m${r}...\x1B[39m` : `${r}...`, o = t.ansiColor ? `\x1B[3m${e.parameter.brief}\x1B[23m` : e.parameter.brief;
return $([
[
i,
o
]
], [
" "
]);
}
let { keywords: n } = t.text, a = e.parameters.some((r)=>r.optional);
return $(e.parameters.map((r, i)=>{
let o = r.placeholder ?? `arg${i + 1}`, d;
return r.optional ? o = `[${o}]` : a && (o = ` ${o}`), r.default && (d = `[${t.ansiColor ? `\x1B[90m${n.default}\x1B[39m` : n.default} ${r.default}]`), [
t.ansiColor ? `\x1B[97m${o}\x1B[39m` : o,
t.ansiColor ? `\x1B[3m${r.brief}\x1B[23m` : r.brief,
d ?? ""
];
}), [
" ",
" "
]);
}
function* ve(e, t, n) {
let { brief: a, fullDescription: r, customUsage: i } = t, { headers: o } = n.text, d = n.prefix.join(" ");
if (yield n.ansiColor ? `\x1B[1m${o.usage}\x1B[22m` : o.usage, i) for (let s of i)if ("string" == typeof s) yield ` ${d} ${s}`;
else {
let u = n.ansiColor ? `\x1B[3m${s.brief}\x1B[23m` : s.brief;
yield ` ${d} ${s.input}
${u}`;
}
else yield ` ${ee(e, n)}`;
for (let s of te(n))yield ` ${d} ${s}`;
if (yield "", yield r ?? a, n.aliases && n.aliases.length > 0) {
let s = n.prefix.slice(0, -1).join(" ");
yield "", yield n.ansiColor ? `\x1B[1m${o.aliases}\x1B[22m` : o.aliases;
for (let u of n.aliases)yield ` ${s} ${u}`;
}
yield "", yield n.ansiColor ? `\x1B[1m${o.flags}\x1B[22m` : o.flags;
for (let s of ne(e.flags ?? {}, e.aliases ?? {}, n))yield ` ${s}`;
let m = e.positional ?? {
kind: "tuple",
parameters: []
};
if ("array" === m.kind || m.parameters.length > 0) {
yield "", yield n.ansiColor ? `\x1B[1m${o.arguments}\x1B[22m` : o.arguments;
for (let s of Oe(m, n))yield ` ${s}`;
}
}
function nn(e, t) {
for (let n of t)if (n in e) throw new C(`Unable to use reserved flag --${n}`);
}
function tn(e, t) {
for (let n of t)if (n in e) throw new C(`Unable to use reserved alias -${n}`);
}
function* rn(e) {
yield `no-${F(e)}`, yield `no${e[0].toUpperCase()}${e.slice(1)}`;
}
function on(e) {
let t = Object.entries(e).filter(([, n])=>"boolean" === n.kind && !n.optional);
for (let [n] of t)for (let a of rn(n))if (a in e) throw new C(`Unable to allow negation for --${n} as it conflicts with --${a}`);
}
function an(e) {
for (let [t, n] of Object.entries(e))if ("variadic" in n && "string" == typeof n.variadic) {
if (n.variadic.length < 1) throw new C(`Unable to use "" as variadic separator for --${t} as it is empty`);
if (/\s/.test(n.variadic)) throw new C(`Unable to use "${n.variadic}" as variadic separator for --${t} as it contains whitespace`);
}
}
function sn(e) {
let { flags: t = {}, aliases: n = {} } = e.parameters;
nn(t, [
"help",
"helpAll",
"help-all"
]), tn(n, [
"h",
"H"
]), on(t), an(t);
let a;
return "func" in e ? a = async ()=>e.func : a = e.loader, {
kind: O,
loader: a,
parameters: e.parameters,
get brief () {
return e.docs.brief;
},
formatUsageLine: (r)=>ee(e.parameters, r),
formatHelp: (r)=>[
...ve(e.parameters, e.docs, r)
].join(`
`) + `
`,
usesFlag: (r)=>r in t || r in n
};
}
async function Yt(e, t, n) {
let a = await Fe(e, t, n);
n.process.exitCode = a;
}
var package_namespaceObject = JSON.parse('{"u2":"build-my-own","i8":"0.0.5","WL":"A CLI tool that helps developers learn by recreating open source projects from scratch. It sets up learning environments with AI-powered coding assistance for the \'build-your-own-X\' approach."}');
var util_util;
(function(util) {
util.assertEqual = (_)=>{};
function assertIs(_arg) {}
util.assertIs = assertIs;
function assertNever(_x) {
throw new Error();
}
util.assertNever = assertNever;
util.arrayToEnum = (items)=>{
const obj = {};
for (const item of items)obj[item] = item;
return obj;
};
util.getValidEnumValues = (obj)=>{
const validKeys = util.objectKeys(obj).filter((k)=>"number" != typeof obj[obj[k]]);
const filtered = {};
for (const k of validKeys)filtered[k] = obj[k];
return util.objectValues(filtered);
};
util.objectValues = (obj)=>util.objectKeys(obj).map(function(e) {
return obj[e];
});
util.objectKeys = "function" == typeof Object.keys ? (obj)=>Object.keys(obj) : (object)=>{
const keys = [];
for(const key in object)if (Object.prototype.hasOwnProperty.call(object, key)) keys.push(key);
return keys;
};
util.find = (arr, checker)=>{
for (const item of arr)if (checker(item)) return item;
};
util.isInteger = "function" == typeof Number.isInteger ? (val)=>Number.isInteger(val) : (val)=>"number" == typeof val && Number.isFinite(val) && Math.floor(val) === val;
function joinValues(array, separator = " | ") {
return array.map((val)=>"string" == typeof val ? `'${val}'` : val).join(separator);
}
util.joinValues = joinValues;
util.jsonStringifyReplacer = (_, value)=>{
if ("bigint" == typeof value) return value.toString();
return value;
};
})(util_util || (util_util = {}));
var util_objectUtil;
(function(objectUtil) {
objectUtil.mergeShapes = (first, second)=>({
...first,
...second
});
})(util_objectUtil || (util_objectUtil = {}));
const ZodParsedType = util_util.arrayToEnum([
"string",
"nan",
"number",
"integer",
"float",
"boolean",
"date",
"bigint",
"symbol",
"function",
"undefined",
"null",
"array",
"object",
"unknown",
"promise",
"void",
"never",
"map",
"set"
]);
const getParsedType = (data)=>{
const t = typeof data;
switch(t){
case "undefined":
return ZodParsedType.undefined;
case "string":
return ZodParsedType.string;
case "number":
return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
case "boolean":
return ZodParsedType.boolean;
case "function":
return ZodParsedType.function;
case "bigint":
return ZodParsedType.bigint;
case "symbol":
return ZodParsedType.symbol;
case "object":
if (Array.isArray(data)) return ZodParsedType.array;
if (null === data) return ZodParsedType.null;
if (data.then && "function" == typeof data.then && data.catch && "function" == typeof data.catch) return ZodParsedType.promise;
if ("undefined" != typeof Map && data instanceof Map) return ZodParsedType.map;
if ("undefined" != typeof Set && data instanceof Set) return ZodParsedType.set;
if ("undefined" != typeof Date && data instanceof Date) return ZodParsedType.date;
return ZodParsedType.object;
default:
return ZodParsedType.unknown;
}
};
const ZodIssueCode = util_util.arrayToEnum([
"invalid_type",
"invalid_literal",
"custom",
"invalid_union",
"invalid_union_discriminator",
"invalid_enum_value",
"unrecognized_keys",
"invalid_arguments",
"invalid_return_type",
"invalid_date",
"invalid_string",
"too_small",
"too_big",
"invalid_intersection_types",
"not_multiple_of",
"not_finite"
]);
class ZodError extends Error {
get errors() {
return this.issues;
}
constructor(issues){
super();
this.issues = [];
this.addIssue = (sub)=>{
this.issues = [
...this.issues,
sub
];
};
this.addIssues = (subs = [])=>{
this.issues = [
...this.issues,
...subs
];
};
const actualProto = new.target.prototype;
if (Object.setPrototypeOf) Object.setPrototypeOf(this, actualProto);
else this.__proto__ = actualProto;
this.name = "ZodError";
this.issues = issues;
}
format(_mapper) {
const mapper = _mapper || function(issue) {
return issue.message;
};
const fieldErrors = {
_errors: []
};
const processError = (error)=>{
for (const issue of error.issues)if ("invalid_union" === issue.code) issue.unionErrors.map(processError);
else if ("invalid_return_type" === issue.code) processError(issue.returnTypeError);
else if ("invalid_arguments" === issue.code) processError(issue.argumentsError);
else if (0 === issue.path.length) fieldErrors._errors.push(mapper(issue));
else {
let curr = fieldErrors;
let i = 0;
while(i < issue.path.length){
const el = issue.path[i];
const terminal = i === issue.path.length - 1;
if (terminal) {
curr[el] = curr[el] || {
_errors: []
};
curr[el]._errors.push(mapper(issue));
} else curr[el] = curr[el] || {
_errors: []
};
curr = curr[el];
i++;
}
}
};
processError(this);
return fieldErrors;
}
static assert(value) {
if (!(value instanceof ZodError)) throw new Error(`Not a ZodError: ${value}`);
}
toString() {
return this.message;
}
get message() {
return JSON.stringify(this.issues, util_util.jsonStringifyReplacer, 2);
}
get isEmpty() {
return 0 === this.issues.length;
}
flatten(mapper = (issue)=>issue.message) {
const fieldErrors = {};
const formErrors = [];
for (const sub of this.issues)if (sub.path.length > 0) {
const firstEl = sub.path[0];
fieldErrors[firstEl] = fieldErrors[firstEl] || [];
fieldErrors[firstEl].push(mapper(sub));
} else formErrors.push(mapper(sub));
return {
formErrors,
fieldErrors
};
}
get formErrors() {
return this.flatten();
}
}
ZodError.create = (issues)=>{
const error = new ZodError(issues);
return error;
};
const en_errorMap = (issue, _ctx)=>{
let message;
switch(issue.code){
case ZodIssueCode.invalid_type:
message = issue.received === ZodParsedType.undefined ? "Required" : `Expected ${issue.expected}, received ${issue.received}`;
break;
case ZodIssueCode.invalid_literal:
message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_util.jsonStringifyReplacer)}`;
break;
case ZodIssueCode.unrecognized_keys:
message = `Unrecognized key(s) in object: ${util_util.joinValues(issue.keys, ", ")}`;
break;
case ZodIssueCode.invalid_union:
message = "Invalid input";
break;
case ZodIssueCode.invalid_union_discriminator:
message = `Invalid discriminator value. Expected ${util_util.joinValues(issue.options)}`;
break;
case ZodIssueCode.invalid_enum_value:
message = `Invalid enum value. Expected ${util_util.joinValues(issue.options)}, received '${issue.received}'`;
break;
case ZodIssueCode.invalid_arguments:
message = "Invalid function arguments";
break;
case ZodIssueCode.invalid_return_type:
message = "Invalid function return type";
break;
case ZodIssueCode.invalid_date:
message = "Invalid date";
break;
case ZodIssueCode.invalid_string:
if ("object" == typeof issue.validation) if ("includes" in issue.validation) {
message = `Invalid input: must include "${issue.validation.includes}"`;
if ("number" == typeof issue.validation.position) message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;
} else if ("startsWith" in issue.validation) message = `Invalid input: must start with "${issue.validation.startsWith}"`;
else if ("endsWith" in issue.validation) message = `Invalid input: must end with "${issue.validation.endsWith}"`;
else util_util.assertNever(issue.validation);
else message = "regex" !== issue.validation ? `Invalid ${issue.validation}` : "Invalid";
break;
case ZodIssueCode.too_small:
message = "array" === issue.type ? `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "more than"} ${issue.minimum} element(s)` : "string" === issue.type ? `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at least" : "over"} ${issue.minimum} character(s)` : "number" === issue.type ? `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : "bigint" === issue.type ? `Number must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${issue.minimum}` : "date" === issue.type ? `Date must be ${issue.exact ? "exactly equal to " : issue.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number(issue.minimum))}` : "Invalid input";
break;
case ZodIssueCode.too_big:
message = "array" === issue.type ? `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "less than"} ${issue.maximum} element(s)` : "string" === issue.type ? `String must contain ${issue.exact ? "exactly" : issue.inclusive ? "at most" : "under"} ${issue.maximum} character(s)` : "number" === issue.type ? `Number must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : "bigint" === issue.type ? `BigInt must be ${issue.exact ? "exactly" : issue.inclusive ? "less than or equal to" : "less than"} ${issue.maximum}` : "date" === issue.type ? `Date must be ${issue.exact ? "exactly" : issue.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number(issue.maximum))}` : "Invalid input";
break;
case ZodIssueCode.custom:
message = "Invalid input";
break;
case ZodIssueCode.invalid_intersection_types:
message = "Intersection results could not be merged";
break;
case ZodIssueCode.not_multiple_of:
message = `Number must be a multiple of ${issue.multipleOf}`;
break;
case ZodIssueCode.not_finite:
message = "Number must be finite";
break;
default:
message = _ctx.defaultError;
util_util.assertNever(issue);
}
return {
message
};
};
const locales_en = en_errorMap;
let overrideErrorMap = locales_en;
function getErrorMap() {
return overrideErrorMap;
}
var errorUtil_errorUtil;
(function(errorUtil) {
errorUtil.errToObj = (message)=>"string" == typeof message ? {
message
} : message || {};
errorUtil.toString = (message)=>"string" == typeof message ? message : message?.message;
})(errorUtil_errorUtil || (errorUtil_errorUtil = {}));
const makeIssue = (params)=>{
const { data, path, errorMaps, issueData } = params;
const fullPath = [
...path,
...issueData.path || []
];
const fullIssue = {
...issueData,
path: fullPath
};
if (void 0 !== issueData.message) return {
...issueData,
path: fullPath,
message: issueData.message
};
let errorMessage = "";
const maps = errorMaps.filter((m)=>!!m).slice().reverse();
for (const map of maps)errorMessage = map(fullIssue, {
data,
defaultError: errorMessage
}).message;
return {
...issueData,
path: fullPath,
message: errorMessage
};
};
function addIssueToContext(ctx, issueData) {
const overrideMap = getErrorMap();
const issue = makeIssue({
issueData: issueData,
data: ctx.data,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
overrideMap,
overrideMap === locales_en ? void 0 : locales_en
].filter((x)=>!!x)
});
ctx.common.issues.push(issue);
}
class ParseStatus {
constructor(){
this.value = "valid";
}
dirty() {
if ("valid" === this.value) this.value = "dirty";
}
abort() {
if ("aborted" !== this.value) this.value = "aborted";
}
static mergeArray(status, results) {
const arrayValue = [];
for (const s of results){
if ("aborted" === s.status) return parseUtil_INVALID;
if ("dirty" === s.status) status.dirty();
arrayValue.push(s.value);
}
return {
status: status.value,
value: arrayValue
};
}
static async mergeObjectAsync(status, pairs) {
const syncPairs = [];
for (const pair of pairs){
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value
});
}
return ParseStatus.mergeObjectSync(status, syncPairs);
}
static mergeObjectSync(status, pairs) {
const finalObject = {};
for (const pair of pairs){
const { key, value } = pair;
if ("aborted" === key.status) return parseUtil_INVALID;
if ("aborted" === value.status) return parseUtil_INVALID;
if ("dirty" === key.status) status.dirty();
if ("dirty" === value.status) status.dirty();
if ("__proto__" !== key.value && (void 0 !== value.value || pair.alwaysSet)) finalObject[key.value] = value.value;
}
return {
status: status.value,
value: finalObject
};
}
}
const parseUtil_INVALID = Object.freeze({
status: "aborted"
});
const DIRTY = (value)=>({
status: "dirty",
value
});
const OK = (value)=>({
status: "valid",
value
});
const isAborted = (x)=>"aborted" === x.status;
const isDirty = (x)=>"dirty" === x.status;
const parseUtil_isValid = (x)=>"valid" === x.status;
const isAsync = (x)=>"undefined" != typeof Promise && x instanceof Promise;
class ParseInputLazyPath {
constructor(parent, value, path, key){
this._cachedPath = [];
this.parent = parent;
this.data = value;
this._path = path;
this._key = key;
}
get path() {
if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
else this._cachedPath.push(...this._path, this._key);
return this._cachedPath;
}
}
const handleResult = (ctx, result)=>{
if (parseUtil_isValid(result)) return {
success: true,
data: result.value
};
if (!ctx.common.issues.length) throw new Error("Validation failed but no issues detected.");
return {
success: false,
get error () {
if (this._error) return this._error;
const error = new ZodError(ctx.common.issues);
this._error = error;
return this._error;
}
};
};
function processCreateParams(params) {
if (!params) return {};
const { errorMap, invalid_type_error, required_error, description } = params;
if (errorMap && (invalid_type_error || required_error)) throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');
if (errorMap) return {
errorMap: errorMap,
description
};
const customMap = (iss, ctx)=>{
const { message } = params;
if ("invalid_enum_value" === iss.code) return {
message: message ?? ctx.defaultError
};
if (void 0 === ctx.data) return {
message: message ?? required_error ?? ctx.defaultError
};
if ("invalid_type" !== iss.code) return {
message: ctx.defaultError
};
return {
message: message ?? invalid_type_error ?? ctx.defaultError
};
};
return {
errorMap: customMap,
description
};
}
class ZodType {
get description() {
return this._def.description;
}
_getType(input) {
return getParsedType(input.data);
}
_getOrReturnCtx(input, ctx) {
return ctx || {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
};
}
_processInputParams(input) {
return {
status: new ParseStatus(),
ctx: {
common: input.parent.common,
data: input.data,
parsedType: getParsedType(input.data),
schemaErrorMap: this._def.errorMap,
path: input.path,
parent: input.parent
}
};
}
_parseSync(input) {
const result = this._parse(input);
if (isAsync(result)) throw new Error("Synchronous parse encountered promise.");
return result;
}
_parseAsync(input) {
const result = this._parse(input);
return Promise.resolve(result);
}
parse(data, params) {
const result = this.safeParse(data, params);
if (result.success) return result.data;
throw result.error;
}
safeParse(data, params) {
const ctx = {
common: {
issues: [],
async: params?.async ?? false,
contextualErrorMap: params?.errorMap
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const result = this._parseSync({
data,
path: ctx.path,
parent: ctx
});
return handleResult(ctx, result);
}
"~validate"(data) {
const ctx = {
common: {
issues: [],
async: !!this["~standard"].async
},
path: [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
if (!this["~standard"].async) try {
const result = this._parseSync({
data,
path: [],
parent: ctx
});
return parseUtil_isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
};
} catch (err) {
if (err?.message?.toLowerCase()?.includes("encountered")) this["~standard"].async = true;
ctx.common = {
issues: [],
async: true
};
}
return this._parseAsync({
data,
path: [],
parent: ctx
}).then((result)=>parseUtil_isValid(result) ? {
value: result.value
} : {
issues: ctx.common.issues
});
}
async parseAsync(data, params) {
const result = await this.safeParseAsync(data, params);
if (result.success) return result.data;
throw result.error;
}
async safeParseAsync(data, params) {
const ctx = {
common: {
issues: [],
contextualErrorMap: params?.errorMap,
async: true
},
path: params?.path || [],
schemaErrorMap: this._def.errorMap,
parent: null,
data,
parsedType: getParsedType(data)
};
const maybeAsyncResult = this._parse({
data,
path: ctx.path,
parent: ctx
});
const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
return handleResult(ctx, result);
}
refine(check, message) {
const getIssueProperties = (val)=>{
if ("string" == typeof message || void 0 === message) return {
message
};
if ("function" == typeof message) return message(val);
return message;
};
return this._refinement((val, ctx)=>{
const result = check(val);
const setError = ()=>ctx.addIssue({
code: ZodIssueCode.custom,
...getIssueProperties(val)
});
if ("undefined" != typeof Promise && result instanceof Promise) return result.then((data)=>{
if (data) return true;
setError();
return false;
});
if (result) return true;
setError();
return false;
});
}
refinement(check, refinementData) {
return this._refinement((val, ctx)=>{
if (check(val)) return true;
ctx.addIssue("function" == typeof refinementData ? refinementData(val, ctx) : refinementData);
return false;
});
}
_refinement(refinement) {
return new ZodEffects({
schema: this,
typeName: types_ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "refinement",
refinement
}
});
}
superRefine(refinement) {
return this._refinement(refinement);
}
constructor(def){
this.spa = this.safeParseAsync;
this._def = def;
this.parse = this.parse.bind(this);
this.safeParse = this.safeParse.bind(this);
this.parseAsync = this.parseAsync.bind(this);
this.safeParseAsync = this.safeParseAsync.bind(this);
this.spa = this.spa.bind(this);
this.refine = this.refine.bind(this);
this.refinement = this.refinement.bind(this);
this.superRefine = this.superRefine.bind(this);
this.optional = this.optional.bind(this);
this.nullable = this.nullable.bind(this);
this.nullish = this.nullish.bind(this);
this.array = this.array.bind(this);
this.promise = this.promise.bind(this);
this.or = this.or.bind(this);
this.and = this.and.bind(this);
this.transform = this.transform.bind(this);
this.brand = this.brand.bind(this);
this.default = this.default.bind(this);
this.catch = this.catch.bind(this);
this.describe = this.describe.bind(this);
this.pipe = this.pipe.bind(this);
this.readonly = this.readonly.bind(this);
this.isNullable = this.isNullable.bind(this);
this.isOptional = this.isOptional.bind(this);
this["~standard"] = {
version: 1,
vendor: "zod",
validate: (data)=>this["~validate"](data)
};
}
optional() {
return ZodOptional.create(this, this._def);
}
nullable() {
return ZodNullable.create(this, this._def);
}
nullish() {
return this.nullable().optional();
}
array() {
return ZodArray.create(this);
}
promise() {
return ZodPromise.create(this, this._def);
}
or(option) {
return ZodUnion.create([
this,
option
], this._def);
}
and(incoming) {
return ZodIntersection.create(this, incoming, this._def);
}
transform(transform) {
return new ZodEffects({
...processCreateParams(this._def),
schema: this,
typeName: types_ZodFirstPartyTypeKind.ZodEffects,
effect: {
type: "transform",
transform
}
});
}
default(def) {
const defaultValueFunc = "function" == typeof def ? def : ()=>def;
return new ZodDefault({
...processCreateParams(this._def),
innerType: this,
defaultValue: defaultValueFunc,
typeName: types_ZodFirstPartyTypeKind.ZodDefault
});
}
brand() {
return new ZodBranded({
typeName: types_ZodFirstPartyTypeKind.ZodBranded,
type: this,
...processCreateParams(this._def)
});
}
catch(def) {
const catchValueFunc = "function" == typeof def ? def : ()=>def;
return new ZodCatch({
...processCreateParams(this._def),
innerType: this,
catchValue: catchValueFunc,
typeName: types_ZodFirstPartyTypeKind.ZodCatch
});
}
describe(description) {
const This = this.constructor;
return new This({
...this._def,
description
});
}
pipe(target) {
return ZodPipeline.create(this, target);
}
readonly() {
return ZodReadonly.create(this);
}
isOptional() {
return this.safeParse(void 0).success;
}
isNullable() {
return this.safeParse(null).success;
}
}
const cuidRegex = /^c[^\s-]{8,}$/i;
const cuid2Regex = /^[0-9a-z]+$/;
const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i;
const nanoidRegex = /^[a-z0-9_-]{21}$/i;
const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/;
const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
const _emojiRegex = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
let emojiRegex;
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;
const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/;
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;
const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;
const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
const dateRegexSource = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))";
const dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
let secondsRegexSource = "[0-5]\\d";
if (args.precision) secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
else if (null == args.precision) secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
const secondsQuantifier = args.precision ? "+" : "?";
return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
const opts = [];
opts.push(args.local ? "Z?" : "Z");
if (args.offset) opts.push("([+-]\\d{2}:?\\d{2})");
regex = `${regex}(${opts.join("|")})`;
return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version) {
if (("v4" === version || !version) && ipv4Regex.test(ip)) return true;
if (("v6" === version || !version) && ipv6Regex.test(ip)) return true;
return false;
}
function isValidJWT(jwt, alg) {
if (!jwtRegex.test(jwt)) return false;
try {
const [header] = jwt.split(".");
if (!header) return false;
const base64 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
const decoded = JSON.parse(atob(base64));
if ("object" != typeof decoded || null === decoded) return false;
if ("typ" in decoded && decoded?.typ !== "JWT") return false;
if (!decoded.alg) return false;
if (alg && decoded.alg !== alg) return false;
return true;
} catch {
return false;
}
}
function isValidCidr(ip, version) {
if (("v4" === version || !version) && ipv4CidrRegex.test(ip)) return true;
if (("v6" === version || !version) && ipv6CidrRegex.test(ip)) return true;
return false;
}
class ZodString extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = String(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.string) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.string,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const status = new ParseStatus();
let ctx;
for (const check of this._def.checks)if ("min" === check.kind) {
if (input.data.length < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if ("max" === check.kind) {
if (input.data.length > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: false,
message: check.message
});
status.dirty();
}
} else if ("length" === check.kind) {
const tooBig = input.data.length > check.value;
const tooSmall = input.data.length < check.value;
if (tooBig || tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
if (tooBig) addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
else if (tooSmall) addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "string",
inclusive: true,
exact: true,
message: check.message
});
status.dirty();
}
} else if ("email" === check.kind) {
if (!emailRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "email",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("emoji" === check.kind) {
if (!emojiRegex) emojiRegex = new RegExp(_emojiRegex, "u");
if (!emojiRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "emoji",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("uuid" === check.kind) {
if (!uuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "uuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("nanoid" === check.kind) {
if (!nanoidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "nanoid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("cuid" === check.kind) {
if (!cuidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("cuid2" === check.kind) {
if (!cuid2Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cuid2",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("ulid" === check.kind) {
if (!ulidRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ulid",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("url" === check.kind) try {
new URL(input.data);
} catch {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
else if ("regex" === check.kind) {
check.regex.lastIndex = 0;
const testResult = check.regex.test(input.data);
if (!testResult) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "regex",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("trim" === check.kind) input.data = input.data.trim();
else if ("includes" === check.kind) {
if (!input.data.includes(check.value, check.position)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: {
includes: check.value,
position: check.position
},
message: check.message
});
status.dirty();
}
} else if ("toLowerCase" === check.kind) input.data = input.data.toLowerCase();
else if ("toUpperCase" === check.kind) input.data = input.data.toUpperCase();
else if ("startsWith" === check.kind) {
if (!input.data.startsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: {
startsWith: check.value
},
message: check.message
});
status.dirty();
}
} else if ("endsWith" === check.kind) {
if (!input.data.endsWith(check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: {
endsWith: check.value
},
message: check.message
});
status.dirty();
}
} else if ("datetime" === check.kind) {
const regex = datetimeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "datetime",
message: check.message
});
status.dirty();
}
} else if ("date" === check.kind) {
const regex = dateRegex;
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "date",
message: check.message
});
status.dirty();
}
} else if ("time" === check.kind) {
const regex = timeRegex(check);
if (!regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_string,
validation: "time",
message: check.message
});
status.dirty();
}
} else if ("duration" === check.kind) {
if (!durationRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "duration",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("ip" === check.kind) {
if (!isValidIP(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "ip",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("jwt" === check.kind) {
if (!isValidJWT(input.data, check.alg)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "jwt",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("cidr" === check.kind) {
if (!isValidCidr(input.data, check.version)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "cidr",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("base64" === check.kind) {
if (!base64Regex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else if ("base64url" === check.kind) {
if (!base64urlRegex.test(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
validation: "base64url",
code: ZodIssueCode.invalid_string,
message: check.message
});
status.dirty();
}
} else util_util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_regex(regex, validation, message) {
return this.refinement((data)=>regex.test(data), {
validation,
code: ZodIssueCode.invalid_string,
...errorUtil_errorUtil.errToObj(message)
});
}
_addCheck(check) {
return new ZodString({
...this._def,
checks: [
...this._def.checks,
check
]
});
}
email(message) {
return this._addCheck({
kind: "email",
...errorUtil_errorUtil.errToObj(message)
});
}
url(message) {
return this._addCheck({
kind: "url",
...errorUtil_errorUtil.errToObj(message)
});
}
emoji(message) {
return this._addCheck({
kind: "emoji",
...errorUtil_errorUtil.errToObj(message)
});
}
uuid(message) {
return this._addCheck({
kind: "uuid",
...errorUtil_errorUtil.errToObj(message)
});
}
nanoid(message) {
return this._addCheck({
kind: "nanoid",
...errorUtil_errorUtil.errToObj(message)
});
}
cuid(message) {
return this._addCheck({
kind: "cuid",
...errorUtil_errorUtil.errToObj(message)
});
}
cuid2(message) {
return this._addCheck({
kind: "cuid2",
...errorUtil_errorUtil.errToObj(message)
});
}
ulid(message) {
return this._addCheck({
kind: "ulid",
...errorUtil_errorUtil.errToObj(message)
});
}
base64(message) {
return this._addCheck({
kind: "base64",
...errorUtil_errorUtil.errToObj(message)
});
}
base64url(message) {
return this._addCheck({
kind: "base64url",
...errorUtil_errorUtil.errToObj(message)
});
}
jwt(options) {
return this._addCheck({
kind: "jwt",
...errorUtil_errorUtil.errToObj(options)
});
}
ip(options) {
return this._addCheck({
kind: "ip",
...errorUtil_errorUtil.errToObj(options)
});
}
cidr(options) {
return this._addCheck({
kind: "cidr",
...errorUtil_errorUtil.errToObj(options)
});
}
datetime(options) {
if ("string" == typeof options) return this._addCheck({
kind: "datetime",
precision: null,
offset: false,
local: false,
message: options
});
return this._addCheck({
kind: "datetime",
precision: void 0 === options?.precision ? null : options?.precision,
offset: options?.offset ?? false,
local: options?.local ?? false,
...errorUtil_errorUtil.errToObj(options?.message)
});
}
date(message) {
return this._addCheck({
kind: "date",
message
});
}
time(options) {
if ("string" == typeof options) return this._addCheck({
kind: "time",
precision: null,
message: options
});
return this._addCheck({
kind: "time",
precision: void 0 === options?.precision ? null : options?.precision,
...errorUtil_errorUtil.errToObj(options?.message)
});
}
duration(message) {
return this._addCheck({
kind: "duration",
...errorUtil_errorUtil.errToObj(message)
});
}
regex(regex, message) {
return this._addCheck({
kind: "regex",
regex: regex,
...errorUtil_errorUtil.errToObj(message)
});
}
includes(value, options) {
return this._addCheck({
kind: "includes",
value: value,
position: options?.position,
...errorUtil_errorUtil.errToObj(options?.message)
});
}
startsWith(value, message) {
return this._addCheck({
kind: "startsWith",
value: value,
...errorUtil_errorUtil.errToObj(message)
});
}
endsWith(value, message) {
return this._addCheck({
kind: "endsWith",
value: value,
...errorUtil_errorUtil.errToObj(message)
});
}
min(minLength, message) {
return this._addCheck({
kind: "min",
value: minLength,
...errorUtil_errorUtil.errToObj(message)
});
}
max(maxLength, message) {
return this._addCheck({
kind: "max",
value: maxLength,
...errorUtil_errorUtil.errToObj(message)
});
}
length(len, message) {
return this._addCheck({
kind: "length",
value: len,
...errorUtil_errorUtil.errToObj(message)
});
}
nonempty(message) {
return this.min(1, errorUtil_errorUtil.errToObj(message));
}
trim() {
return new ZodString({
...this._def,
checks: [
...this._def.checks,
{
kind: "trim"
}
]
});
}
toLowerCase() {
return new ZodString({
...this._def,
checks: [
...this._def.checks,
{
kind: "toLowerCase"
}
]
});
}
toUpperCase() {
return new ZodString({
...this._def,
checks: [
...this._def.checks,
{
kind: "toUpperCase"
}
]
});
}
get isDatetime() {
return !!this._def.checks.find((ch)=>"datetime" === ch.kind);
}
get isDate() {
return !!this._def.checks.find((ch)=>"date" === ch.kind);
}
get isTime() {
return !!this._def.checks.find((ch)=>"time" === ch.kind);
}
get isDuration() {
return !!this._def.checks.find((ch)=>"duration" === ch.kind);
}
get isEmail() {
return !!this._def.checks.find((ch)=>"email" === ch.kind);
}
get isURL() {
return !!this._def.checks.find((ch)=>"url" === ch.kind);
}
get isEmoji() {
return !!this._def.checks.find((ch)=>"emoji" === ch.kind);
}
get isUUID() {
return !!this._def.checks.find((ch)=>"uuid" === ch.kind);
}
get isNANOID() {
return !!this._def.checks.find((ch)=>"nanoid" === ch.kind);
}
get isCUID() {
return !!this._def.checks.find((ch)=>"cuid" === ch.kind);
}
get isCUID2() {
return !!this._def.checks.find((ch)=>"cuid2" === ch.kind);
}
get isULID() {
return !!this._def.checks.find((ch)=>"ulid" === ch.kind);
}
get isIP() {
return !!this._def.checks.find((ch)=>"ip" === ch.kind);
}
get isCIDR() {
return !!this._def.checks.find((ch)=>"cidr" === ch.kind);
}
get isBase64() {
return !!this._def.checks.find((ch)=>"base64" === ch.kind);
}
get isBase64url() {
return !!this._def.checks.find((ch)=>"base64url" === ch.kind);
}
get minLength() {
let min = null;
for (const ch of this._def.checks)if ("min" === ch.kind) {
if (null === min || ch.value > min) min = ch.value;
}
return min;
}
get maxLength() {
let max = null;
for (const ch of this._def.checks)if ("max" === ch.kind) {
if (null === max || ch.value < max) max = ch.value;
}
return max;
}
}
ZodString.create = (params)=>new ZodString({
checks: [],
typeName: types_ZodFirstPartyTypeKind.ZodString,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
function floatSafeRemainder(val, step) {
const valDecCount = (val.toString().split(".")[1] || "").length;
const stepDecCount = (step.toString().split(".")[1] || "").length;
const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
return valInt % stepInt / 10 ** decCount;
}
class ZodNumber extends ZodType {
constructor(){
super(...arguments);
this.min = this.gte;
this.max = this.lte;
this.step = this.multipleOf;
}
_parse(input) {
if (this._def.coerce) input.data = Number(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.number) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.number,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
let ctx;
const status = new ParseStatus();
for (const check of this._def.checks)if ("int" === check.kind) {
if (!util_util.isInteger(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: "integer",
received: "float",
message: check.message
});
status.dirty();
}
} else if ("min" === check.kind) {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if ("max" === check.kind) {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: check.value,
type: "number",
inclusive: check.inclusive,
exact: false,
message: check.message
});
status.dirty();
}
} else if ("multipleOf" === check.kind) {
if (0 !== floatSafeRemainder(input.data, check.value)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else if ("finite" === check.kind) {
if (!Number.isFinite(input.data)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_finite,
message: check.message
});
status.dirty();
}
} else util_util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil_errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil_errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil_errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil_errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil_errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodNumber({
...this._def,
checks: [
...this._def.checks,
check
]
});
}
int(message) {
return this._addCheck({
kind: "int",
message: errorUtil_errorUtil.toString(message)
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: false,
message: errorUtil_errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: false,
message: errorUtil_errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: 0,
inclusive: true,
message: errorUtil_errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: 0,
inclusive: true,
message: errorUtil_errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value: value,
message: errorUtil_errorUtil.toString(message)
});
}
finite(message) {
return this._addCheck({
kind: "finite",
message: errorUtil_errorUtil.toString(message)
});
}
safe(message) {
return this._addCheck({
kind: "min",
inclusive: true,
value: Number.MIN_SAFE_INTEGER,
message: errorUtil_errorUtil.toString(message)
})._addCheck({
kind: "max",
inclusive: true,
value: Number.MAX_SAFE_INTEGER,
message: errorUtil_errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks)if ("min" === ch.kind) {
if (null === min || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks)if ("max" === ch.kind) {
if (null === max || ch.value < max) max = ch.value;
}
return max;
}
get isInt() {
return !!this._def.checks.find((ch)=>"int" === ch.kind || "multipleOf" === ch.kind && util_util.isInteger(ch.value));
}
get isFinite() {
let max = null;
let min = null;
for (const ch of this._def.checks)if ("finite" === ch.kind || "int" === ch.kind || "multipleOf" === ch.kind) return true;
else if ("min" === ch.kind) {
if (null === min || ch.value > min) min = ch.value;
} else if ("max" === ch.kind) {
if (null === max || ch.value < max) max = ch.value;
}
return Number.isFinite(min) && Number.isFinite(max);
}
}
ZodNumber.create = (params)=>new ZodNumber({
checks: [],
typeName: types_ZodFirstPartyTypeKind.ZodNumber,
coerce: params?.coerce || false,
...processCreateParams(params)
});
class ZodBigInt extends ZodType {
constructor(){
super(...arguments);
this.min = this.gte;
this.max = this.lte;
}
_parse(input) {
if (this._def.coerce) try {
input.data = BigInt(input.data);
} catch {
return this._getInvalidInput(input);
}
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.bigint) return this._getInvalidInput(input);
let ctx;
const status = new ParseStatus();
for (const check of this._def.checks)if ("min" === check.kind) {
const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;
if (tooSmall) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
type: "bigint",
minimum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if ("max" === check.kind) {
const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;
if (tooBig) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
type: "bigint",
maximum: check.value,
inclusive: check.inclusive,
message: check.message
});
status.dirty();
}
} else if ("multipleOf" === check.kind) {
if (input.data % check.value !== BigInt(0)) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.not_multiple_of,
multipleOf: check.value,
message: check.message
});
status.dirty();
}
} else util_util.assertNever(check);
return {
status: status.value,
value: input.data
};
}
_getInvalidInput(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.bigint,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
gte(value, message) {
return this.setLimit("min", value, true, errorUtil_errorUtil.toString(message));
}
gt(value, message) {
return this.setLimit("min", value, false, errorUtil_errorUtil.toString(message));
}
lte(value, message) {
return this.setLimit("max", value, true, errorUtil_errorUtil.toString(message));
}
lt(value, message) {
return this.setLimit("max", value, false, errorUtil_errorUtil.toString(message));
}
setLimit(kind, value, inclusive, message) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
{
kind,
value,
inclusive,
message: errorUtil_errorUtil.toString(message)
}
]
});
}
_addCheck(check) {
return new ZodBigInt({
...this._def,
checks: [
...this._def.checks,
check
]
});
}
positive(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: false,
message: errorUtil_errorUtil.toString(message)
});
}
negative(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: false,
message: errorUtil_errorUtil.toString(message)
});
}
nonpositive(message) {
return this._addCheck({
kind: "max",
value: BigInt(0),
inclusive: true,
message: errorUtil_errorUtil.toString(message)
});
}
nonnegative(message) {
return this._addCheck({
kind: "min",
value: BigInt(0),
inclusive: true,
message: errorUtil_errorUtil.toString(message)
});
}
multipleOf(value, message) {
return this._addCheck({
kind: "multipleOf",
value,
message: errorUtil_errorUtil.toString(message)
});
}
get minValue() {
let min = null;
for (const ch of this._def.checks)if ("min" === ch.kind) {
if (null === min || ch.value > min) min = ch.value;
}
return min;
}
get maxValue() {
let max = null;
for (const ch of this._def.checks)if ("max" === ch.kind) {
if (null === max || ch.value < max) max = ch.value;
}
return max;
}
}
ZodBigInt.create = (params)=>new ZodBigInt({
checks: [],
typeName: types_ZodFirstPartyTypeKind.ZodBigInt,
coerce: params?.coerce ?? false,
...processCreateParams(params)
});
class ZodBoolean extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = Boolean(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.boolean) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.boolean,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
return OK(input.data);
}
}
ZodBoolean.create = (params)=>new ZodBoolean({
typeName: types_ZodFirstPartyTypeKind.ZodBoolean,
coerce: params?.coerce || false,
...processCreateParams(params)
});
class ZodDate extends ZodType {
_parse(input) {
if (this._def.coerce) input.data = new Date(input.data);
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.date) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.date,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
if (Number.isNaN(input.data.getTime())) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_date
});
return parseUtil_INVALID;
}
const status = new ParseStatus();
let ctx;
for (const check of this._def.checks)if ("min" === check.kind) {
if (input.data.getTime() < check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
message: check.message,
inclusive: true,
exact: false,
minimum: check.value,
type: "date"
});
status.dirty();
}
} else if ("max" === check.kind) {
if (input.data.getTime() > check.value) {
ctx = this._getOrReturnCtx(input, ctx);
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
message: check.message,
inclusive: true,
exact: false,
maximum: check.value,
type: "date"
});
status.dirty();
}
} else util_util.assertNever(check);
return {
status: status.value,
value: new Date(input.data.getTime())
};
}
_addCheck(check) {
return new ZodDate({
...this._def,
checks: [
...this._def.checks,
check
]
});
}
min(minDate, message) {
return this._addCheck({
kind: "min",
value: minDate.getTime(),
message: errorUtil_errorUtil.toString(message)
});
}
max(maxDate, message) {
return this._addCheck({
kind: "max",
value: maxDate.getTime(),
message: errorUtil_errorUtil.toString(message)
});
}
get minDate() {
let min = null;
for (const ch of this._def.checks)if ("min" === ch.kind) {
if (null === min || ch.value > min) min = ch.value;
}
return null != min ? new Date(min) : null;
}
get maxDate() {
let max = null;
for (const ch of this._def.checks)if ("max" === ch.kind) {
if (null === max || ch.value < max) max = ch.value;
}
return null != max ? new Date(max) : null;
}
}
ZodDate.create = (params)=>new ZodDate({
checks: [],
coerce: params?.coerce || false,
typeName: types_ZodFirstPartyTypeKind.ZodDate,
...processCreateParams(params)
});
class ZodSymbol extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.symbol) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.symbol,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
return OK(input.data);
}
}
ZodSymbol.create = (params)=>new ZodSymbol({
typeName: types_ZodFirstPartyTypeKind.ZodSymbol,
...processCreateParams(params)
});
class ZodUndefined extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.undefined,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
return OK(input.data);
}
}
ZodUndefined.create = (params)=>new ZodUndefined({
typeName: types_ZodFirstPartyTypeKind.ZodUndefined,
...processCreateParams(params)
});
class ZodNull extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType["null"]) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType["null"],
received: ctx.parsedType
});
return parseUtil_INVALID;
}
return OK(input.data);
}
}
ZodNull.create = (params)=>new ZodNull({
typeName: types_ZodFirstPartyTypeKind.ZodNull,
...processCreateParams(params)
});
class ZodAny extends ZodType {
constructor(){
super(...arguments);
this._any = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodAny.create = (params)=>new ZodAny({
typeName: types_ZodFirstPartyTypeKind.ZodAny,
...processCreateParams(params)
});
class ZodUnknown extends ZodType {
constructor(){
super(...arguments);
this._unknown = true;
}
_parse(input) {
return OK(input.data);
}
}
ZodUnknown.create = (params)=>new ZodUnknown({
typeName: types_ZodFirstPartyTypeKind.ZodUnknown,
...processCreateParams(params)
});
class ZodNever extends ZodType {
_parse(input) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.never,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
}
ZodNever.create = (params)=>new ZodNever({
typeName: types_ZodFirstPartyTypeKind.ZodNever,
...processCreateParams(params)
});
class ZodVoid extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.undefined) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType["void"],
received: ctx.parsedType
});
return parseUtil_INVALID;
}
return OK(input.data);
}
}
ZodVoid.create = (params)=>new ZodVoid({
typeName: types_ZodFirstPartyTypeKind.ZodVoid,
...processCreateParams(params)
});
class ZodArray extends ZodType {
_parse(input) {
const { ctx, status } = this._processInputParams(input);
const def = this._def;
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
if (null !== def.exactLength) {
const tooBig = ctx.data.length > def.exactLength.value;
const tooSmall = ctx.data.length < def.exactLength.value;
if (tooBig || tooSmall) {
addIssueToContext(ctx, {
code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
minimum: tooSmall ? def.exactLength.value : void 0,
maximum: tooBig ? def.exactLength.value : void 0,
type: "array",
inclusive: true,
exact: true,
message: def.exactLength.message
});
status.dirty();
}
}
if (null !== def.minLength) {
if (ctx.data.length < def.minLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.minLength.message
});
status.dirty();
}
}
if (null !== def.maxLength) {
if (ctx.data.length > def.maxLength.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxLength.value,
type: "array",
inclusive: true,
exact: false,
message: def.maxLength.message
});
status.dirty();
}
}
if (ctx.common.async) return Promise.all([
...ctx.data
].map((item, i)=>def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)))).then((result)=>ParseStatus.mergeArray(status, result));
const result = [
...ctx.data
].map((item, i)=>def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)));
return ParseStatus.mergeArray(status, result);
}
get element() {
return this._def.type;
}
min(minLength, message) {
return new ZodArray({
...this._def,
minLength: {
value: minLength,
message: errorUtil_errorUtil.toString(message)
}
});
}
max(maxLength, message) {
return new ZodArray({
...this._def,
maxLength: {
value: maxLength,
message: errorUtil_errorUtil.toString(message)
}
});
}
length(len, message) {
return new ZodArray({
...this._def,
exactLength: {
value: len,
message: errorUtil_errorUtil.toString(message)
}
});
}
nonempty(message) {
return this.min(1, message);
}
}
ZodArray.create = (schema, params)=>new ZodArray({
type: schema,
minLength: null,
maxLength: null,
exactLength: null,
typeName: types_ZodFirstPartyTypeKind.ZodArray,
...processCreateParams(params)
});
function deepPartialify(schema) {
if (schema instanceof ZodObject) {
const newShape = {};
for(const key in schema.shape){
const fieldSchema = schema.shape[key];
newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
}
return new ZodObject({
...schema._def,
shape: ()=>newShape
});
}
if (schema instanceof ZodArray) return new ZodArray({
...schema._def,
type: deepPartialify(schema.element)
});
if (schema instanceof ZodOptional) return ZodOptional.create(deepPartialify(schema.unwrap()));
if (schema instanceof ZodNullable) return ZodNullable.create(deepPartialify(schema.unwrap()));
if (schema instanceof ZodTuple) return ZodTuple.create(schema.items.map((item)=>deepPartialify(item)));
else return schema;
}
class ZodObject extends ZodType {
constructor(){
super(...arguments);
this._cached = null;
this.nonstrict = this.passthrough;
this.augment = this.extend;
}
_getCached() {
if (null !== this._cached) return this._cached;
const shape = this._def.shape();
const keys = util_util.objectKeys(shape);
this._cached = {
shape,
keys
};
return this._cached;
}
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.object) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const { status, ctx } = this._processInputParams(input);
const { shape, keys: shapeKeys } = this._getCached();
const extraKeys = [];
if (!(this._def.catchall instanceof ZodNever && "strip" === this._def.unknownKeys)) {
for(const key in ctx.data)if (!shapeKeys.includes(key)) extraKeys.push(key);
}
const pairs = [];
for (const key of shapeKeys){
const keyValidator = shape[key];
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
if (this._def.catchall instanceof ZodNever) {
const unknownKeys = this._def.unknownKeys;
if ("passthrough" === unknownKeys) for (const key of extraKeys)pairs.push({
key: {
status: "valid",
value: key
},
value: {
status: "valid",
value: ctx.data[key]
}
});
else if ("strict" === unknownKeys) {
if (extraKeys.length > 0) {
addIssueToContext(ctx, {
code: ZodIssueCode.unrecognized_keys,
keys: extraKeys
});
status.dirty();
}
} else if ("strip" === unknownKeys) ;
else throw new Error("Internal ZodObject error: invalid unknownKeys value.");
} else {
const catchall = this._def.catchall;
for (const key of extraKeys){
const value = ctx.data[key];
pairs.push({
key: {
status: "valid",
value: key
},
value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
alwaysSet: key in ctx.data
});
}
}
if (ctx.common.async) return Promise.resolve().then(async ()=>{
const syncPairs = [];
for (const pair of pairs){
const key = await pair.key;
const value = await pair.value;
syncPairs.push({
key,
value,
alwaysSet: pair.alwaysSet
});
}
return syncPairs;
}).then((syncPairs)=>ParseStatus.mergeObjectSync(status, syncPairs));
return ParseStatus.mergeObjectSync(status, pairs);
}
get shape() {
return this._def.shape();
}
strict(message) {
errorUtil_errorUtil.errToObj;
return new ZodObject({
...this._def,
unknownKeys: "strict",
...void 0 !== message ? {
errorMap: (issue, ctx)=>{
const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;
if ("unrecognized_keys" === issue.code) return {
message: errorUtil_errorUtil.errToObj(message).message ?? defaultError
};
return {
message: defaultError
};
}
} : {}
});
}
strip() {
return new ZodObject({
...this._def,
unknownKeys: "strip"
});
}
passthrough() {
return new ZodObject({
...this._def,
unknownKeys: "passthrough"
});
}
extend(augmentation) {
return new ZodObject({
...this._def,
shape: ()=>({
...this._def.shape(),
...augmentation
})
});
}
merge(merging) {
const merged = new ZodObject({
unknownKeys: merging._def.unknownKeys,
catchall: merging._def.catchall,
shape: ()=>({
...this._def.shape(),
...merging._def.shape()
}),
typeName: types_ZodFirstPartyTypeKind.ZodObject
});
return merged;
}
setKey(key, schema) {
return this.augment({
[key]: schema
});
}
catchall(index) {
return new ZodObject({
...this._def,
catchall: index
});
}
pick(mask) {
const shape = {};
for (const key of util_util.objectKeys(mask))if (mask[key] && this.shape[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: ()=>shape
});
}
omit(mask) {
const shape = {};
for (const key of util_util.objectKeys(this.shape))if (!mask[key]) shape[key] = this.shape[key];
return new ZodObject({
...this._def,
shape: ()=>shape
});
}
deepPartial() {
return deepPartialify(this);
}
partial(mask) {
const newShape = {};
for (const key of util_util.objectKeys(this.shape)){
const fieldSchema = this.shape[key];
if (mask && !mask[key]) newShape[key] = fieldSchema;
else newShape[key] = fieldSchema.optional();
}
return new ZodObject({
...this._def,
shape: ()=>newShape
});
}
required(mask) {
const newShape = {};
for (const key of util_util.objectKeys(this.shape))if (mask && !mask[key]) newShape[key] = this.shape[key];
else {
const fieldSchema = this.shape[key];
let newField = fieldSchema;
while(newField instanceof ZodOptional)newField = newField._def.innerType;
newShape[key] = newField;
}
return new ZodObject({
...this._def,
shape: ()=>newShape
});
}
keyof() {
return createZodEnum(util_util.objectKeys(this.shape));
}
}
ZodObject.create = (shape, params)=>new ZodObject({
shape: ()=>shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: types_ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
ZodObject.strictCreate = (shape, params)=>new ZodObject({
shape: ()=>shape,
unknownKeys: "strict",
catchall: ZodNever.create(),
typeName: types_ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
ZodObject.lazycreate = (shape, params)=>new ZodObject({
shape,
unknownKeys: "strip",
catchall: ZodNever.create(),
typeName: types_ZodFirstPartyTypeKind.ZodObject,
...processCreateParams(params)
});
class ZodUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const options = this._def.options;
function handleResults(results) {
for (const result of results)if ("valid" === result.result.status) return result.result;
for (const result of results)if ("dirty" === result.result.status) {
ctx.common.issues.push(...result.ctx.common.issues);
return result.result;
}
const unionErrors = results.map((result)=>new ZodError(result.ctx.common.issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return parseUtil_INVALID;
}
if (ctx.common.async) return Promise.all(options.map(async (option)=>{
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
return {
result: await option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: childCtx
}),
ctx: childCtx
};
})).then(handleResults);
{
let dirty;
const issues = [];
for (const option of options){
const childCtx = {
...ctx,
common: {
...ctx.common,
issues: []
},
parent: null
};
const result = option._parseSync({
data: ctx.data,
path: ctx.path,
parent: childCtx
});
if ("valid" === result.status) return result;
if ("dirty" === result.status && !dirty) dirty = {
result,
ctx: childCtx
};
if (childCtx.common.issues.length) issues.push(childCtx.common.issues);
}
if (dirty) {
ctx.common.issues.push(...dirty.ctx.common.issues);
return dirty.result;
}
const unionErrors = issues.map((issues)=>new ZodError(issues));
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union,
unionErrors
});
return parseUtil_INVALID;
}
}
get options() {
return this._def.options;
}
}
ZodUnion.create = (types, params)=>new ZodUnion({
options: types,
typeName: types_ZodFirstPartyTypeKind.ZodUnion,
...processCreateParams(params)
});
const getDiscriminator = (type)=>{
if (type instanceof ZodLazy) return getDiscriminator(type.schema);
if (type instanceof ZodEffects) return getDiscriminator(type.innerType());
if (type instanceof ZodLiteral) return [
type.value
];
if (type instanceof ZodEnum) return type.options;
if (type instanceof ZodNativeEnum) return util_util.objectValues(type.enum);
else if (type instanceof ZodDefault) return getDiscriminator(type._def.innerType);
else if (type instanceof ZodUndefined) return [
void 0
];
else if (type instanceof ZodNull) return [
null
];
else if (type instanceof ZodOptional) return [
void 0,
...getDiscriminator(type.unwrap())
];
else if (type instanceof ZodNullable) return [
null,
...getDiscriminator(type.unwrap())
];
else if (type instanceof ZodBranded) return getDiscriminator(type.unwrap());
else if (type instanceof ZodReadonly) return getDiscriminator(type.unwrap());
else if (type instanceof ZodCatch) return getDiscriminator(type._def.innerType);
else return [];
};
class ZodDiscriminatedUnion extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const discriminator = this.discriminator;
const discriminatorValue = ctx.data[discriminator];
const option = this.optionsMap.get(discriminatorValue);
if (!option) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_union_discriminator,
options: Array.from(this.optionsMap.keys()),
path: [
discriminator
]
});
return parseUtil_INVALID;
}
if (ctx.common.async) return option._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
return option._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
get discriminator() {
return this._def.discriminator;
}
get options() {
return this._def.options;
}
get optionsMap() {
return this._def.optionsMap;
}
static create(discriminator, options, params) {
const optionsMap = new Map();
for (const type of options){
const discriminatorValues = getDiscriminator(type.shape[discriminator]);
if (!discriminatorValues.length) throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
for (const value of discriminatorValues){
if (optionsMap.has(value)) throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
optionsMap.set(value, type);
}
}
return new ZodDiscriminatedUnion({
typeName: types_ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
discriminator,
options,
optionsMap,
...processCreateParams(params)
});
}
}
function mergeValues(a, b) {
const aType = getParsedType(a);
const bType = getParsedType(b);
if (a === b) return {
valid: true,
data: a
};
if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
const bKeys = util_util.objectKeys(b);
const sharedKeys = util_util.objectKeys(a).filter((key)=>-1 !== bKeys.indexOf(key));
const newObj = {
...a,
...b
};
for (const key of sharedKeys){
const sharedValue = mergeValues(a[key], b[key]);
if (!sharedValue.valid) return {
valid: false
};
newObj[key] = sharedValue.data;
}
return {
valid: true,
data: newObj
};
}
if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
if (a.length !== b.length) return {
valid: false
};
const newArray = [];
for(let index = 0; index < a.length; index++){
const itemA = a[index];
const itemB = b[index];
const sharedValue = mergeValues(itemA, itemB);
if (!sharedValue.valid) return {
valid: false
};
newArray.push(sharedValue.data);
}
return {
valid: true,
data: newArray
};
}
if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) return {
valid: true,
data: a
};
return {
valid: false
};
}
class ZodIntersection extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const handleParsed = (parsedLeft, parsedRight)=>{
if (isAborted(parsedLeft) || isAborted(parsedRight)) return parseUtil_INVALID;
const merged = mergeValues(parsedLeft.value, parsedRight.value);
if (!merged.valid) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_intersection_types
});
return parseUtil_INVALID;
}
if (isDirty(parsedLeft) || isDirty(parsedRight)) status.dirty();
return {
status: status.value,
value: merged.data
};
};
if (ctx.common.async) return Promise.all([
this._def.left._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}),
this._def.right._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
})
]).then(([left, right])=>handleParsed(left, right));
return handleParsed(this._def.left._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}), this._def.right._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
}));
}
}
ZodIntersection.create = (left, right, params)=>new ZodIntersection({
left: left,
right: right,
typeName: types_ZodFirstPartyTypeKind.ZodIntersection,
...processCreateParams(params)
});
class ZodTuple extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.array) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.array,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
if (ctx.data.length < this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
return parseUtil_INVALID;
}
const rest = this._def.rest;
if (!rest && ctx.data.length > this._def.items.length) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: this._def.items.length,
inclusive: true,
exact: false,
type: "array"
});
status.dirty();
}
const items = [
...ctx.data
].map((item, itemIndex)=>{
const schema = this._def.items[itemIndex] || this._def.rest;
if (!schema) return null;
return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
}).filter((x)=>!!x);
if (ctx.common.async) return Promise.all(items).then((results)=>ParseStatus.mergeArray(status, results));
return ParseStatus.mergeArray(status, items);
}
get items() {
return this._def.items;
}
rest(rest) {
return new ZodTuple({
...this._def,
rest
});
}
}
ZodTuple.create = (schemas, params)=>{
if (!Array.isArray(schemas)) throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
return new ZodTuple({
items: schemas,
typeName: types_ZodFirstPartyTypeKind.ZodTuple,
rest: null,
...processCreateParams(params)
});
};
class ZodRecord extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.object) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.object,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const pairs = [];
const keyType = this._def.keyType;
const valueType = this._def.valueType;
for(const key in ctx.data)pairs.push({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
alwaysSet: key in ctx.data
});
if (ctx.common.async) return ParseStatus.mergeObjectAsync(status, pairs);
return ParseStatus.mergeObjectSync(status, pairs);
}
get element() {
return this._def.valueType;
}
static create(first, second, third) {
if (second instanceof ZodType) return new ZodRecord({
keyType: first,
valueType: second,
typeName: types_ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(third)
});
return new ZodRecord({
keyType: ZodString.create(),
valueType: first,
typeName: types_ZodFirstPartyTypeKind.ZodRecord,
...processCreateParams(second)
});
}
}
class ZodMap extends ZodType {
get keySchema() {
return this._def.keyType;
}
get valueSchema() {
return this._def.valueType;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.map) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.map,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const keyType = this._def.keyType;
const valueType = this._def.valueType;
const pairs = [
...ctx.data.entries()
].map(([key, value], index)=>({
key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [
index,
"key"
])),
value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [
index,
"value"
]))
}));
if (ctx.common.async) {
const finalMap = new Map();
return Promise.resolve().then(async ()=>{
for (const pair of pairs){
const key = await pair.key;
const value = await pair.value;
if ("aborted" === key.status || "aborted" === value.status) return parseUtil_INVALID;
if ("dirty" === key.status || "dirty" === value.status) status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
});
}
{
const finalMap = new Map();
for (const pair of pairs){
const key = pair.key;
const value = pair.value;
if ("aborted" === key.status || "aborted" === value.status) return parseUtil_INVALID;
if ("dirty" === key.status || "dirty" === value.status) status.dirty();
finalMap.set(key.value, value.value);
}
return {
status: status.value,
value: finalMap
};
}
}
}
ZodMap.create = (keyType, valueType, params)=>new ZodMap({
valueType,
keyType,
typeName: types_ZodFirstPartyTypeKind.ZodMap,
...processCreateParams(params)
});
class ZodSet extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.set) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.set,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const def = this._def;
if (null !== def.minSize) {
if (ctx.data.size < def.minSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_small,
minimum: def.minSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.minSize.message
});
status.dirty();
}
}
if (null !== def.maxSize) {
if (ctx.data.size > def.maxSize.value) {
addIssueToContext(ctx, {
code: ZodIssueCode.too_big,
maximum: def.maxSize.value,
type: "set",
inclusive: true,
exact: false,
message: def.maxSize.message
});
status.dirty();
}
}
const valueType = this._def.valueType;
function finalizeSet(elements) {
const parsedSet = new Set();
for (const element of elements){
if ("aborted" === element.status) return parseUtil_INVALID;
if ("dirty" === element.status) status.dirty();
parsedSet.add(element.value);
}
return {
status: status.value,
value: parsedSet
};
}
const elements = [
...ctx.data.values()
].map((item, i)=>valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));
if (ctx.common.async) return Promise.all(elements).then((elements)=>finalizeSet(elements));
return finalizeSet(elements);
}
min(minSize, message) {
return new ZodSet({
...this._def,
minSize: {
value: minSize,
message: errorUtil_errorUtil.toString(message)
}
});
}
max(maxSize, message) {
return new ZodSet({
...this._def,
maxSize: {
value: maxSize,
message: errorUtil_errorUtil.toString(message)
}
});
}
size(size, message) {
return this.min(size, message).max(size, message);
}
nonempty(message) {
return this.min(1, message);
}
}
ZodSet.create = (valueType, params)=>new ZodSet({
valueType,
minSize: null,
maxSize: null,
typeName: types_ZodFirstPartyTypeKind.ZodSet,
...processCreateParams(params)
});
class ZodFunction extends ZodType {
constructor(){
super(...arguments);
this.validate = this.implement;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType["function"]) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType["function"],
received: ctx.parsedType
});
return parseUtil_INVALID;
}
function makeArgsIssue(args, error) {
return makeIssue({
data: args,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
locales_en
].filter((x)=>!!x),
issueData: {
code: ZodIssueCode.invalid_arguments,
argumentsError: error
}
});
}
function makeReturnsIssue(returns, error) {
return makeIssue({
data: returns,
path: ctx.path,
errorMaps: [
ctx.common.contextualErrorMap,
ctx.schemaErrorMap,
getErrorMap(),
locales_en
].filter((x)=>!!x),
issueData: {
code: ZodIssueCode.invalid_return_type,
returnTypeError: error
}
});
}
const params = {
errorMap: ctx.common.contextualErrorMap
};
const fn = ctx.data;
if (this._def.returns instanceof ZodPromise) {
const me = this;
return OK(async function(...args) {
const error = new ZodError([]);
const parsedArgs = await me._def.args.parseAsync(args, params).catch((e)=>{
error.addIssue(makeArgsIssue(args, e));
throw error;
});
const result = await Reflect.apply(fn, this, parsedArgs);
const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e)=>{
error.addIssue(makeReturnsIssue(result, e));
throw error;
});
return parsedReturns;
});
}
{
const me = this;
return OK(function(...args) {
const parsedArgs = me._def.args.safeParse(args, params);
if (!parsedArgs.success) throw new ZodError([
makeArgsIssue(args, parsedArgs.error)
]);
const result = Reflect.apply(fn, this, parsedArgs.data);
const parsedReturns = me._def.returns.safeParse(result, params);
if (!parsedReturns.success) throw new ZodError([
makeReturnsIssue(result, parsedReturns.error)
]);
return parsedReturns.data;
});
}
}
parameters() {
return this._def.args;
}
returnType() {
return this._def.returns;
}
args(...items) {
return new ZodFunction({
...this._def,
args: ZodTuple.create(items).rest(ZodUnknown.create())
});
}
returns(returnType) {
return new ZodFunction({
...this._def,
returns: returnType
});
}
implement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
strictImplement(func) {
const validatedFunc = this.parse(func);
return validatedFunc;
}
static create(args, returns, params) {
return new ZodFunction({
args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
returns: returns || ZodUnknown.create(),
typeName: types_ZodFirstPartyTypeKind.ZodFunction,
...processCreateParams(params)
});
}
}
class ZodLazy extends ZodType {
get schema() {
return this._def.getter();
}
_parse(input) {
const { ctx } = this._processInputParams(input);
const lazySchema = this._def.getter();
return lazySchema._parse({
data: ctx.data,
path: ctx.path,
parent: ctx
});
}
}
ZodLazy.create = (getter, params)=>new ZodLazy({
getter: getter,
typeName: types_ZodFirstPartyTypeKind.ZodLazy,
...processCreateParams(params)
});
class ZodLiteral extends ZodType {
_parse(input) {
if (input.data !== this._def.value) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_literal,
expected: this._def.value
});
return parseUtil_INVALID;
}
return {
status: "valid",
value: input.data
};
}
get value() {
return this._def.value;
}
}
ZodLiteral.create = (value, params)=>new ZodLiteral({
value: value,
typeName: types_ZodFirstPartyTypeKind.ZodLiteral,
...processCreateParams(params)
});
function createZodEnum(values, params) {
return new ZodEnum({
values,
typeName: types_ZodFirstPartyTypeKind.ZodEnum,
...processCreateParams(params)
});
}
class ZodEnum extends ZodType {
_parse(input) {
if ("string" != typeof input.data) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
expected: util_util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return parseUtil_INVALID;
}
if (!this._cache) this._cache = new Set(this._def.values);
if (!this._cache.has(input.data)) {
const ctx = this._getOrReturnCtx(input);
const expectedValues = this._def.values;
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return parseUtil_INVALID;
}
return OK(input.data);
}
get options() {
return this._def.values;
}
get enum() {
const enumValues = {};
for (const val of this._def.values)enumValues[val] = val;
return enumValues;
}
get Values() {
const enumValues = {};
for (const val of this._def.values)enumValues[val] = val;
return enumValues;
}
get Enum() {
const enumValues = {};
for (const val of this._def.values)enumValues[val] = val;
return enumValues;
}
extract(values, newDef = this._def) {
return ZodEnum.create(values, {
...this._def,
...newDef
});
}
exclude(values, newDef = this._def) {
return ZodEnum.create(this.options.filter((opt)=>!values.includes(opt)), {
...this._def,
...newDef
});
}
}
ZodEnum.create = createZodEnum;
class ZodNativeEnum extends ZodType {
_parse(input) {
const nativeEnumValues = util_util.getValidEnumValues(this._def.values);
const ctx = this._getOrReturnCtx(input);
if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
const expectedValues = util_util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
expected: util_util.joinValues(expectedValues),
received: ctx.parsedType,
code: ZodIssueCode.invalid_type
});
return parseUtil_INVALID;
}
if (!this._cache) this._cache = new Set(util_util.getValidEnumValues(this._def.values));
if (!this._cache.has(input.data)) {
const expectedValues = util_util.objectValues(nativeEnumValues);
addIssueToContext(ctx, {
received: ctx.data,
code: ZodIssueCode.invalid_enum_value,
options: expectedValues
});
return parseUtil_INVALID;
}
return OK(input.data);
}
get enum() {
return this._def.values;
}
}
ZodNativeEnum.create = (values, params)=>new ZodNativeEnum({
values: values,
typeName: types_ZodFirstPartyTypeKind.ZodNativeEnum,
...processCreateParams(params)
});
class ZodPromise extends ZodType {
unwrap() {
return this._def.type;
}
_parse(input) {
const { ctx } = this._processInputParams(input);
if (ctx.parsedType !== ZodParsedType.promise && false === ctx.common.async) {
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.promise,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
return OK(promisified.then((data)=>this._def.type.parseAsync(data, {
path: ctx.path,
errorMap: ctx.common.contextualErrorMap
})));
}
}
ZodPromise.create = (schema, params)=>new ZodPromise({
type: schema,
typeName: types_ZodFirstPartyTypeKind.ZodPromise,
...processCreateParams(params)
});
class ZodEffects extends ZodType {
innerType() {
return this._def.schema;
}
sourceType() {
return this._def.schema._def.typeName === types_ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
}
_parse(input) {
const { status, ctx } = this._processInputParams(input);
const effect = this._def.effect || null;
const checkCtx = {
addIssue: (arg)=>{
addIssueToContext(ctx, arg);
if (arg.fatal) status.abort();
else status.dirty();
},
get path () {
return ctx.path;
}
};
checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
if ("preprocess" === effect.type) {
const processed = effect.transform(ctx.data, checkCtx);
if (ctx.common.async) return Promise.resolve(processed).then(async (processed)=>{
if ("aborted" === status.value) return parseUtil_INVALID;
const result = await this._def.schema._parseAsync({
data: processed,
path: ctx.path,
parent: ctx
});
if ("aborted" === result.status) return parseUtil_INVALID;
if ("dirty" === result.status) return DIRTY(result.value);
if ("dirty" === status.value) return DIRTY(result.value);
return result;
});
{
if ("aborted" === status.value) return parseUtil_INVALID;
const result = this._def.schema._parseSync({
data: processed,
path: ctx.path,
parent: ctx
});
if ("aborted" === result.status) return parseUtil_INVALID;
if ("dirty" === result.status) return DIRTY(result.value);
if ("dirty" === status.value) return DIRTY(result.value);
return result;
}
}
if ("refinement" === effect.type) {
const executeRefinement = (acc)=>{
const result = effect.refinement(acc, checkCtx);
if (ctx.common.async) return Promise.resolve(result);
if (result instanceof Promise) throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
return acc;
};
if (false !== ctx.common.async) return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((inner)=>{
if ("aborted" === inner.status) return parseUtil_INVALID;
if ("dirty" === inner.status) status.dirty();
return executeRefinement(inner.value).then(()=>({
status: status.value,
value: inner.value
}));
});
{
const inner = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if ("aborted" === inner.status) return parseUtil_INVALID;
if ("dirty" === inner.status) status.dirty();
executeRefinement(inner.value);
return {
status: status.value,
value: inner.value
};
}
}
if ("transform" === effect.type) if (false !== ctx.common.async) return this._def.schema._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
}).then((base)=>{
if (!parseUtil_isValid(base)) return parseUtil_INVALID;
return Promise.resolve(effect.transform(base.value, checkCtx)).then((result)=>({
status: status.value,
value: result
}));
});
else {
const base = this._def.schema._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if (!parseUtil_isValid(base)) return parseUtil_INVALID;
const result = effect.transform(base.value, checkCtx);
if (result instanceof Promise) throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
return {
status: status.value,
value: result
};
}
util_util.assertNever(effect);
}
}
ZodEffects.create = (schema, effect, params)=>new ZodEffects({
schema,
typeName: types_ZodFirstPartyTypeKind.ZodEffects,
effect,
...processCreateParams(params)
});
ZodEffects.createWithPreprocess = (preprocess, schema, params)=>new ZodEffects({
schema,
effect: {
type: "preprocess",
transform: preprocess
},
typeName: types_ZodFirstPartyTypeKind.ZodEffects,
...processCreateParams(params)
});
class ZodOptional extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType.undefined) return OK(void 0);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodOptional.create = (type, params)=>new ZodOptional({
innerType: type,
typeName: types_ZodFirstPartyTypeKind.ZodOptional,
...processCreateParams(params)
});
class ZodNullable extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType === ZodParsedType["null"]) return OK(null);
return this._def.innerType._parse(input);
}
unwrap() {
return this._def.innerType;
}
}
ZodNullable.create = (type, params)=>new ZodNullable({
innerType: type,
typeName: types_ZodFirstPartyTypeKind.ZodNullable,
...processCreateParams(params)
});
class ZodDefault extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
let data = ctx.data;
if (ctx.parsedType === ZodParsedType.undefined) data = this._def.defaultValue();
return this._def.innerType._parse({
data,
path: ctx.path,
parent: ctx
});
}
removeDefault() {
return this._def.innerType;
}
}
ZodDefault.create = (type, params)=>new ZodDefault({
innerType: type,
typeName: types_ZodFirstPartyTypeKind.ZodDefault,
defaultValue: "function" == typeof params.default ? params.default : ()=>params.default,
...processCreateParams(params)
});
class ZodCatch extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const newCtx = {
...ctx,
common: {
...ctx.common,
issues: []
}
};
const result = this._def.innerType._parse({
data: newCtx.data,
path: newCtx.path,
parent: {
...newCtx
}
});
if (isAsync(result)) return result.then((result)=>({
status: "valid",
value: "valid" === result.status ? result.value : this._def.catchValue({
get error () {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
}));
return {
status: "valid",
value: "valid" === result.status ? result.value : this._def.catchValue({
get error () {
return new ZodError(newCtx.common.issues);
},
input: newCtx.data
})
};
}
removeCatch() {
return this._def.innerType;
}
}
ZodCatch.create = (type, params)=>new ZodCatch({
innerType: type,
typeName: types_ZodFirstPartyTypeKind.ZodCatch,
catchValue: "function" == typeof params.catch ? params.catch : ()=>params.catch,
...processCreateParams(params)
});
class ZodNaN extends ZodType {
_parse(input) {
const parsedType = this._getType(input);
if (parsedType !== ZodParsedType.nan) {
const ctx = this._getOrReturnCtx(input);
addIssueToContext(ctx, {
code: ZodIssueCode.invalid_type,
expected: ZodParsedType.nan,
received: ctx.parsedType
});
return parseUtil_INVALID;
}
return {
status: "valid",
value: input.data
};
}
}
ZodNaN.create = (params)=>new ZodNaN({
typeName: types_ZodFirstPartyTypeKind.ZodNaN,
...processCreateParams(params)
});
Symbol("zod_brand");
class ZodBranded extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}
class ZodPipeline extends ZodType {
_parse(input) {
const { status, ctx } = this._processInputParams(input);
if (ctx.common.async) {
const handleAsync = async ()=>{
const inResult = await this._def.in._parseAsync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if ("aborted" === inResult.status) return parseUtil_INVALID;
if ("dirty" !== inResult.status) return this._def.out._parseAsync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
status.dirty();
return DIRTY(inResult.value);
};
return handleAsync();
}
{
const inResult = this._def.in._parseSync({
data: ctx.data,
path: ctx.path,
parent: ctx
});
if ("aborted" === inResult.status) return parseUtil_INVALID;
if ("dirty" !== inResult.status) return this._def.out._parseSync({
data: inResult.value,
path: ctx.path,
parent: ctx
});
status.dirty();
return {
status: "dirty",
value: inResult.value
};
}
}
static create(a, b) {
return new ZodPipeline({
in: a,
out: b,
typeName: types_ZodFirstPartyTypeKind.ZodPipeline
});
}
}
class ZodReadonly extends ZodType {
_parse(input) {
const result = this._def.innerType._parse(input);
const freeze = (data)=>{
if (parseUtil_isValid(data)) data.value = Object.freeze(data.value);
return data;
};
return isAsync(result) ? result.then((data)=>freeze(data)) : freeze(result);
}
unwrap() {
return this._def.innerType;
}
}
ZodReadonly.create = (type, params)=>new ZodReadonly({
innerType: type,
typeName: types_ZodFirstPartyTypeKind.ZodReadonly,
...processCreateParams(params)
});
ZodObject.lazycreate;
var types_ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind) {
ZodFirstPartyTypeKind["ZodString"] = "ZodString";
ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber";
ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN";
ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt";
ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean";
ZodFirstPartyTypeKind["ZodDate"] = "ZodDate";
ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol";
ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined";
ZodFirstPartyTypeKind["ZodNull"] = "ZodNull";
ZodFirstPartyTypeKind["ZodAny"] = "ZodAny";
ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown";
ZodFirstPartyTypeKind["ZodNever"] = "ZodNever";
ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid";
ZodFirstPartyTypeKind["ZodArray"] = "ZodArray";
ZodFirstPartyTypeKind["ZodObject"] = "ZodObject";
ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion";
ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection";
ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple";
ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord";
ZodFirstPartyTypeKind["ZodMap"] = "ZodMap";
ZodFirstPartyTypeKind["ZodSet"] = "ZodSet";
ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction";
ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy";
ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral";
ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum";
ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects";
ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum";
ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional";
ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable";
ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault";
ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch";
ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise";
ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded";
ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline";
ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly";
})(types_ZodFirstPartyTypeKind || (types_ZodFirstPartyTypeKind = {}));
const stringType = ZodString.create;
const numberType = ZodNumber.create;
ZodNaN.create;
ZodBigInt.create;
const booleanType = ZodBoolean.create;
ZodDate.create;
ZodSymbol.create;
ZodUndefined.create;
ZodNull.create;
ZodAny.create;
const unknownType = ZodUnknown.create;
ZodNever.create;
ZodVoid.create;
const arrayType = ZodArray.create;
const objectType = ZodObject.create;
ZodObject.strictCreate;
const unionType = ZodUnion.create;
const discriminatedUnionType = ZodDiscriminatedUnion.create;
ZodIntersection.create;
ZodTuple.create;
const recordType = ZodRecord.create;
ZodMap.create;
ZodSet.create;
ZodFunction.create;
ZodLazy.create;
const literalType = ZodLiteral.create;
const enumType = ZodEnum.create;
ZodNativeEnum.create;
ZodPromise.create;
ZodEffects.create;
const optionalType = ZodOptional.create;
ZodNullable.create;
ZodEffects.createWithPreprocess;
ZodPipeline.create;
const LATEST_PROTOCOL_VERSION = "2025-06-18";
const SUPPORTED_PROTOCOL_VERSIONS = [
LATEST_PROTOCOL_VERSION,
"2025-03-26",
"2024-11-05",
"2024-10-07"
];
const JSONRPC_VERSION = "2.0";
const ProgressTokenSchema = unionType([
stringType(),
numberType().int()
]);
const CursorSchema = stringType();
const RequestMetaSchema = objectType({
progressToken: optionalType(ProgressTokenSchema)
}).passthrough();
const BaseRequestParamsSchema = objectType({
_meta: optionalType(RequestMetaSchema)
}).passthrough();
const RequestSchema = objectType({
method: stringType(),
params: optionalType(BaseRequestParamsSchema)
});
const BaseNotificationParamsSchema = objectType({
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const NotificationSchema = objectType({
method: stringType(),
params: optionalType(BaseNotificationParamsSchema)
});
const ResultSchema = objectType({
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const RequestIdSchema = unionType([
stringType(),
numberType().int()
]);
const JSONRPCRequestSchema = objectType({
jsonrpc: literalType(JSONRPC_VERSION),
id: RequestIdSchema
}).merge(RequestSchema).strict();
const isJSONRPCRequest = (value)=>JSONRPCRequestSchema.safeParse(value).success;
const JSONRPCNotificationSchema = objectType({
jsonrpc: literalType(JSONRPC_VERSION)
}).merge(NotificationSchema).strict();
const isJSONRPCNotification = (value)=>JSONRPCNotificationSchema.safeParse(value).success;
const JSONRPCResponseSchema = objectType({
jsonrpc: literalType(JSONRPC_VERSION),
id: RequestIdSchema,
result: ResultSchema
}).strict();
const isJSONRPCResponse = (value)=>JSONRPCResponseSchema.safeParse(value).success;
var types_ErrorCode;
(function(ErrorCode) {
ErrorCode[ErrorCode["ConnectionClosed"] = -32000] = "ConnectionClosed";
ErrorCode[ErrorCode["RequestTimeout"] = -32001] = "RequestTimeout";
ErrorCode[ErrorCode["ParseError"] = -32700] = "ParseError";
ErrorCode[ErrorCode["InvalidRequest"] = -32600] = "InvalidRequest";
ErrorCode[ErrorCode["MethodNotFound"] = -32601] = "MethodNotFound";
ErrorCode[ErrorCode["InvalidParams"] = -32602] = "InvalidParams";
ErrorCode[ErrorCode["InternalError"] = -32603] = "InternalError";
})(types_ErrorCode || (types_ErrorCode = {}));
const JSONRPCErrorSchema = objectType({
jsonrpc: literalType(JSONRPC_VERSION),
id: RequestIdSchema,
error: objectType({
code: numberType().int(),
message: stringType(),
data: optionalType(unknownType())
})
}).strict();
const isJSONRPCError = (value)=>JSONRPCErrorSchema.safeParse(value).success;
const JSONRPCMessageSchema = unionType([
JSONRPCRequestSchema,
JSONRPCNotificationSchema,
JSONRPCResponseSchema,
JSONRPCErrorSchema
]);
const EmptyResultSchema = ResultSchema.strict();
const CancelledNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/cancelled"),
params: BaseNotificationParamsSchema.extend({
requestId: RequestIdSchema,
reason: stringType().optional()
})
});
const BaseMetadataSchema = objectType({
name: stringType(),
title: optionalType(stringType())
}).passthrough();
const ImplementationSchema = BaseMetadataSchema.extend({
version: stringType()
});
const ClientCapabilitiesSchema = objectType({
experimental: optionalType(objectType({}).passthrough()),
sampling: optionalType(objectType({}).passthrough()),
elicitation: optionalType(objectType({}).passthrough()),
roots: optionalType(objectType({
listChanged: optionalType(booleanType())
}).passthrough())
}).passthrough();
const InitializeRequestSchema = RequestSchema.extend({
method: literalType("initialize"),
params: BaseRequestParamsSchema.extend({
protocolVersion: stringType(),
capabilities: ClientCapabilitiesSchema,
clientInfo: ImplementationSchema
})
});
const ServerCapabilitiesSchema = objectType({
experimental: optionalType(objectType({}).passthrough()),
logging: optionalType(objectType({}).passthrough()),
completions: optionalType(objectType({}).passthrough()),
prompts: optionalType(objectType({
listChanged: optionalType(booleanType())
}).passthrough()),
resources: optionalType(objectType({
subscribe: optionalType(booleanType()),
listChanged: optionalType(booleanType())
}).passthrough()),
tools: optionalType(objectType({
listChanged: optionalType(booleanType())
}).passthrough())
}).passthrough();
const InitializeResultSchema = ResultSchema.extend({
protocolVersion: stringType(),
capabilities: ServerCapabilitiesSchema,
serverInfo: ImplementationSchema,
instructions: optionalType(stringType())
});
const InitializedNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/initialized")
});
const PingRequestSchema = RequestSchema.extend({
method: literalType("ping")
});
const ProgressSchema = objectType({
progress: numberType(),
total: optionalType(numberType()),
message: optionalType(stringType())
}).passthrough();
const ProgressNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/progress"),
params: BaseNotificationParamsSchema.merge(ProgressSchema).extend({
progressToken: ProgressTokenSchema
})
});
const PaginatedRequestSchema = RequestSchema.extend({
params: BaseRequestParamsSchema.extend({
cursor: optionalType(CursorSchema)
}).optional()
});
const PaginatedResultSchema = ResultSchema.extend({
nextCursor: optionalType(CursorSchema)
});
const ResourceContentsSchema = objectType({
uri: stringType(),
mimeType: optionalType(stringType()),
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const TextResourceContentsSchema = ResourceContentsSchema.extend({
text: stringType()
});
const BlobResourceContentsSchema = ResourceContentsSchema.extend({
blob: stringType().base64()
});
const ResourceSchema = BaseMetadataSchema.extend({
uri: stringType(),
description: optionalType(stringType()),
mimeType: optionalType(stringType()),
_meta: optionalType(objectType({}).passthrough())
});
const ResourceTemplateSchema = BaseMetadataSchema.extend({
uriTemplate: stringType(),
description: optionalType(stringType()),
mimeType: optionalType(stringType()),
_meta: optionalType(objectType({}).passthrough())
});
const ListResourcesRequestSchema = PaginatedRequestSchema.extend({
method: literalType("resources/list")
});
const ListResourcesResultSchema = PaginatedResultSchema.extend({
resources: arrayType(ResourceSchema)
});
const ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
method: literalType("resources/templates/list")
});
const ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
resourceTemplates: arrayType(ResourceTemplateSchema)
});
const ReadResourceRequestSchema = RequestSchema.extend({
method: literalType("resources/read"),
params: BaseRequestParamsSchema.extend({
uri: stringType()
})
});
const ReadResourceResultSchema = ResultSchema.extend({
contents: arrayType(unionType([
TextResourceContentsSchema,
BlobResourceContentsSchema
]))
});
const ResourceListChangedNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/resources/list_changed")
});
const SubscribeRequestSchema = RequestSchema.extend({
method: literalType("resources/subscribe"),
params: BaseRequestParamsSchema.extend({
uri: stringType()
})
});
const UnsubscribeRequestSchema = RequestSchema.extend({
method: literalType("resources/unsubscribe"),
params: BaseRequestParamsSchema.extend({
uri: stringType()
})
});
const ResourceUpdatedNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/resources/updated"),
params: BaseNotificationParamsSchema.extend({
uri: stringType()
})
});
const PromptArgumentSchema = objectType({
name: stringType(),
description: optionalType(stringType()),
required: optionalType(booleanType())
}).passthrough();
const PromptSchema = BaseMetadataSchema.extend({
description: optionalType(stringType()),
arguments: optionalType(arrayType(PromptArgumentSchema)),
_meta: optionalType(objectType({}).passthrough())
});
const ListPromptsRequestSchema = PaginatedRequestSchema.extend({
method: literalType("prompts/list")
});
const ListPromptsResultSchema = PaginatedResultSchema.extend({
prompts: arrayType(PromptSchema)
});
const GetPromptRequestSchema = RequestSchema.extend({
method: literalType("prompts/get"),
params: BaseRequestParamsSchema.extend({
name: stringType(),
arguments: optionalType(recordType(stringType()))
})
});
const TextContentSchema = objectType({
type: literalType("text"),
text: stringType(),
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const ImageContentSchema = objectType({
type: literalType("image"),
data: stringType().base64(),
mimeType: stringType(),
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const AudioContentSchema = objectType({
type: literalType("audio"),
data: stringType().base64(),
mimeType: stringType(),
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const EmbeddedResourceSchema = objectType({
type: literalType("resource"),
resource: unionType([
TextResourceContentsSchema,
BlobResourceContentsSchema
]),
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const ResourceLinkSchema = ResourceSchema.extend({
type: literalType("resource_link")
});
const ContentBlockSchema = unionType([
TextContentSchema,
ImageContentSchema,
AudioContentSchema,
ResourceLinkSchema,
EmbeddedResourceSchema
]);
const PromptMessageSchema = objectType({
role: enumType([
"user",
"assistant"
]),
content: ContentBlockSchema
}).passthrough();
const GetPromptResultSchema = ResultSchema.extend({
description: optionalType(stringType()),
messages: arrayType(PromptMessageSchema)
});
const PromptListChangedNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/prompts/list_changed")
});
const ToolAnnotationsSchema = objectType({
title: optionalType(stringType()),
readOnlyHint: optionalType(booleanType()),
destructiveHint: optionalType(booleanType()),
idempotentHint: optionalType(booleanType()),
openWorldHint: optionalType(booleanType())
}).passthrough();
const ToolSchema = BaseMetadataSchema.extend({
description: optionalType(stringType()),
inputSchema: objectType({
type: literalType("object"),
properties: optionalType(objectType({}).passthrough()),
required: optionalType(arrayType(stringType()))
}).passthrough(),
outputSchema: optionalType(objectType({
type: literalType("object"),
properties: optionalType(objectType({}).passthrough()),
required: optionalType(arrayType(stringType()))
}).passthrough()),
annotations: optionalType(ToolAnnotationsSchema),
_meta: optionalType(objectType({}).passthrough())
});
const ListToolsRequestSchema = PaginatedRequestSchema.extend({
method: literalType("tools/list")
});
const ListToolsResultSchema = PaginatedResultSchema.extend({
tools: arrayType(ToolSchema)
});
const CallToolResultSchema = ResultSchema.extend({
content: arrayType(ContentBlockSchema).default([]),
structuredContent: objectType({}).passthrough().optional(),
isError: optionalType(booleanType())
});
CallToolResultSchema.or(ResultSchema.extend({
toolResult: unknownType()
}));
const CallToolRequestSchema = RequestSchema.extend({
method: literalType("tools/call"),
params: BaseRequestParamsSchema.extend({
name: stringType(),
arguments: optionalType(recordType(unknownType()))
})
});
const ToolListChangedNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/tools/list_changed")
});
const LoggingLevelSchema = enumType([
"debug",
"info",
"notice",
"warning",
"error",
"critical",
"alert",
"emergency"
]);
const SetLevelRequestSchema = RequestSchema.extend({
method: literalType("logging/setLevel"),
params: BaseRequestParamsSchema.extend({
level: LoggingLevelSchema
})
});
const LoggingMessageNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/message"),
params: BaseNotificationParamsSchema.extend({
level: LoggingLevelSchema,
logger: optionalType(stringType()),
data: unknownType()
})
});
const ModelHintSchema = objectType({
name: stringType().optional()
}).passthrough();
const ModelPreferencesSchema = objectType({
hints: optionalType(arrayType(ModelHintSchema)),
costPriority: optionalType(numberType().min(0).max(1)),
speedPriority: optionalType(numberType().min(0).max(1)),
intelligencePriority: optionalType(numberType().min(0).max(1))
}).passthrough();
const SamplingMessageSchema = objectType({
role: enumType([
"user",
"assistant"
]),
content: unionType([
TextContentSchema,
ImageContentSchema,
AudioContentSchema
])
}).passthrough();
const CreateMessageRequestSchema = RequestSchema.extend({
method: literalType("sampling/createMessage"),
params: BaseRequestParamsSchema.extend({
messages: arrayType(SamplingMessageSchema),
systemPrompt: optionalType(stringType()),
includeContext: optionalType(enumType([
"none",
"thisServer",
"allServers"
])),
temperature: optionalType(numberType()),
maxTokens: numberType().int(),
stopSequences: optionalType(arrayType(stringType())),
metadata: optionalType(objectType({}).passthrough()),
modelPreferences: optionalType(ModelPreferencesSchema)
})
});
const CreateMessageResultSchema = ResultSchema.extend({
model: stringType(),
stopReason: optionalType(enumType([
"endTurn",
"stopSequence",
"maxTokens"
]).or(stringType())),
role: enumType([
"user",
"assistant"
]),
content: discriminatedUnionType("type", [
TextContentSchema,
ImageContentSchema,
AudioContentSchema
])
});
const BooleanSchemaSchema = objectType({
type: literalType("boolean"),
title: optionalType(stringType()),
description: optionalType(stringType()),
default: optionalType(booleanType())
}).passthrough();
const StringSchemaSchema = objectType({
type: literalType("string"),
title: optionalType(stringType()),
description: optionalType(stringType()),
minLength: optionalType(numberType()),
maxLength: optionalType(numberType()),
format: optionalType(enumType([
"email",
"uri",
"date",
"date-time"
]))
}).passthrough();
const NumberSchemaSchema = objectType({
type: enumType([
"number",
"integer"
]),
title: optionalType(stringType()),
description: optionalType(stringType()),
minimum: optionalType(numberType()),
maximum: optionalType(numberType())
}).passthrough();
const EnumSchemaSchema = objectType({
type: literalType("string"),
title: optionalType(stringType()),
description: optionalType(stringType()),
enum: arrayType(stringType()),
enumNames: optionalType(arrayType(stringType()))
}).passthrough();
const PrimitiveSchemaDefinitionSchema = unionType([
BooleanSchemaSchema,
StringSchemaSchema,
NumberSchemaSchema,
EnumSchemaSchema
]);
const ElicitRequestSchema = RequestSchema.extend({
method: literalType("elicitation/create"),
params: BaseRequestParamsSchema.extend({
message: stringType(),
requestedSchema: objectType({
type: literalType("object"),
properties: recordType(stringType(), PrimitiveSchemaDefinitionSchema),
required: optionalType(arrayType(stringType()))
}).passthrough()
})
});
const ElicitResultSchema = ResultSchema.extend({
action: enumType([
"accept",
"decline",
"cancel"
]),
content: optionalType(recordType(stringType(), unknownType()))
});
const ResourceTemplateReferenceSchema = objectType({
type: literalType("ref/resource"),
uri: stringType()
}).passthrough();
const PromptReferenceSchema = objectType({
type: literalType("ref/prompt"),
name: stringType()
}).passthrough();
const CompleteRequestSchema = RequestSchema.extend({
method: literalType("completion/complete"),
params: BaseRequestParamsSchema.extend({
ref: unionType([
PromptReferenceSchema,
ResourceTemplateReferenceSchema
]),
argument: objectType({
name: stringType(),
value: stringType()
}).passthrough(),
context: optionalType(objectType({
arguments: optionalType(recordType(stringType(), stringType()))
}))
})
});
const CompleteResultSchema = ResultSchema.extend({
completion: objectType({
values: arrayType(stringType()).max(100),
total: optionalType(numberType().int()),
hasMore: optionalType(booleanType())
}).passthrough()
});
const RootSchema = objectType({
uri: stringType().startsWith("file://"),
name: optionalType(stringType()),
_meta: optionalType(objectType({}).passthrough())
}).passthrough();
const ListRootsRequestSchema = RequestSchema.extend({
method: literalType("roots/list")
});
const ListRootsResultSchema = ResultSchema.extend({
roots: arrayType(RootSchema)
});
const RootsListChangedNotificationSchema = NotificationSchema.extend({
method: literalType("notifications/roots/list_changed")
});
unionType([
PingRequestSchema,
InitializeRequestSchema,
CompleteRequestSchema,
SetLevelRequestSchema,
GetPromptRequestSchema,
ListPromptsRequestSchema,
ListResourcesRequestSchema,
ListResourceTemplatesRequestSchema,
ReadResourceRequestSchema,
SubscribeRequestSchema,
UnsubscribeRequestSchema,
CallToolRequestSchema,
ListToolsRequestSchema
]);
unionType([
CancelledNotificationSchema,
ProgressNotificationSchema,
InitializedNotificationSchema,
RootsListChangedNotificationSchema
]);
unionType([
EmptyResultSchema,
CreateMessageResultSchema,
ElicitResultSchema,
ListRootsResultSchema
]);
unionType([
PingRequestSchema,
CreateMessageRequestSchema,
ElicitRequestSchema,
ListRootsRequestSchema
]);
unionType([
CancelledNotificationSchema,
ProgressNotificationSchema,
LoggingMessageNotificationSchema,
ResourceUpdatedNotificationSchema,
ResourceListChangedNotificationSchema,
ToolListChangedNotificationSchema,
PromptListChangedNotificationSchema
]);
unionType([
EmptyResultSchema,
InitializeResultSchema,
CompleteResultSchema,
GetPromptResultSchema,
ListPromptsResultSchema,
ListResourcesResultSchema,
ListResourceTemplatesResultSchema,
ReadResourceResultSchema,
CallToolResultSchema,
ListToolsResultSchema
]);
class McpError extends Error {
constructor(code, message, data){
super(`MCP error ${code}: ${message}`);
this.code = code;
this.data = data;
this.name = "McpError";
}
}
const DEFAULT_REQUEST_TIMEOUT_MSEC = 60000;
class Protocol {
constructor(_options){
this._options = _options;
this._requestMessageId = 0;
this._requestHandlers = new Map();
this._requestHandlerAbortControllers = new Map();
this._notificationHandlers = new Map();
this._responseHandlers = new Map();
this._progressHandlers = new Map();
this._timeoutInfo = new Map();
this._pendingDebouncedNotifications = new Set();
this.setNotificationHandler(CancelledNotificationSchema, (notification)=>{
const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
null == controller || controller.abort(notification.params.reason);
});
this.setNotificationHandler(ProgressNotificationSchema, (notification)=>{
this._onprogress(notification);
});
this.setRequestHandler(PingRequestSchema, (_request)=>({}));
}
_setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
this._timeoutInfo.set(messageId, {
timeoutId: setTimeout(onTimeout, timeout),
startTime: Date.now(),
timeout,
maxTotalTimeout,
resetTimeoutOnProgress,
onTimeout
});
}
_resetTimeout(messageId) {
const info = this._timeoutInfo.get(messageId);
if (!info) return false;
const totalElapsed = Date.now() - info.startTime;
if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
this._timeoutInfo.delete(messageId);
throw new McpError(types_ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
maxTotalTimeout: info.maxTotalTimeout,
totalElapsed
});
}
clearTimeout(info.timeoutId);
info.timeoutId = setTimeout(info.onTimeout, info.timeout);
return true;
}
_cleanupTimeout(messageId) {
const info = this._timeoutInfo.get(messageId);
if (info) {
clearTimeout(info.timeoutId);
this._timeoutInfo.delete(messageId);
}
}
async connect(transport) {
var _a, _b, _c;
this._transport = transport;
const _onclose = null == (_a = this.transport) ? void 0 : _a.onclose;
this._transport.onclose = ()=>{
null == _onclose || _onclose();
this._onclose();
};
const _onerror = null == (_b = this.transport) ? void 0 : _b.onerror;
this._transport.onerror = (error)=>{
null == _onerror || _onerror(error);
this._onerror(error);
};
const _onmessage = null == (_c = this._transport) ? void 0 : _c.onmessage;
this._transport.onmessage = (message, extra)=>{
null == _onmessage || _onmessage(message, extra);
if (isJSONRPCResponse(message) || isJSONRPCError(message)) this._onresponse(message);
else if (isJSONRPCRequest(message)) this._onrequest(message, extra);
else if (isJSONRPCNotification(message)) this._onnotification(message);
else this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
};
await this._transport.start();
}
_onclose() {
var _a;
const responseHandlers = this._responseHandlers;
this._responseHandlers = new Map();
this._progressHandlers.clear();
this._pendingDebouncedNotifications.clear();
this._transport = void 0;
null == (_a = this.onclose) || _a.call(this);
const error = new McpError(types_ErrorCode.ConnectionClosed, "Connection closed");
for (const handler of responseHandlers.values())handler(error);
}
_onerror(error) {
var _a;
null == (_a = this.onerror) || _a.call(this, error);
}
_onnotification(notification) {
var _a;
const handler = null != (_a = this._notificationHandlers.get(notification.method)) ? _a : this.fallbackNotificationHandler;
if (void 0 === handler) return;
Promise.resolve().then(()=>handler(notification)).catch((error)=>this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
}
_onrequest(request, extra) {
var _a, _b, _c, _d;
const handler = null != (_a = this._requestHandlers.get(request.method)) ? _a : this.fallbackRequestHandler;
if (void 0 === handler) return void (null == (_b = this._transport) || _b.send({
jsonrpc: "2.0",
id: request.id,
error: {
code: types_ErrorCode.MethodNotFound,
message: "Method not found"
}
}).catch((error)=>this._onerror(new Error(`Failed to send an error response: ${error}`))));
const abortController = new AbortController();
this._requestHandlerAbortControllers.set(request.id, abortController);
const fullExtra = {
signal: abortController.signal,
sessionId: null == (_c = this._transport) ? void 0 : _c.sessionId,
_meta: null == (_d = request.params) ? void 0 : _d._meta,
sendNotification: (notification)=>this.notification(notification, {
relatedRequestId: request.id
}),
sendRequest: (r, resultSchema, options)=>this.request(r, resultSchema, {
...options,
relatedRequestId: request.id
}),
authInfo: null == extra ? void 0 : extra.authInfo,
requestId: request.id,
requestInfo: null == extra ? void 0 : extra.requestInfo
};
Promise.resolve().then(()=>handler(request, fullExtra)).then((result)=>{
var _a;
if (abortController.signal.aborted) return;
return null == (_a = this._transport) ? void 0 : _a.send({
result,
jsonrpc: "2.0",
id: request.id
});
}, (error)=>{
var _a, _b;
if (abortController.signal.aborted) return;
return null == (_a = this._transport) ? void 0 : _a.send({
jsonrpc: "2.0",
id: request.id,
error: {
code: Number.isSafeInteger(error["code"]) ? error["code"] : types_ErrorCode.InternalError,
message: null != (_b = error.message) ? _b : "Internal error"
}
});
}).catch((error)=>this._onerror(new Error(`Failed to send response: ${error}`))).finally(()=>{
this._requestHandlerAbortControllers.delete(request.id);
});
}
_onprogress(notification) {
const { progressToken, ...params } = notification.params;
const messageId = Number(progressToken);
const handler = this._progressHandlers.get(messageId);
if (!handler) return void this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
const responseHandler = this._responseHandlers.get(messageId);
const timeoutInfo = this._timeoutInfo.get(messageId);
if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) try {
this._resetTimeout(messageId);
} catch (error) {
responseHandler(error);
return;
}
handler(params);
}
_onresponse(response) {
const messageId = Number(response.id);
const handler = this._responseHandlers.get(messageId);
if (void 0 === handler) return void this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
this._responseHandlers.delete(messageId);
this._progressHandlers.delete(messageId);
this._cleanupTimeout(messageId);
if (isJSONRPCResponse(response)) handler(response);
else {
const error = new McpError(response.error.code, response.error.message, response.error.data);
handler(error);
}
}
get transport() {
return this._transport;
}
async close() {
var _a;
await (null == (_a = this._transport) ? void 0 : _a.close());
}
request(request, resultSchema, options) {
const { relatedRequestId, resumptionToken, onresumptiontoken } = null != options ? options : {};
return new Promise((resolve, reject)=>{
var _a, _b, _c, _d, _e, _f;
if (!this._transport) return void reject(new Error("Not connected"));
if ((null == (_a = this._options) ? void 0 : _a.enforceStrictCapabilities) === true) this.assertCapabilityForMethod(request.method);
null == (_b = null == options ? void 0 : options.signal) || _b.throwIfAborted();
const messageId = this._requestMessageId++;
const jsonrpcRequest = {
...request,
jsonrpc: "2.0",
id: messageId
};
if (null == options ? void 0 : options.onprogress) {
this._progressHandlers.set(messageId, options.onprogress);
jsonrpcRequest.params = {
...request.params,
_meta: {
...(null == (_c = request.params) ? void 0 : _c._meta) || {},
progressToken: messageId
}
};
}
const cancel = (reason)=>{
var _a;
this._responseHandlers.delete(messageId);
this._progressHandlers.delete(messageId);
this._cleanupTimeout(messageId);
null == (_a = this._transport) || _a.send({
jsonrpc: "2.0",
method: "notifications/cancelled",
params: {
requestId: messageId,
reason: String(reason)
}
}, {
relatedRequestId,
resumptionToken,
onresumptiontoken
}).catch((error)=>this._onerror(new Error(`Failed to send cancellation: ${error}`)));
reject(reason);
};
this._responseHandlers.set(messageId, (response)=>{
var _a;
if (null == (_a = null == options ? void 0 : options.signal) ? void 0 : _a.aborted) return;
if (response instanceof Error) return reject(response);
try {
const result = resultSchema.parse(response.result);
resolve(result);
} catch (error) {
reject(error);
}
});
null == (_d = null == options ? void 0 : options.signal) || _d.addEventListener("abort", ()=>{
var _a;
cancel(null == (_a = null == options ? void 0 : options.signal) ? void 0 : _a.reason);
});
const timeout = null != (_e = null == options ? void 0 : options.timeout) ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
const timeoutHandler = ()=>cancel(new McpError(types_ErrorCode.RequestTimeout, "Request timed out", {
timeout
}));
this._setupTimeout(messageId, timeout, null == options ? void 0 : options.maxTotalTimeout, timeoutHandler, null != (_f = null == options ? void 0 : options.resetTimeoutOnProgress) ? _f : false);
this._transport.send(jsonrpcRequest, {
relatedRequestId,
resumptionToken,
onresumptiontoken
}).catch((error)=>{
this._cleanupTimeout(messageId);
reject(error);
});
});
}
async notification(notification, options) {
var _a, _b;
if (!this._transport) throw new Error("Not connected");
this.assertNotificationCapability(notification.method);
const debouncedMethods = null != (_b = null == (_a = this._options) ? void 0 : _a.debouncedNotificationMethods) ? _b : [];
const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(null == options ? void 0 : options.relatedRequestId);
if (canDebounce) {
if (this._pendingDebouncedNotifications.has(notification.method)) return;
this._pendingDebouncedNotifications.add(notification.method);
Promise.resolve().then(()=>{
var _a;
this._pendingDebouncedNotifications.delete(notification.method);
if (!this._transport) return;
const jsonrpcNotification = {
...notification,
jsonrpc: "2.0"
};
null == (_a = this._transport) || _a.send(jsonrpcNotification, options).catch((error)=>this._onerror(error));
});
return;
}
const jsonrpcNotification = {
...notification,
jsonrpc: "2.0"
};
await this._transport.send(jsonrpcNotification, options);
}
setRequestHandler(requestSchema, handler) {
const method = requestSchema.shape.method.value;
this.assertRequestHandlerCapability(method);
this._requestHandlers.set(method, (request, extra)=>Promise.resolve(handler(requestSchema.parse(request), extra)));
}
removeRequestHandler(method) {
this._requestHandlers.delete(method);
}
assertCanSetRequestHandler(method) {
if (this._requestHandlers.has(method)) throw new Error(`A request handler for ${method} already exists, which would be overridden`);
}
setNotificationHandler(notificationSchema, handler) {
this._notificationHandlers.set(notificationSchema.shape.method.value, (notification)=>Promise.resolve(handler(notificationSchema.parse(notification))));
}
removeNotificationHandler(method) {
this._notificationHandlers.delete(method);
}
}
function mergeCapabilities(base, additional) {
return Object.entries(additional).reduce((acc, [key, value])=>{
if (value && "object" == typeof value) acc[key] = acc[key] ? {
...acc[key],
...value
} : value;
else acc[key] = value;
return acc;
}, {
...base
});
}
var lib_ajv = __webpack_require__("./node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/ajv.js");
class Server extends Protocol {
constructor(_serverInfo, options){
var _a;
super(options);
this._serverInfo = _serverInfo;
this._capabilities = null != (_a = null == options ? void 0 : options.capabilities) ? _a : {};
this._instructions = null == options ? void 0 : options.instructions;
this.setRequestHandler(InitializeRequestSchema, (request)=>this._oninitialize(request));
this.setNotificationHandler(InitializedNotificationSchema, ()=>{
var _a;
return null == (_a = this.oninitialized) ? void 0 : _a.call(this);
});
}
registerCapabilities(capabilities) {
if (this.transport) throw new Error("Cannot register capabilities after connecting to transport");
this._capabilities = mergeCapabilities(this._capabilities, capabilities);
}
assertCapabilityForMethod(method) {
var _a, _b, _c;
switch(method){
case "sampling/createMessage":
if (!(null == (_a = this._clientCapabilities) ? void 0 : _a.sampling)) throw new Error(`Client does not support sampling (required for ${method})`);
break;
case "elicitation/create":
if (!(null == (_b = this._clientCapabilities) ? void 0 : _b.elicitation)) throw new Error(`Client does not support elicitation (required for ${method})`);
break;
case "roots/list":
if (!(null == (_c = this._clientCapabilities) ? void 0 : _c.roots)) throw new Error(`Client does not support listing roots (required for ${method})`);
break;
case "ping":
break;
}
}
assertNotificationCapability(method) {
switch(method){
case "notifications/message":
if (!this._capabilities.logging) throw new Error(`Server does not support logging (required for ${method})`);
break;
case "notifications/resources/updated":
case "notifications/resources/list_changed":
if (!this._capabilities.resources) throw new Error(`Server does not support notifying about resources (required for ${method})`);
break;
case "notifications/tools/list_changed":
if (!this._capabilities.tools) throw new Error(`Server does not support notifying of tool list changes (required for ${method})`);
break;
case "notifications/prompts/list_changed":
if (!this._capabilities.prompts) throw new Error(`Server does not support notifying of prompt list changes (required for ${method})`);
break;
case "notifications/cancelled":
break;
case "notifications/progress":
break;
}
}
assertRequestHandlerCapability(method) {
switch(method){
case "sampling/createMessage":
if (!this._capabilities.sampling) throw new Error(`Server does not support sampling (required for ${method})`);
break;
case "logging/setLevel":
if (!this._capabilities.logging) throw new Error(`Server does not support logging (required for ${method})`);
break;
case "prompts/get":
case "prompts/list":
if (!this._capabilities.prompts) throw new Error(`Server does not support prompts (required for ${method})`);
break;
case "resources/list":
case "resources/templates/list":
case "resources/read":
if (!this._capabilities.resources) throw new Error(`Server does not support resources (required for ${method})`);
break;
case "tools/call":
case "tools/list":
if (!this._capabilities.tools) throw new Error(`Server does not support tools (required for ${method})`);
break;
case "ping":
case "initialize":
break;
}
}
async _oninitialize(request) {
const requestedVersion = request.params.protocolVersion;
this._clientCapabilities = request.params.capabilities;
this._clientVersion = request.params.clientInfo;
const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requestedVersion) ? requestedVersion : LATEST_PROTOCOL_VERSION;
return {
protocolVersion,
capabilities: this.getCapabilities(),
serverInfo: this._serverInfo,
...this._instructions && {
instructions: this._instructions
}
};
}
getClientCapabilities() {
return this._clientCapabilities;
}
getClientVersion() {
return this._clientVersion;
}
getCapabilities() {
return this._capabilities;
}
async ping() {
return this.request({
method: "ping"
}, EmptyResultSchema);
}
async createMessage(params, options) {
return this.request({
method: "sampling/createMessage",
params
}, CreateMessageResultSchema, options);
}
async elicitInput(params, options) {
const result = await this.request({
method: "elicitation/create",
params
}, ElicitResultSchema, options);
if ("accept" === result.action && result.content) try {
const ajv = new lib_ajv();
const validate = ajv.compile(params.requestedSchema);
const isValid = validate(result.content);
if (!isValid) throw new McpError(types_ErrorCode.InvalidParams, `Elicitation response content does not match requested schema: ${ajv.errorsText(validate.errors)}`);
} catch (error) {
if (error instanceof McpError) throw error;
throw new McpError(types_ErrorCode.InternalError, `Error validating elicitation response: ${error}`);
}
return result;
}
async listRoots(params, options) {
return this.request({
method: "roots/list",
params
}, ListRootsResultSchema, options);
}
async sendLoggingMessage(params) {
return this.notification({
method: "notifications/message",
params
});
}
async sendResourceUpdated(params) {
return this.notification({
method: "notifications/resources/updated",
params
});
}
async sendResourceListChanged() {
return this.notification({
method: "notifications/resources/list_changed"
});
}
async sendToolListChanged() {
return this.notification({
method: "notifications/tools/list_changed"
});
}
async sendPromptListChanged() {
return this.notification({
method: "notifications/prompts/list_changed"
});
}
}
const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
const defaultOptions = {
name: void 0,
$refStrategy: "root",
basePath: [
"#"
],
effectStrategy: "input",
pipeStrategy: "all",
dateStrategy: "format:date-time",
mapStrategy: "entries",
removeAdditionalStrategy: "passthrough",
allowedAdditionalProperties: true,
rejectedAdditionalProperties: false,
definitionPath: "definitions",
target: "jsonSchema7",
strictUnions: false,
definitions: {},
errorMessages: false,
markdownDescription: false,
patternStrategy: "escape",
applyRegexFlags: false,
emailStrategy: "format:email",
base64Strategy: "contentEncoding:base64",
nameStrategy: "ref",
openAiAnyTypeName: "OpenAiAnyType"
};
const getDefaultOptions = (options)=>"string" == typeof options ? {
...defaultOptions,
name: options
} : {
...defaultOptions,
...options
};
const getRefs = (options)=>{
const _options = getDefaultOptions(options);
const currentPath = void 0 !== _options.name ? [
..._options.basePath,
_options.definitionPath,
_options.name
] : _options.basePath;
return {
..._options,
flags: {
hasReferencedOpenAiAnyType: false
},
currentPath: currentPath,
propertyPath: void 0,
seen: new Map(Object.entries(_options.definitions).map(([name, def])=>[
def._def,
{
def: def._def,
path: [
..._options.basePath,
_options.definitionPath,
name
],
jsonSchema: void 0
}
]))
};
};
const getRelativePath = (pathA, pathB)=>{
let i = 0;
for(; i < pathA.length && i < pathB.length && pathA[i] === pathB[i]; i++);
return [
(pathA.length - i).toString(),
...pathB.slice(i)
].join("/");
};
function parseAnyDef(refs) {
if ("openAi" !== refs.target) return {};
const anyDefinitionPath = [
...refs.basePath,
refs.definitionPath,
refs.openAiAnyTypeName
];
refs.flags.hasReferencedOpenAiAnyType = true;
return {
$ref: "relative" === refs.$refStrategy ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/")
};
}
function addErrorMessage(res, key, errorMessage, refs) {
if (!refs?.errorMessages) return;
if (errorMessage) res.errorMessage = {
...res.errorMessage,
[key]: errorMessage
};
}
function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
res[key] = value;
addErrorMessage(res, key, errorMessage, refs);
}
function parseArrayDef(def, refs) {
const res = {
type: "array"
};
if (def.type?._def && def.type?._def?.typeName !== types_ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, {
...refs,
currentPath: [
...refs.currentPath,
"items"
]
});
if (def.minLength) setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
if (def.maxLength) setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
if (def.exactLength) {
setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
}
return res;
}
function parseBigintDef(def, refs) {
const res = {
type: "integer",
format: "int64"
};
if (!def.checks) return res;
for (const check of def.checks)switch(check.kind){
case "min":
if ("jsonSchema7" === refs.target) check.inclusive ? setResponseValueAndErrors(res, "minimum", check.value, check.message, refs) : setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
else {
if (!check.inclusive) res.exclusiveMinimum = true;
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if ("jsonSchema7" === refs.target) check.inclusive ? setResponseValueAndErrors(res, "maximum", check.value, check.message, refs) : setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
else {
if (!check.inclusive) res.exclusiveMaximum = true;
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
return res;
}
function parseBooleanDef() {
return {
type: "boolean"
};
}
function parseBrandedDef(_def, refs) {
return parseDef(_def.type._def, refs);
}
const parseCatchDef = (def, refs)=>parseDef(def.innerType._def, refs);
function parseDateDef(def, refs, overrideDateStrategy) {
const strategy = overrideDateStrategy ?? refs.dateStrategy;
if (Array.isArray(strategy)) return {
anyOf: strategy.map((item, i)=>parseDateDef(def, refs, item))
};
switch(strategy){
case "string":
case "format:date-time":
return {
type: "string",
format: "date-time"
};
case "format:date":
return {
type: "string",
format: "date"
};
case "integer":
return integerDateParser(def, refs);
}
}
const integerDateParser = (def, refs)=>{
const res = {
type: "integer",
format: "unix-time"
};
if ("openApi3" === refs.target) return res;
for (const check of def.checks)switch(check.kind){
case "min":
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
break;
}
return res;
};
function parseDefaultDef(_def, refs) {
return {
...parseDef(_def.innerType._def, refs),
default: _def.defaultValue()
};
}
function parseEffectsDef(_def, refs) {
return "input" === refs.effectStrategy ? parseDef(_def.schema._def, refs) : parseAnyDef(refs);
}
function parseEnumDef(def) {
return {
type: "string",
enum: Array.from(def.values)
};
}
const isJsonSchema7AllOfType = (type)=>{
if ("type" in type && "string" === type.type) return false;
return "allOf" in type;
};
function parseIntersectionDef(def, refs) {
const allOf = [
parseDef(def.left._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
}),
parseDef(def.right._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"1"
]
})
].filter((x)=>!!x);
let unevaluatedProperties = "jsonSchema2019-09" === refs.target ? {
unevaluatedProperties: false
} : void 0;
const mergedAllOf = [];
allOf.forEach((schema)=>{
if (isJsonSchema7AllOfType(schema)) {
mergedAllOf.push(...schema.allOf);
if (void 0 === schema.unevaluatedProperties) unevaluatedProperties = void 0;
} else {
let nestedSchema = schema;
if ("additionalProperties" in schema && false === schema.additionalProperties) {
const { additionalProperties, ...rest } = schema;
nestedSchema = rest;
} else unevaluatedProperties = void 0;
mergedAllOf.push(nestedSchema);
}
});
return mergedAllOf.length ? {
allOf: mergedAllOf,
...unevaluatedProperties
} : void 0;
}
function parseLiteralDef(def, refs) {
const parsedType = typeof def.value;
if ("bigint" !== parsedType && "number" !== parsedType && "boolean" !== parsedType && "string" !== parsedType) return {
type: Array.isArray(def.value) ? "array" : "object"
};
if ("openApi3" === refs.target) return {
type: "bigint" === parsedType ? "integer" : parsedType,
enum: [
def.value
]
};
return {
type: "bigint" === parsedType ? "integer" : parsedType,
const: def.value
};
}
let string_emojiRegex;
const zodPatterns = {
cuid: /^[cC][^\s-]{8,}$/,
cuid2: /^[0-9a-z]+$/,
ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
emoji: ()=>{
if (void 0 === string_emojiRegex) string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
return string_emojiRegex;
},
uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
nanoid: /^[a-zA-Z0-9_-]{21}$/,
jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
};
function parseStringDef(def, refs) {
const res = {
type: "string"
};
if (def.checks) for (const check of def.checks)switch(check.kind){
case "min":
setResponseValueAndErrors(res, "minLength", "number" == typeof res.minLength ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
break;
case "max":
setResponseValueAndErrors(res, "maxLength", "number" == typeof res.maxLength ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
break;
case "email":
switch(refs.emailStrategy){
case "format:email":
addFormat(res, "email", check.message, refs);
break;
case "format:idn-email":
addFormat(res, "idn-email", check.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.email, check.message, refs);
break;
}
break;
case "url":
addFormat(res, "uri", check.message, refs);
break;
case "uuid":
addFormat(res, "uuid", check.message, refs);
break;
case "regex":
addPattern(res, check.regex, check.message, refs);
break;
case "cuid":
addPattern(res, zodPatterns.cuid, check.message, refs);
break;
case "cuid2":
addPattern(res, zodPatterns.cuid2, check.message, refs);
break;
case "startsWith":
addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
break;
case "endsWith":
addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
break;
case "datetime":
addFormat(res, "date-time", check.message, refs);
break;
case "date":
addFormat(res, "date", check.message, refs);
break;
case "time":
addFormat(res, "time", check.message, refs);
break;
case "duration":
addFormat(res, "duration", check.message, refs);
break;
case "length":
setResponseValueAndErrors(res, "minLength", "number" == typeof res.minLength ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
setResponseValueAndErrors(res, "maxLength", "number" == typeof res.maxLength ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
break;
case "includes":
addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
break;
case "ip":
if ("v6" !== check.version) addFormat(res, "ipv4", check.message, refs);
if ("v4" !== check.version) addFormat(res, "ipv6", check.message, refs);
break;
case "base64url":
addPattern(res, zodPatterns.base64url, check.message, refs);
break;
case "jwt":
addPattern(res, zodPatterns.jwt, check.message, refs);
break;
case "cidr":
if ("v6" !== check.version) addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
if ("v4" !== check.version) addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
break;
case "emoji":
addPattern(res, zodPatterns.emoji(), check.message, refs);
break;
case "ulid":
addPattern(res, zodPatterns.ulid, check.message, refs);
break;
case "base64":
switch(refs.base64Strategy){
case "format:binary":
addFormat(res, "binary", check.message, refs);
break;
case "contentEncoding:base64":
setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
break;
case "pattern:zod":
addPattern(res, zodPatterns.base64, check.message, refs);
break;
}
break;
case "nanoid":
addPattern(res, zodPatterns.nanoid, check.message, refs);
case "toLowerCase":
case "toUpperCase":
case "trim":
break;
default:
((_)=>{})(0);
}
return res;
}
function escapeLiteralCheckValue(literal, refs) {
return "escape" === refs.patternStrategy ? escapeNonAlphaNumeric(literal) : literal;
}
const ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
function escapeNonAlphaNumeric(source) {
let result = "";
for(let i = 0; i < source.length; i++){
if (!ALPHA_NUMERIC.has(source[i])) result += "\\";
result += source[i];
}
return result;
}
function addFormat(schema, value, message, refs) {
if (schema.format || schema.anyOf?.some((x)=>x.format)) {
if (!schema.anyOf) schema.anyOf = [];
if (schema.format) {
schema.anyOf.push({
format: schema.format,
...schema.errorMessage && refs.errorMessages && {
errorMessage: {
format: schema.errorMessage.format
}
}
});
delete schema.format;
if (schema.errorMessage) {
delete schema.errorMessage.format;
if (0 === Object.keys(schema.errorMessage).length) delete schema.errorMessage;
}
}
schema.anyOf.push({
format: value,
...message && refs.errorMessages && {
errorMessage: {
format: message
}
}
});
} else setResponseValueAndErrors(schema, "format", value, message, refs);
}
function addPattern(schema, regex, message, refs) {
if (schema.pattern || schema.allOf?.some((x)=>x.pattern)) {
if (!schema.allOf) schema.allOf = [];
if (schema.pattern) {
schema.allOf.push({
pattern: schema.pattern,
...schema.errorMessage && refs.errorMessages && {
errorMessage: {
pattern: schema.errorMessage.pattern
}
}
});
delete schema.pattern;
if (schema.errorMessage) {
delete schema.errorMessage.pattern;
if (0 === Object.keys(schema.errorMessage).length) delete schema.errorMessage;
}
}
schema.allOf.push({
pattern: stringifyRegExpWithFlags(regex, refs),
...message && refs.errorMessages && {
errorMessage: {
pattern: message
}
}
});
} else setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
}
function stringifyRegExpWithFlags(regex, refs) {
if (!refs.applyRegexFlags || !regex.flags) return regex.source;
const flags = {
i: regex.flags.includes("i"),
m: regex.flags.includes("m"),
s: regex.flags.includes("s")
};
const source = flags.i ? regex.source.toLowerCase() : regex.source;
let pattern = "";
let isEscaped = false;
let inCharGroup = false;
let inCharRange = false;
for(let i = 0; i < source.length; i++){
if (isEscaped) {
pattern += source[i];
isEscaped = false;
continue;
}
if (flags.i) {
if (inCharGroup) {
if (source[i].match(/[a-z]/)) {
if (inCharRange) {
pattern += source[i];
pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
inCharRange = false;
} else if ("-" === source[i + 1] && source[i + 2]?.match(/[a-z]/)) {
pattern += source[i];
inCharRange = true;
} else pattern += `${source[i]}${source[i].toUpperCase()}`;
continue;
}
} else if (source[i].match(/[a-z]/)) {
pattern += `[${source[i]}${source[i].toUpperCase()}]`;
continue;
}
}
if (flags.m) {
if ("^" === source[i]) {
pattern += `(^|(?<=[\r\n]))`;
continue;
} else if ("$" === source[i]) {
pattern += `($|(?=[\r\n]))`;
continue;
}
}
if (flags.s && "." === source[i]) {
pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`;
continue;
}
pattern += source[i];
if ("\\" === source[i]) isEscaped = true;
else if (inCharGroup && "]" === source[i]) inCharGroup = false;
else if (!inCharGroup && "[" === source[i]) inCharGroup = true;
}
try {
new RegExp(pattern);
} catch {
console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
return regex.source;
}
return pattern;
}
function parseRecordDef(def, refs) {
if ("openAi" === refs.target) console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
if ("openApi3" === refs.target && def.keyType?._def.typeName === types_ZodFirstPartyTypeKind.ZodEnum) return {
type: "object",
required: def.keyType._def.values,
properties: def.keyType._def.values.reduce((acc, key)=>({
...acc,
[key]: parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
key
]
}) ?? parseAnyDef(refs)
}), {}),
additionalProperties: refs.rejectedAdditionalProperties
};
const schema = {
type: "object",
additionalProperties: parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"additionalProperties"
]
}) ?? refs.allowedAdditionalProperties
};
if ("openApi3" === refs.target) return schema;
if (def.keyType?._def.typeName === types_ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) {
const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
if (def.keyType?._def.typeName === types_ZodFirstPartyTypeKind.ZodEnum) return {
...schema,
propertyNames: {
enum: def.keyType._def.values
}
};
if (def.keyType?._def.typeName === types_ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === types_ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) {
const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
return {
...schema,
propertyNames: keyType
};
}
return schema;
}
function parseMapDef(def, refs) {
if ("record" === refs.mapStrategy) return parseRecordDef(def, refs);
const keys = parseDef(def.keyType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"0"
]
}) || parseAnyDef(refs);
const values = parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
"items",
"1"
]
}) || parseAnyDef(refs);
return {
type: "array",
maxItems: 125,
items: {
type: "array",
items: [
keys,
values
],
minItems: 2,
maxItems: 2
}
};
}
function parseNativeEnumDef(def) {
const object = def.values;
const actualKeys = Object.keys(def.values).filter((key)=>"number" != typeof object[object[key]]);
const actualValues = actualKeys.map((key)=>object[key]);
const parsedTypes = Array.from(new Set(actualValues.map((values)=>typeof values)));
return {
type: 1 === parsedTypes.length ? "string" === parsedTypes[0] ? "string" : "number" : [
"string",
"number"
],
enum: actualValues
};
}
function parseNeverDef(refs) {
return "openAi" === refs.target ? void 0 : {
not: parseAnyDef({
...refs,
currentPath: [
...refs.currentPath,
"not"
]
})
};
}
function parseNullDef(refs) {
return "openApi3" === refs.target ? {
enum: [
"null"
],
nullable: true
} : {
type: "null"
};
}
const primitiveMappings = {
ZodString: "string",
ZodNumber: "number",
ZodBigInt: "integer",
ZodBoolean: "boolean",
ZodNull: "null"
};
function parseUnionDef(def, refs) {
if ("openApi3" === refs.target) return asAnyOf(def, refs);
const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
if (options.every((x)=>x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
const types = options.reduce((types, x)=>{
const type = primitiveMappings[x._def.typeName];
return type && !types.includes(type) ? [
...types,
type
] : types;
}, []);
return {
type: types.length > 1 ? types : types[0]
};
}
if (options.every((x)=>"ZodLiteral" === x._def.typeName && !x.description)) {
const types = options.reduce((acc, x)=>{
const type = typeof x._def.value;
switch(type){
case "string":
case "number":
case "boolean":
return [
...acc,
type
];
case "bigint":
return [
...acc,
"integer"
];
case "object":
if (null === x._def.value) return [
...acc,
"null"
];
case "symbol":
case "undefined":
case "function":
default:
return acc;
}
}, []);
if (types.length === options.length) {
const uniqueTypes = types.filter((x, i, a)=>a.indexOf(x) === i);
return {
type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
enum: options.reduce((acc, x)=>acc.includes(x._def.value) ? acc : [
...acc,
x._def.value
], [])
};
}
} else if (options.every((x)=>"ZodEnum" === x._def.typeName)) return {
type: "string",
enum: options.reduce((acc, x)=>[
...acc,
...x._def.values.filter((x)=>!acc.includes(x))
], [])
};
return asAnyOf(def, refs);
}
const asAnyOf = (def, refs)=>{
const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i)=>parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
`${i}`
]
})).filter((x)=>!!x && (!refs.strictUnions || "object" == typeof x && Object.keys(x).length > 0));
return anyOf.length ? {
anyOf
} : void 0;
};
function parseNullableDef(def, refs) {
if ([
"ZodString",
"ZodNumber",
"ZodBigInt",
"ZodBoolean",
"ZodNull"
].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
if ("openApi3" === refs.target) return {
type: primitiveMappings[def.innerType._def.typeName],
nullable: true
};
return {
type: [
primitiveMappings[def.innerType._def.typeName],
"null"
]
};
}
if ("openApi3" === refs.target) {
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath
]
});
if (base && "$ref" in base) return {
allOf: [
base
],
nullable: true
};
return base && {
...base,
nullable: true
};
}
const base = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"0"
]
});
return base && {
anyOf: [
base,
{
type: "null"
}
]
};
}
function parseNumberDef(def, refs) {
const res = {
type: "number"
};
if (!def.checks) return res;
for (const check of def.checks)switch(check.kind){
case "int":
res.type = "integer";
addErrorMessage(res, "type", check.message, refs);
break;
case "min":
if ("jsonSchema7" === refs.target) check.inclusive ? setResponseValueAndErrors(res, "minimum", check.value, check.message, refs) : setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
else {
if (!check.inclusive) res.exclusiveMinimum = true;
setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
}
break;
case "max":
if ("jsonSchema7" === refs.target) check.inclusive ? setResponseValueAndErrors(res, "maximum", check.value, check.message, refs) : setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
else {
if (!check.inclusive) res.exclusiveMaximum = true;
setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
}
break;
case "multipleOf":
setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
break;
}
return res;
}
function parseObjectDef(def, refs) {
const forceOptionalIntoNullable = "openAi" === refs.target;
const result = {
type: "object",
properties: {}
};
const required = [];
const shape = def.shape();
for(const propName in shape){
let propDef = shape[propName];
if (void 0 === propDef || void 0 === propDef._def) continue;
let propOptional = safeIsOptional(propDef);
if (propOptional && forceOptionalIntoNullable) {
if ("ZodOptional" === propDef._def.typeName) propDef = propDef._def.innerType;
if (!propDef.isNullable()) propDef = propDef.nullable();
propOptional = false;
}
const parsedDef = parseDef(propDef._def, {
...refs,
currentPath: [
...refs.currentPath,
"properties",
propName
],
propertyPath: [
...refs.currentPath,
"properties",
propName
]
});
if (void 0 !== parsedDef) {
result.properties[propName] = parsedDef;
if (!propOptional) required.push(propName);
}
}
if (required.length) result.required = required;
const additionalProperties = decideAdditionalProperties(def, refs);
if (void 0 !== additionalProperties) result.additionalProperties = additionalProperties;
return result;
}
function decideAdditionalProperties(def, refs) {
if ("ZodNever" !== def.catchall._def.typeName) return parseDef(def.catchall._def, {
...refs,
currentPath: [
...refs.currentPath,
"additionalProperties"
]
});
switch(def.unknownKeys){
case "passthrough":
return refs.allowedAdditionalProperties;
case "strict":
return refs.rejectedAdditionalProperties;
case "strip":
return "strict" === refs.removeAdditionalStrategy ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
}
}
function safeIsOptional(schema) {
try {
return schema.isOptional();
} catch {
return true;
}
}
const parseOptionalDef = (def, refs)=>{
if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs);
const innerSchema = parseDef(def.innerType._def, {
...refs,
currentPath: [
...refs.currentPath,
"anyOf",
"1"
]
});
return innerSchema ? {
anyOf: [
{
not: parseAnyDef(refs)
},
innerSchema
]
} : parseAnyDef(refs);
};
const parsePipelineDef = (def, refs)=>{
if ("input" === refs.pipeStrategy) return parseDef(def.in._def, refs);
if ("output" === refs.pipeStrategy) return parseDef(def.out._def, refs);
const a = parseDef(def.in._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
"0"
]
});
const b = parseDef(def.out._def, {
...refs,
currentPath: [
...refs.currentPath,
"allOf",
a ? "1" : "0"
]
});
return {
allOf: [
a,
b
].filter((x)=>void 0 !== x)
};
};
function parsePromiseDef(def, refs) {
return parseDef(def.type._def, refs);
}
function parseSetDef(def, refs) {
const items = parseDef(def.valueType._def, {
...refs,
currentPath: [
...refs.currentPath,
"items"
]
});
const schema = {
type: "array",
uniqueItems: true,
items
};
if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
return schema;
}
function parseTupleDef(def, refs) {
if (def.rest) return {
type: "array",
minItems: def.items.length,
items: def.items.map((x, i)=>parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x)=>void 0 === x ? acc : [
...acc,
x
], []),
additionalItems: parseDef(def.rest._def, {
...refs,
currentPath: [
...refs.currentPath,
"additionalItems"
]
})
};
return {
type: "array",
minItems: def.items.length,
maxItems: def.items.length,
items: def.items.map((x, i)=>parseDef(x._def, {
...refs,
currentPath: [
...refs.currentPath,
"items",
`${i}`
]
})).reduce((acc, x)=>void 0 === x ? acc : [
...acc,
x
], [])
};
}
function parseUndefinedDef(refs) {
return {
not: parseAnyDef(refs)
};
}
function parseUnknownDef(refs) {
return parseAnyDef(refs);
}
const parseReadonlyDef = (def, refs)=>parseDef(def.innerType._def, refs);
const selectParser = (def, typeName, refs)=>{
switch(typeName){
case types_ZodFirstPartyTypeKind.ZodString:
return parseStringDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodNumber:
return parseNumberDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodObject:
return parseObjectDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodBigInt:
return parseBigintDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodBoolean:
return parseBooleanDef();
case types_ZodFirstPartyTypeKind.ZodDate:
return parseDateDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodUndefined:
return parseUndefinedDef(refs);
case types_ZodFirstPartyTypeKind.ZodNull:
return parseNullDef(refs);
case types_ZodFirstPartyTypeKind.ZodArray:
return parseArrayDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodUnion:
case types_ZodFirstPartyTypeKind.ZodDiscriminatedUnion:
return parseUnionDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodIntersection:
return parseIntersectionDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodTuple:
return parseTupleDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodRecord:
return parseRecordDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodLiteral:
return parseLiteralDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodEnum:
return parseEnumDef(def);
case types_ZodFirstPartyTypeKind.ZodNativeEnum:
return parseNativeEnumDef(def);
case types_ZodFirstPartyTypeKind.ZodNullable:
return parseNullableDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodOptional:
return parseOptionalDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodMap:
return parseMapDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodSet:
return parseSetDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodLazy:
return ()=>def.getter()._def;
case types_ZodFirstPartyTypeKind.ZodPromise:
return parsePromiseDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodNaN:
case types_ZodFirstPartyTypeKind.ZodNever:
return parseNeverDef(refs);
case types_ZodFirstPartyTypeKind.ZodEffects:
return parseEffectsDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodAny:
return parseAnyDef(refs);
case types_ZodFirstPartyTypeKind.ZodUnknown:
return parseUnknownDef(refs);
case types_ZodFirstPartyTypeKind.ZodDefault:
return parseDefaultDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodBranded:
return parseBrandedDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodReadonly:
return parseReadonlyDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodCatch:
return parseCatchDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodPipeline:
return parsePipelineDef(def, refs);
case types_ZodFirstPartyTypeKind.ZodFunction:
case types_ZodFirstPartyTypeKind.ZodVoid:
case types_ZodFirstPartyTypeKind.ZodSymbol:
return;
default:
return ((_)=>void 0)(0);
}
};
function parseDef(def, refs, forceResolution = false) {
const seenItem = refs.seen.get(def);
if (refs.override) {
const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
if (overrideResult !== ignoreOverride) return overrideResult;
}
if (seenItem && !forceResolution) {
const seenSchema = get$ref(seenItem, refs);
if (void 0 !== seenSchema) return seenSchema;
}
const newItem = {
def,
path: refs.currentPath,
jsonSchema: void 0
};
refs.seen.set(def, newItem);
const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
const jsonSchema = "function" == typeof jsonSchemaOrGetter ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
if (jsonSchema) addMeta(def, refs, jsonSchema);
if (refs.postProcess) {
const postProcessResult = refs.postProcess(jsonSchema, def, refs);
newItem.jsonSchema = jsonSchema;
return postProcessResult;
}
newItem.jsonSchema = jsonSchema;
return jsonSchema;
}
const get$ref = (item, refs)=>{
switch(refs.$refStrategy){
case "root":
return {
$ref: item.path.join("/")
};
case "relative":
return {
$ref: getRelativePath(refs.currentPath, item.path)
};
case "none":
case "seen":
if (item.path.length < refs.currentPath.length && item.path.every((value, index)=>refs.currentPath[index] === value)) {
console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
return parseAnyDef(refs);
}
return "seen" === refs.$refStrategy ? parseAnyDef(refs) : void 0;
}
};
const addMeta = (def, refs, jsonSchema)=>{
if (def.description) {
jsonSchema.description = def.description;
if (refs.markdownDescription) jsonSchema.markdownDescription = def.description;
}
return jsonSchema;
};
const zodToJsonSchema_zodToJsonSchema = (schema, options)=>{
const refs = getRefs(options);
let definitions = "object" == typeof options && options.definitions ? Object.entries(options.definitions).reduce((acc, [name, schema])=>({
...acc,
[name]: parseDef(schema._def, {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name
]
}, true) ?? parseAnyDef(refs)
}), {}) : void 0;
const name = "string" == typeof options ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
const main = parseDef(schema._def, void 0 === name ? refs : {
...refs,
currentPath: [
...refs.basePath,
refs.definitionPath,
name
]
}, false) ?? parseAnyDef(refs);
const title = "object" == typeof options && void 0 !== options.name && "title" === options.nameStrategy ? options.name : void 0;
if (void 0 !== title) main.title = title;
if (refs.flags.hasReferencedOpenAiAnyType) {
if (!definitions) definitions = {};
if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = {
type: [
"string",
"number",
"integer",
"boolean",
"array",
"null"
],
items: {
$ref: "relative" === refs.$refStrategy ? "1" : [
...refs.basePath,
refs.definitionPath,
refs.openAiAnyTypeName
].join("/")
}
};
}
const combined = void 0 === name ? definitions ? {
...main,
[refs.definitionPath]: definitions
} : main : {
$ref: [
..."relative" === refs.$refStrategy ? [] : refs.basePath,
refs.definitionPath,
name
].join("/"),
[refs.definitionPath]: {
...definitions,
[name]: main
}
};
if ("jsonSchema7" === refs.target) combined.$schema = "http://json-schema.org/draft-07/schema#";
else if ("jsonSchema2019-09" === refs.target || "openAi" === refs.target) combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
if ("openAi" === refs.target && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
return combined;
};
var completable_McpZodTypeKind;
(function(McpZodTypeKind) {
McpZodTypeKind["Completable"] = "McpCompletable";
})(completable_McpZodTypeKind || (completable_McpZodTypeKind = {}));
class Completable extends ZodType {
_parse(input) {
const { ctx } = this._processInputParams(input);
const data = ctx.data;
return this._def.type._parse({
data,
path: ctx.path,
parent: ctx
});
}
unwrap() {
return this._def.type;
}
}
Completable.create = (type, params)=>new Completable({
type,
typeName: completable_McpZodTypeKind.Completable,
complete: params.complete,
...completable_processCreateParams(params)
});
function completable_processCreateParams(params) {
if (!params) return {};
const { errorMap, invalid_type_error, required_error, description } = params;
if (errorMap && (invalid_type_error || required_error)) throw new Error('Can\'t use "invalid_type_error" or "required_error" in conjunction with custom error map.');
if (errorMap) return {
errorMap: errorMap,
description
};
const customMap = (iss, ctx)=>{
var _a, _b;
const { message } = params;
if ("invalid_enum_value" === iss.code) return {
message: null != message ? message : ctx.defaultError
};
if (void 0 === ctx.data) return {
message: null != (_a = null != message ? message : required_error) ? _a : ctx.defaultError
};
if ("invalid_type" !== iss.code) return {
message: ctx.defaultError
};
return {
message: null != (_b = null != message ? message : invalid_type_error) ? _b : ctx.defaultError
};
};
return {
errorMap: customMap,
description
};
}
class McpServer {
constructor(serverInfo, options){
this._registeredResources = {};
this._registeredResourceTemplates = {};
this._registeredTools = {};
this._registeredPrompts = {};
this._toolHandlersInitialized = false;
this._completionHandlerInitialized = false;
this._resourceHandlersInitialized = false;
this._promptHandlersInitialized = false;
this.server = new Server(serverInfo, options);
}
async connect(transport) {
return await this.server.connect(transport);
}
async close() {
await this.server.close();
}
setToolRequestHandlers() {
if (this._toolHandlersInitialized) return;
this.server.assertCanSetRequestHandler(ListToolsRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(CallToolRequestSchema.shape.method.value);
this.server.registerCapabilities({
tools: {
listChanged: true
}
});
this.server.setRequestHandler(ListToolsRequestSchema, ()=>({
tools: Object.entries(this._registeredTools).filter(([, tool])=>tool.enabled).map(([name, tool])=>{
const toolDefinition = {
name,
title: tool.title,
description: tool.description,
inputSchema: tool.inputSchema ? zodToJsonSchema_zodToJsonSchema(tool.inputSchema, {
strictUnions: true
}) : EMPTY_OBJECT_JSON_SCHEMA,
annotations: tool.annotations
};
if (tool.outputSchema) toolDefinition.outputSchema = zodToJsonSchema_zodToJsonSchema(tool.outputSchema, {
strictUnions: true
});
return toolDefinition;
})
}));
this.server.setRequestHandler(CallToolRequestSchema, async (request, extra)=>{
const tool = this._registeredTools[request.params.name];
if (!tool) throw new McpError(types_ErrorCode.InvalidParams, `Tool ${request.params.name} not found`);
if (!tool.enabled) throw new McpError(types_ErrorCode.InvalidParams, `Tool ${request.params.name} disabled`);
let result;
if (tool.inputSchema) {
const parseResult = await tool.inputSchema.safeParseAsync(request.params.arguments);
if (!parseResult.success) throw new McpError(types_ErrorCode.InvalidParams, `Invalid arguments for tool ${request.params.name}: ${parseResult.error.message}`);
const args = parseResult.data;
const cb = tool.callback;
try {
result = await Promise.resolve(cb(args, extra));
} catch (error) {
result = {
content: [
{
type: "text",
text: error instanceof Error ? error.message : String(error)
}
],
isError: true
};
}
} else {
const cb = tool.callback;
try {
result = await Promise.resolve(cb(extra));
} catch (error) {
result = {
content: [
{
type: "text",
text: error instanceof Error ? error.message : String(error)
}
],
isError: true
};
}
}
if (tool.outputSchema && !result.isError) {
if (!result.structuredContent) throw new McpError(types_ErrorCode.InvalidParams, `Tool ${request.params.name} has an output schema but no structured content was provided`);
const parseResult = await tool.outputSchema.safeParseAsync(result.structuredContent);
if (!parseResult.success) throw new McpError(types_ErrorCode.InvalidParams, `Invalid structured content for tool ${request.params.name}: ${parseResult.error.message}`);
}
return result;
});
this._toolHandlersInitialized = true;
}
setCompletionRequestHandler() {
if (this._completionHandlerInitialized) return;
this.server.assertCanSetRequestHandler(CompleteRequestSchema.shape.method.value);
this.server.registerCapabilities({
completions: {}
});
this.server.setRequestHandler(CompleteRequestSchema, async (request)=>{
switch(request.params.ref.type){
case "ref/prompt":
return this.handlePromptCompletion(request, request.params.ref);
case "ref/resource":
return this.handleResourceCompletion(request, request.params.ref);
default:
throw new McpError(types_ErrorCode.InvalidParams, `Invalid completion reference: ${request.params.ref}`);
}
});
this._completionHandlerInitialized = true;
}
async handlePromptCompletion(request, ref) {
const prompt = this._registeredPrompts[ref.name];
if (!prompt) throw new McpError(types_ErrorCode.InvalidParams, `Prompt ${ref.name} not found`);
if (!prompt.enabled) throw new McpError(types_ErrorCode.InvalidParams, `Prompt ${ref.name} disabled`);
if (!prompt.argsSchema) return EMPTY_COMPLETION_RESULT;
const field = prompt.argsSchema.shape[request.params.argument.name];
if (!(field instanceof Completable)) return EMPTY_COMPLETION_RESULT;
const def = field._def;
const suggestions = await def.complete(request.params.argument.value, request.params.context);
return createCompletionResult(suggestions);
}
async handleResourceCompletion(request, ref) {
const template = Object.values(this._registeredResourceTemplates).find((t)=>t.resourceTemplate.uriTemplate.toString() === ref.uri);
if (!template) {
if (this._registeredResources[ref.uri]) return EMPTY_COMPLETION_RESULT;
throw new McpError(types_ErrorCode.InvalidParams, `Resource template ${request.params.ref.uri} not found`);
}
const completer = template.resourceTemplate.completeCallback(request.params.argument.name);
if (!completer) return EMPTY_COMPLETION_RESULT;
const suggestions = await completer(request.params.argument.value, request.params.context);
return createCompletionResult(suggestions);
}
setResourceRequestHandlers() {
if (this._resourceHandlersInitialized) return;
this.server.assertCanSetRequestHandler(ListResourcesRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(ListResourceTemplatesRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(ReadResourceRequestSchema.shape.method.value);
this.server.registerCapabilities({
resources: {
listChanged: true
}
});
this.server.setRequestHandler(ListResourcesRequestSchema, async (request, extra)=>{
const resources = Object.entries(this._registeredResources).filter(([_, resource])=>resource.enabled).map(([uri, resource])=>({
uri,
name: resource.name,
...resource.metadata
}));
const templateResources = [];
for (const template of Object.values(this._registeredResourceTemplates)){
if (!template.resourceTemplate.listCallback) continue;
const result = await template.resourceTemplate.listCallback(extra);
for (const resource of result.resources)templateResources.push({
...template.metadata,
...resource
});
}
return {
resources: [
...resources,
...templateResources
]
};
});
this.server.setRequestHandler(ListResourceTemplatesRequestSchema, async ()=>{
const resourceTemplates = Object.entries(this._registeredResourceTemplates).map(([name, template])=>({
name,
uriTemplate: template.resourceTemplate.uriTemplate.toString(),
...template.metadata
}));
return {
resourceTemplates
};
});
this.server.setRequestHandler(ReadResourceRequestSchema, async (request, extra)=>{
const uri = new URL(request.params.uri);
const resource = this._registeredResources[uri.toString()];
if (resource) {
if (!resource.enabled) throw new McpError(types_ErrorCode.InvalidParams, `Resource ${uri} disabled`);
return resource.readCallback(uri, extra);
}
for (const template of Object.values(this._registeredResourceTemplates)){
const variables = template.resourceTemplate.uriTemplate.match(uri.toString());
if (variables) return template.readCallback(uri, variables, extra);
}
throw new McpError(types_ErrorCode.InvalidParams, `Resource ${uri} not found`);
});
this.setCompletionRequestHandler();
this._resourceHandlersInitialized = true;
}
setPromptRequestHandlers() {
if (this._promptHandlersInitialized) return;
this.server.assertCanSetRequestHandler(ListPromptsRequestSchema.shape.method.value);
this.server.assertCanSetRequestHandler(GetPromptRequestSchema.shape.method.value);
this.server.registerCapabilities({
prompts: {
listChanged: true
}
});
this.server.setRequestHandler(ListPromptsRequestSchema, ()=>({
prompts: Object.entries(this._registeredPrompts).filter(([, prompt])=>prompt.enabled).map(([name, prompt])=>({
name,
title: prompt.title,
description: prompt.description,
arguments: prompt.argsSchema ? promptArgumentsFromSchema(prompt.argsSchema) : void 0
}))
}));
this.server.setRequestHandler(GetPromptRequestSchema, async (request, extra)=>{
const prompt = this._registeredPrompts[request.params.name];
if (!prompt) throw new McpError(types_ErrorCode.InvalidParams, `Prompt ${request.params.name} not found`);
if (!prompt.enabled) throw new McpError(types_ErrorCode.InvalidParams, `Prompt ${request.params.name} disabled`);
if (prompt.argsSchema) {
const parseResult = await prompt.argsSchema.safeParseAsync(request.params.arguments);
if (!parseResult.success) throw new McpError(types_ErrorCode.InvalidParams, `Invalid arguments for prompt ${request.params.name}: ${parseResult.error.message}`);
const args = parseResult.data;
const cb = prompt.callback;
return await Promise.resolve(cb(args, extra));
}
{
const cb = prompt.callback;
return await Promise.resolve(cb(extra));
}
});
this.setCompletionRequestHandler();
this._promptHandlersInitialized = true;
}
resource(name, uriOrTemplate, ...rest) {
let metadata;
if ("object" == typeof rest[0]) metadata = rest.shift();
const readCallback = rest[0];
if ("string" == typeof uriOrTemplate) {
if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
const registeredResource = this._createRegisteredResource(name, void 0, uriOrTemplate, metadata, readCallback);
this.setResourceRequestHandlers();
this.sendResourceListChanged();
return registeredResource;
}
{
if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, void 0, uriOrTemplate, metadata, readCallback);
this.setResourceRequestHandlers();
this.sendResourceListChanged();
return registeredResourceTemplate;
}
}
registerResource(name, uriOrTemplate, config, readCallback) {
if ("string" == typeof uriOrTemplate) {
if (this._registeredResources[uriOrTemplate]) throw new Error(`Resource ${uriOrTemplate} is already registered`);
const registeredResource = this._createRegisteredResource(name, config.title, uriOrTemplate, config, readCallback);
this.setResourceRequestHandlers();
this.sendResourceListChanged();
return registeredResource;
}
{
if (this._registeredResourceTemplates[name]) throw new Error(`Resource template ${name} is already registered`);
const registeredResourceTemplate = this._createRegisteredResourceTemplate(name, config.title, uriOrTemplate, config, readCallback);
this.setResourceRequestHandlers();
this.sendResourceListChanged();
return registeredResourceTemplate;
}
}
_createRegisteredResource(name, title, uri, metadata, readCallback) {
const registeredResource = {
name,
title,
metadata,
readCallback,
enabled: true,
disable: ()=>registeredResource.update({
enabled: false
}),
enable: ()=>registeredResource.update({
enabled: true
}),
remove: ()=>registeredResource.update({
uri: null
}),
update: (updates)=>{
if (void 0 !== updates.uri && updates.uri !== uri) {
delete this._registeredResources[uri];
if (updates.uri) this._registeredResources[updates.uri] = registeredResource;
}
if (void 0 !== updates.name) registeredResource.name = updates.name;
if (void 0 !== updates.title) registeredResource.title = updates.title;
if (void 0 !== updates.metadata) registeredResource.metadata = updates.metadata;
if (void 0 !== updates.callback) registeredResource.readCallback = updates.callback;
if (void 0 !== updates.enabled) registeredResource.enabled = updates.enabled;
this.sendResourceListChanged();
}
};
this._registeredResources[uri] = registeredResource;
return registeredResource;
}
_createRegisteredResourceTemplate(name, title, template, metadata, readCallback) {
const registeredResourceTemplate = {
resourceTemplate: template,
title,
metadata,
readCallback,
enabled: true,
disable: ()=>registeredResourceTemplate.update({
enabled: false
}),
enable: ()=>registeredResourceTemplate.update({
enabled: true
}),
remove: ()=>registeredResourceTemplate.update({
name: null
}),
update: (updates)=>{
if (void 0 !== updates.name && updates.name !== name) {
delete this._registeredResourceTemplates[name];
if (updates.name) this._registeredResourceTemplates[updates.name] = registeredResourceTemplate;
}
if (void 0 !== updates.title) registeredResourceTemplate.title = updates.title;
if (void 0 !== updates.template) registeredResourceTemplate.resourceTemplate = updates.template;
if (void 0 !== updates.metadata) registeredResourceTemplate.metadata = updates.metadata;
if (void 0 !== updates.callback) registeredResourceTemplate.readCallback = updates.callback;
if (void 0 !== updates.enabled) registeredResourceTemplate.enabled = updates.enabled;
this.sendResourceListChanged();
}
};
this._registeredResourceTemplates[name] = registeredResourceTemplate;
return registeredResourceTemplate;
}
_createRegisteredPrompt(name, title, description, argsSchema, callback) {
const registeredPrompt = {
title,
description,
argsSchema: void 0 === argsSchema ? void 0 : objectType(argsSchema),
callback,
enabled: true,
disable: ()=>registeredPrompt.update({
enabled: false
}),
enable: ()=>registeredPrompt.update({
enabled: true
}),
remove: ()=>registeredPrompt.update({
name: null
}),
update: (updates)=>{
if (void 0 !== updates.name && updates.name !== name) {
delete this._registeredPrompts[name];
if (updates.name) this._registeredPrompts[updates.name] = registeredPrompt;
}
if (void 0 !== updates.title) registeredPrompt.title = updates.title;
if (void 0 !== updates.description) registeredPrompt.description = updates.description;
if (void 0 !== updates.argsSchema) registeredPrompt.argsSchema = objectType(updates.argsSchema);
if (void 0 !== updates.callback) registeredPrompt.callback = updates.callback;
if (void 0 !== updates.enabled) registeredPrompt.enabled = updates.enabled;
this.sendPromptListChanged();
}
};
this._registeredPrompts[name] = registeredPrompt;
return registeredPrompt;
}
_createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, callback) {
const registeredTool = {
title,
description,
inputSchema: void 0 === inputSchema ? void 0 : objectType(inputSchema),
outputSchema: void 0 === outputSchema ? void 0 : objectType(outputSchema),
annotations,
callback,
enabled: true,
disable: ()=>registeredTool.update({
enabled: false
}),
enable: ()=>registeredTool.update({
enabled: true
}),
remove: ()=>registeredTool.update({
name: null
}),
update: (updates)=>{
if (void 0 !== updates.name && updates.name !== name) {
delete this._registeredTools[name];
if (updates.name) this._registeredTools[updates.name] = registeredTool;
}
if (void 0 !== updates.title) registeredTool.title = updates.title;
if (void 0 !== updates.description) registeredTool.description = updates.description;
if (void 0 !== updates.paramsSchema) registeredTool.inputSchema = objectType(updates.paramsSchema);
if (void 0 !== updates.callback) registeredTool.callback = updates.callback;
if (void 0 !== updates.annotations) registeredTool.annotations = updates.annotations;
if (void 0 !== updates.enabled) registeredTool.enabled = updates.enabled;
this.sendToolListChanged();
}
};
this._registeredTools[name] = registeredTool;
this.setToolRequestHandlers();
this.sendToolListChanged();
return registeredTool;
}
tool(name, ...rest) {
if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
let description;
let inputSchema;
let outputSchema;
let annotations;
if ("string" == typeof rest[0]) description = rest.shift();
if (rest.length > 1) {
const firstArg = rest[0];
if (isZodRawShape(firstArg)) {
inputSchema = rest.shift();
if (rest.length > 1 && "object" == typeof rest[0] && null !== rest[0] && !isZodRawShape(rest[0])) annotations = rest.shift();
} else if ("object" == typeof firstArg && null !== firstArg) annotations = rest.shift();
}
const callback = rest[0];
return this._createRegisteredTool(name, void 0, description, inputSchema, outputSchema, annotations, callback);
}
registerTool(name, config, cb) {
if (this._registeredTools[name]) throw new Error(`Tool ${name} is already registered`);
const { title, description, inputSchema, outputSchema, annotations } = config;
return this._createRegisteredTool(name, title, description, inputSchema, outputSchema, annotations, cb);
}
prompt(name, ...rest) {
if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
let description;
if ("string" == typeof rest[0]) description = rest.shift();
let argsSchema;
if (rest.length > 1) argsSchema = rest.shift();
const cb = rest[0];
const registeredPrompt = this._createRegisteredPrompt(name, void 0, description, argsSchema, cb);
this.setPromptRequestHandlers();
this.sendPromptListChanged();
return registeredPrompt;
}
registerPrompt(name, config, cb) {
if (this._registeredPrompts[name]) throw new Error(`Prompt ${name} is already registered`);
const { title, description, argsSchema } = config;
const registeredPrompt = this._createRegisteredPrompt(name, title, description, argsSchema, cb);
this.setPromptRequestHandlers();
this.sendPromptListChanged();
return registeredPrompt;
}
isConnected() {
return void 0 !== this.server.transport;
}
sendResourceListChanged() {
if (this.isConnected()) this.server.sendResourceListChanged();
}
sendToolListChanged() {
if (this.isConnected()) this.server.sendToolListChanged();
}
sendPromptListChanged() {
if (this.isConnected()) this.server.sendPromptListChanged();
}
}
const EMPTY_OBJECT_JSON_SCHEMA = {
type: "object",
properties: {}
};
function isZodRawShape(obj) {
if ("object" != typeof obj || null === obj) return false;
const isEmptyObject = 0 === Object.keys(obj).length;
return isEmptyObject || Object.values(obj).some(isZodTypeLike);
}
function isZodTypeLike(value) {
return null !== value && 'object' == typeof value && 'parse' in value && 'function' == typeof value.parse && 'safeParse' in value && 'function' == typeof value.safeParse;
}
function promptArgumentsFromSchema(schema) {
return Object.entries(schema.shape).map(([name, field])=>({
name,
description: field.description,
required: !field.isOptional()
}));
}
function createCompletionResult(suggestions) {
return {
completion: {
values: suggestions.slice(0, 100),
total: suggestions.length,
hasMore: suggestions.length > 100
}
};
}
const EMPTY_COMPLETION_RESULT = {
completion: {
values: [],
hasMore: false
}
};
var external_node_process_ = __webpack_require__("node:process");
class ReadBuffer {
append(chunk) {
this._buffer = this._buffer ? Buffer.concat([
this._buffer,
chunk
]) : chunk;
}
readMessage() {
if (!this._buffer) return null;
const index = this._buffer.indexOf("\n");
if (-1 === index) return null;
const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, '');
this._buffer = this._buffer.subarray(index + 1);
return deserializeMessage(line);
}
clear() {
this._buffer = void 0;
}
}
function deserializeMessage(line) {
return JSONRPCMessageSchema.parse(JSON.parse(line));
}
function serializeMessage(message) {
return JSON.stringify(message) + "\n";
}
class StdioServerTransport {
constructor(_stdin = external_node_process_.stdin, _stdout = external_node_process_.stdout){
this._stdin = _stdin;
this._stdout = _stdout;
this._readBuffer = new ReadBuffer();
this._started = false;
this._ondata = (chunk)=>{
this._readBuffer.append(chunk);
this.processReadBuffer();
};
this._onerror = (error)=>{
var _a;
null == (_a = this.onerror) || _a.call(this, error);
};
}
async start() {
if (this._started) throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");
this._started = true;
this._stdin.on("data", this._ondata);
this._stdin.on("error", this._onerror);
}
processReadBuffer() {
var _a, _b;
while(true)try {
const message = this._readBuffer.readMessage();
if (null === message) break;
null == (_a = this.onmessage) || _a.call(this, message);
} catch (error) {
null == (_b = this.onerror) || _b.call(this, error);
}
}
async close() {
var _a;
this._stdin.off("data", this._ondata);
this._stdin.off("error", this._onerror);
const remainingDataListeners = this._stdin.listenerCount('data');
if (0 === remainingDataListeners) this._stdin.pause();
this._readBuffer.clear();
null == (_a = this.onclose) || _a.call(this);
}
send(message) {
return new Promise((resolve)=>{
const json = serializeMessage(message);
if (this._stdout.write(json)) resolve();
else this._stdout.once("drain", resolve);
});
}
}
var external_node_fs_ = __webpack_require__("node:fs");
var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_);
var external_node_path_ = __webpack_require__("node:path");
var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_);
var external_node_child_process_ = __webpack_require__("node:child_process");
function debug(...props) {
console.error("[build-my-own]", ...props);
}
function getGithubProjectName(url) {
const splitted = url.split("/");
if (0 === splitted.length) throw new Error("Invalid Github url");
const last = splitted[splitted.length - 1];
if (!last.endsWith(".git")) throw new Error("Invalid Github url, should end with `.git`");
return last.slice(0, -4);
}
async function cloneAndSetupProject(githubUrl) {
debug("[cloneAndSetupProject] starting", githubUrl);
try {
const projectName = getGithubProjectName(githubUrl);
debug(`projectName: ${projectName}`);
const projectDirAbsolutePath = external_node_path_.resolve(projectName);
external_node_fs_.mkdirSync(projectDirAbsolutePath);
const orginalProjectDirAbsolutePath = external_node_path_.resolve(projectName, `${projectName}-original`);
const cloneResult = (0, external_node_child_process_.spawnSync)("git", [
"clone",
githubUrl,
orginalProjectDirAbsolutePath
]);
if (cloneResult.error) throw new Error(`Failed to clone repository: ${cloneResult.error.message}`);
const myOwnProjectDirAbsolutePath = external_node_path_.resolve(projectName, `${projectName}-my-own`);
external_node_fs_.mkdirSync(myOwnProjectDirAbsolutePath);
const from = external_node_path_.resolve(__dirname, "./assets");
const to = projectDirAbsolutePath;
external_node_fs_.cpSync(from, to, {
recursive: true
});
const rulesFiles = getCopiedFilePath(from, to);
return {
success: true,
message: `Successfully cloned and set up project: ${projectName}`,
projectName,
projectPath: projectDirAbsolutePath,
originalPath: orginalProjectDirAbsolutePath,
myOwnPath: myOwnProjectDirAbsolutePath,
rulesFiles
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to clone and setup project: ${errorMessage}`);
}
}
function getCopiedFilePath(sourceDir, targetDir) {
const paths = [];
function traverse(currentDir) {
const entries = external_node_fs_.readdirSync(currentDir, {
withFileTypes: true
});
for (const entry of entries){
const entryPath = external_node_path_.join(currentDir, entry.name);
if (entry.isDirectory()) traverse(entryPath);
else {
const relativePath = external_node_path_.relative(sourceDir, entryPath);
const targetPath = external_node_path_.join(targetDir, relativePath);
paths.push(targetPath);
}
}
}
traverse(sourceDir);
return paths;
}
const server = new McpServer({
name: "build-my-own",
version: package_namespaceObject.i8,
description: "MCP server for build-my-own - AI-powered project learning tool"
}, {
capabilities: {
tools: {}
}
});
server.registerTool("start_to_build_my_own_x", {
description: "Use it when the user says they want to build their own `x`. This will clone github project and setup prompts for AI tools. AI tools then will be able to guide them rebuilding the project from 0 to 1.",
inputSchema: {
github_url: stringType().describe("GitHub repository URL to clone (must end with .git)")
}
}, async ({ github_url })=>{
const result = await cloneAndSetupProject(github_url);
return {
content: [
{
type: "text",
text: `Now the project is successfully setup. Go ahead to guide user to build their own \`x\`! You should check the rules I've setup for you, they are ${JSON.stringify(result.rulesFiles, null, 2)}. Make sure to read the content of the rules file and follow the rules according to who you are! The original project is cloned under ${result.originalPath}, and an empty folder is also created under ${result.myOwnPath}.`
}
]
};
});
async function runMcpServer() {
const transport = new StdioServerTransport();
await server.connect(transport);
debug("Build-my-own MCP server started");
}
const mainCommand = sn({
func: async ({ github })=>{
if (github) cloneAndSetupProject(github);
else await runMcpServer();
},
parameters: {
positional: {
kind: "tuple",
parameters: []
},
flags: {
github: {
kind: "parsed",
brief: "GitHub URL to clone and set up a learning environment",
parse: (x)=>{
const trimmed = x.trim();
if (trimmed.endsWith(".git")) return trimmed;
throw new Error("URL provided should end with `.git`");
},
optional: true
}
}
},
docs: {
brief: package_namespaceObject.WL
}
});
const app = dist_e(mainCommand, {
name: package_namespaceObject.u2,
versionInfo: {
currentVersion: package_namespaceObject.i8
}
});
function buildContext(process1) {
return {
process: process1,
fs: external_node_fs_default(),
path: external_node_path_default()
};
}
(async ()=>{
try {
await Yt(app, process.argv.slice(2), buildContext(process));
} catch (error) {
debug("Error:", error);
throw error;
}
})();
})();
return __webpack_exports__;
})());