");
+ var layer = new Layer(path45, {
+ sensitive: this.caseSensitive,
+ strict: false,
+ end: false
+ }, fn2);
+ layer.route = void 0;
+ this.stack.push(layer);
+ }
+ return this;
+ }, "use");
+ proto.route = /* @__PURE__ */ __name(function route2(path45) {
+ var route3 = new Route(path45);
+ var layer = new Layer(path45, {
+ sensitive: this.caseSensitive,
+ strict: this.strict,
+ end: true
+ }, route3.dispatch.bind(route3));
+ layer.route = route3;
+ this.stack.push(layer);
+ return route3;
+ }, "route");
+ methods.concat("all").forEach(function(method) {
+ proto[method] = function(path45) {
+ var route2 = this.route(path45);
+ route2[method].apply(route2, slice.call(arguments, 1));
+ return this;
+ };
+ });
+ function appendMethods(list, addition) {
+ for (var i = 0; i < addition.length; i++) {
+ var method = addition[i];
+ if (list.indexOf(method) === -1) {
+ list.push(method);
+ }
+ }
+ }
+ __name(appendMethods, "appendMethods");
+ function getPathname(req) {
+ try {
+ return parseUrl(req).pathname;
+ } catch (err) {
+ return void 0;
+ }
+ }
+ __name(getPathname, "getPathname");
+ function getProtohost(url3) {
+ if (typeof url3 !== "string" || url3.length === 0 || url3[0] === "/") {
+ return void 0;
+ }
+ var searchIndex = url3.indexOf("?");
+ var pathLength = searchIndex !== -1 ? searchIndex : url3.length;
+ var fqdnIndex = url3.slice(0, pathLength).indexOf("://");
+ return fqdnIndex !== -1 ? url3.substring(0, url3.indexOf("/", 3 + fqdnIndex)) : void 0;
+ }
+ __name(getProtohost, "getProtohost");
+ function gettype(obj) {
+ var type = typeof obj;
+ if (type !== "object") {
+ return type;
+ }
+ return toString.call(obj).replace(objectRegExp, "$1");
+ }
+ __name(gettype, "gettype");
+ function matchLayer(layer, path45) {
+ try {
+ return layer.match(path45);
+ } catch (err) {
+ return err;
+ }
+ }
+ __name(matchLayer, "matchLayer");
+ function mergeParams(params, parent) {
+ if (typeof parent !== "object" || !parent) {
+ return params;
+ }
+ var obj = mixin3({}, parent);
+ if (!(0 in params) || !(0 in parent)) {
+ return mixin3(obj, params);
+ }
+ var i = 0;
+ var o = 0;
+ while (i in params) {
+ i++;
+ }
+ while (o in parent) {
+ o++;
+ }
+ for (i--; i >= 0; i--) {
+ params[i + o] = params[i];
+ if (i < o) {
+ delete params[i];
+ }
+ }
+ return mixin3(obj, params);
+ }
+ __name(mergeParams, "mergeParams");
+ function restore(fn2, obj) {
+ var props = new Array(arguments.length - 2);
+ var vals = new Array(arguments.length - 2);
+ for (var i = 0; i < props.length; i++) {
+ props[i] = arguments[i + 2];
+ vals[i] = obj[props[i]];
+ }
+ return function() {
+ for (var i2 = 0; i2 < props.length; i2++) {
+ obj[props[i2]] = vals[i2];
+ }
+ return fn2.apply(this, arguments);
+ };
+ }
+ __name(restore, "restore");
+ function sendOptionsResponse(res, options14, next) {
+ try {
+ var body = options14.join(",");
+ res.set("Allow", body);
+ res.send(body);
+ } catch (err) {
+ next(err);
+ }
+ }
+ __name(sendOptionsResponse, "sendOptionsResponse");
+ function wrap2(old, fn2) {
+ return /* @__PURE__ */ __name(function proxy2() {
+ var args = new Array(arguments.length + 1);
+ args[0] = old;
+ for (var i = 0, len = arguments.length; i < len; i++) {
+ args[i + 1] = arguments[i];
+ }
+ fn2.apply(this, args);
+ }, "proxy");
+ }
+ __name(wrap2, "wrap");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/middleware/init.js
+var require_init = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/middleware/init.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var setPrototypeOf = require_setprototypeof();
+ exports2.init = function(app) {
+ return /* @__PURE__ */ __name(function expressInit(req, res, next) {
+ if (app.enabled("x-powered-by"))
+ res.setHeader("X-Powered-By", "Express");
+ req.res = res;
+ res.req = req;
+ req.next = next;
+ setPrototypeOf(req, app.request);
+ setPrototypeOf(res, app.response);
+ res.locals = res.locals || /* @__PURE__ */ Object.create(null);
+ next();
+ }, "expressInit");
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/middleware/query.js
+var require_query = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/middleware/query.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var merge = require_utils_merge();
+ var parseUrl = require_parseurl();
+ var qs = require_lib4();
+ module2.exports = /* @__PURE__ */ __name(function query(options14) {
+ var opts = merge({}, options14);
+ var queryparse = qs.parse;
+ if (typeof options14 === "function") {
+ queryparse = options14;
+ opts = void 0;
+ }
+ if (opts !== void 0 && opts.allowPrototypes === void 0) {
+ opts.allowPrototypes = true;
+ }
+ return /* @__PURE__ */ __name(function query2(req, res, next) {
+ if (!req.query) {
+ var val = parseUrl(req).query;
+ req.query = queryparse(val, opts);
+ }
+ next();
+ }, "query");
+ }, "query");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/view.js
+var require_view = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/view.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var debug = require_src2()("express:view");
+ var path45 = require("path");
+ var fs20 = require("fs");
+ var dirname10 = path45.dirname;
+ var basename6 = path45.basename;
+ var extname4 = path45.extname;
+ var join12 = path45.join;
+ var resolve18 = path45.resolve;
+ module2.exports = View;
+ function View(name, options14) {
+ var opts = options14 || {};
+ this.defaultEngine = opts.defaultEngine;
+ this.ext = extname4(name);
+ this.name = name;
+ this.root = opts.root;
+ if (!this.ext && !this.defaultEngine) {
+ throw new Error("No default engine was specified and no extension was provided.");
+ }
+ var fileName = name;
+ if (!this.ext) {
+ this.ext = this.defaultEngine[0] !== "." ? "." + this.defaultEngine : this.defaultEngine;
+ fileName += this.ext;
+ }
+ if (!opts.engines[this.ext]) {
+ var mod = this.ext.slice(1);
+ debug('require "%s"', mod);
+ var fn2 = require(mod).__express;
+ if (typeof fn2 !== "function") {
+ throw new Error('Module "' + mod + '" does not provide a view engine.');
+ }
+ opts.engines[this.ext] = fn2;
+ }
+ this.engine = opts.engines[this.ext];
+ this.path = this.lookup(fileName);
+ }
+ __name(View, "View");
+ View.prototype.lookup = /* @__PURE__ */ __name(function lookup(name) {
+ var path46;
+ var roots = [].concat(this.root);
+ debug('lookup "%s"', name);
+ for (var i = 0; i < roots.length && !path46; i++) {
+ var root = roots[i];
+ var loc = resolve18(root, name);
+ var dir = dirname10(loc);
+ var file = basename6(loc);
+ path46 = this.resolve(dir, file);
+ }
+ return path46;
+ }, "lookup");
+ View.prototype.render = /* @__PURE__ */ __name(function render7(options14, callback) {
+ debug('render "%s"', this.path);
+ this.engine(this.path, options14, callback);
+ }, "render");
+ View.prototype.resolve = /* @__PURE__ */ __name(function resolve19(dir, file) {
+ var ext = this.ext;
+ var path46 = join12(dir, file);
+ var stat3 = tryStat(path46);
+ if (stat3 && stat3.isFile()) {
+ return path46;
+ }
+ path46 = join12(dir, basename6(file, ext), "index" + ext);
+ stat3 = tryStat(path46);
+ if (stat3 && stat3.isFile()) {
+ return path46;
+ }
+ }, "resolve");
+ function tryStat(path46) {
+ debug('stat "%s"', path46);
+ try {
+ return fs20.statSync(path46);
+ } catch (e2) {
+ return void 0;
+ }
+ }
+ __name(tryStat, "tryStat");
+ }
+});
+
+// ../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js
+var require_safe_buffer = __commonJS({
+ "../../node_modules/.pnpm/safe-buffer@5.2.1/node_modules/safe-buffer/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var buffer = require("buffer");
+ var Buffer3 = buffer.Buffer;
+ function copyProps(src, dst) {
+ for (var key in src) {
+ dst[key] = src[key];
+ }
+ }
+ __name(copyProps, "copyProps");
+ if (Buffer3.from && Buffer3.alloc && Buffer3.allocUnsafe && Buffer3.allocUnsafeSlow) {
+ module2.exports = buffer;
+ } else {
+ copyProps(buffer, exports2);
+ exports2.Buffer = SafeBuffer;
+ }
+ function SafeBuffer(arg, encodingOrOffset, length) {
+ return Buffer3(arg, encodingOrOffset, length);
+ }
+ __name(SafeBuffer, "SafeBuffer");
+ SafeBuffer.prototype = Object.create(Buffer3.prototype);
+ copyProps(Buffer3, SafeBuffer);
+ SafeBuffer.from = function(arg, encodingOrOffset, length) {
+ if (typeof arg === "number") {
+ throw new TypeError("Argument must not be a number");
+ }
+ return Buffer3(arg, encodingOrOffset, length);
+ };
+ SafeBuffer.alloc = function(size, fill, encoding) {
+ if (typeof size !== "number") {
+ throw new TypeError("Argument must be a number");
+ }
+ var buf = Buffer3(size);
+ if (fill !== void 0) {
+ if (typeof encoding === "string") {
+ buf.fill(fill, encoding);
+ } else {
+ buf.fill(fill);
+ }
+ } else {
+ buf.fill(0);
+ }
+ return buf;
+ };
+ SafeBuffer.allocUnsafe = function(size) {
+ if (typeof size !== "number") {
+ throw new TypeError("Argument must be a number");
+ }
+ return Buffer3(size);
+ };
+ SafeBuffer.allocUnsafeSlow = function(size) {
+ if (typeof size !== "number") {
+ throw new TypeError("Argument must be a number");
+ }
+ return buffer.SlowBuffer(size);
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/content-disposition@0.5.4/node_modules/content-disposition/index.js
+var require_content_disposition = __commonJS({
+ "../../node_modules/.pnpm/content-disposition@0.5.4/node_modules/content-disposition/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = contentDisposition;
+ module2.exports.parse = parse4;
+ var basename6 = require("path").basename;
+ var Buffer3 = require_safe_buffer().Buffer;
+ var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g;
+ var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/;
+ var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g;
+ var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g;
+ var QESC_REGEXP = /\\([\u0000-\u007f])/g;
+ var QUOTE_REGEXP = /([\\"])/g;
+ var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g;
+ var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/;
+ var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/;
+ var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/;
+ var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/;
+ function contentDisposition(filename, options14) {
+ var opts = options14 || {};
+ var type = opts.type || "attachment";
+ var params = createparams(filename, opts.fallback);
+ return format8(new ContentDisposition(type, params));
+ }
+ __name(contentDisposition, "contentDisposition");
+ function createparams(filename, fallback) {
+ if (filename === void 0) {
+ return;
+ }
+ var params = {};
+ if (typeof filename !== "string") {
+ throw new TypeError("filename must be a string");
+ }
+ if (fallback === void 0) {
+ fallback = true;
+ }
+ if (typeof fallback !== "string" && typeof fallback !== "boolean") {
+ throw new TypeError("fallback must be a string or boolean");
+ }
+ if (typeof fallback === "string" && NON_LATIN1_REGEXP.test(fallback)) {
+ throw new TypeError("fallback must be ISO-8859-1 string");
+ }
+ var name = basename6(filename);
+ var isQuotedString = TEXT_REGEXP.test(name);
+ var fallbackName = typeof fallback !== "string" ? fallback && getlatin1(name) : basename6(fallback);
+ var hasFallback = typeof fallbackName === "string" && fallbackName !== name;
+ if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) {
+ params["filename*"] = name;
+ }
+ if (isQuotedString || hasFallback) {
+ params.filename = hasFallback ? fallbackName : name;
+ }
+ return params;
+ }
+ __name(createparams, "createparams");
+ function format8(obj) {
+ var parameters = obj.parameters;
+ var type = obj.type;
+ if (!type || typeof type !== "string" || !TOKEN_REGEXP.test(type)) {
+ throw new TypeError("invalid type");
+ }
+ var string = String(type).toLowerCase();
+ if (parameters && typeof parameters === "object") {
+ var param;
+ var params = Object.keys(parameters).sort();
+ for (var i = 0; i < params.length; i++) {
+ param = params[i];
+ var val = param.substr(-1) === "*" ? ustring(parameters[param]) : qstring(parameters[param]);
+ string += "; " + param + "=" + val;
+ }
+ }
+ return string;
+ }
+ __name(format8, "format");
+ function decodefield(str) {
+ var match = EXT_VALUE_REGEXP.exec(str);
+ if (!match) {
+ throw new TypeError("invalid extended field value");
+ }
+ var charset = match[1].toLowerCase();
+ var encoded = match[2];
+ var value;
+ var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode);
+ switch (charset) {
+ case "iso-8859-1":
+ value = getlatin1(binary);
+ break;
+ case "utf-8":
+ value = Buffer3.from(binary, "binary").toString("utf8");
+ break;
+ default:
+ throw new TypeError("unsupported charset in extended field");
+ }
+ return value;
+ }
+ __name(decodefield, "decodefield");
+ function getlatin1(val) {
+ return String(val).replace(NON_LATIN1_REGEXP, "?");
+ }
+ __name(getlatin1, "getlatin1");
+ function parse4(string) {
+ if (!string || typeof string !== "string") {
+ throw new TypeError("argument string is required");
+ }
+ var match = DISPOSITION_TYPE_REGEXP.exec(string);
+ if (!match) {
+ throw new TypeError("invalid type format");
+ }
+ var index = match[0].length;
+ var type = match[1].toLowerCase();
+ var key;
+ var names = [];
+ var params = {};
+ var value;
+ index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ";" ? index - 1 : index;
+ while (match = PARAM_REGEXP.exec(string)) {
+ if (match.index !== index) {
+ throw new TypeError("invalid parameter format");
+ }
+ index += match[0].length;
+ key = match[1].toLowerCase();
+ value = match[2];
+ if (names.indexOf(key) !== -1) {
+ throw new TypeError("invalid duplicate parameter");
+ }
+ names.push(key);
+ if (key.indexOf("*") + 1 === key.length) {
+ key = key.slice(0, -1);
+ value = decodefield(value);
+ params[key] = value;
+ continue;
+ }
+ if (typeof params[key] === "string") {
+ continue;
+ }
+ if (value[0] === '"') {
+ value = value.substr(1, value.length - 2).replace(QESC_REGEXP, "$1");
+ }
+ params[key] = value;
+ }
+ if (index !== -1 && index !== string.length) {
+ throw new TypeError("invalid parameter format");
+ }
+ return new ContentDisposition(type, params);
+ }
+ __name(parse4, "parse");
+ function pdecode(str, hex) {
+ return String.fromCharCode(parseInt(hex, 16));
+ }
+ __name(pdecode, "pdecode");
+ function pencode(char) {
+ return "%" + String(char).charCodeAt(0).toString(16).toUpperCase();
+ }
+ __name(pencode, "pencode");
+ function qstring(val) {
+ var str = String(val);
+ return '"' + str.replace(QUOTE_REGEXP, "\\$1") + '"';
+ }
+ __name(qstring, "qstring");
+ function ustring(val) {
+ var str = String(val);
+ var encoded = encodeURIComponent(str).replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode);
+ return "UTF-8''" + encoded;
+ }
+ __name(ustring, "ustring");
+ function ContentDisposition(type, parameters) {
+ this.type = type;
+ this.parameters = parameters;
+ }
+ __name(ContentDisposition, "ContentDisposition");
+ }
+});
+
+// ../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js
+var require_etag = __commonJS({
+ "../../node_modules/.pnpm/etag@1.8.1/node_modules/etag/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = etag;
+ var crypto6 = require("crypto");
+ var Stats = require("fs").Stats;
+ var toString = Object.prototype.toString;
+ function entitytag(entity) {
+ if (entity.length === 0) {
+ return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"';
+ }
+ var hash = crypto6.createHash("sha1").update(entity, "utf8").digest("base64").substring(0, 27);
+ var len = typeof entity === "string" ? Buffer.byteLength(entity, "utf8") : entity.length;
+ return '"' + len.toString(16) + "-" + hash + '"';
+ }
+ __name(entitytag, "entitytag");
+ function etag(entity, options14) {
+ if (entity == null) {
+ throw new TypeError("argument entity is required");
+ }
+ var isStats = isstats(entity);
+ var weak = options14 && typeof options14.weak === "boolean" ? options14.weak : isStats;
+ if (!isStats && typeof entity !== "string" && !Buffer.isBuffer(entity)) {
+ throw new TypeError("argument entity must be string, Buffer, or fs.Stats");
+ }
+ var tag = isStats ? stattag(entity) : entitytag(entity);
+ return weak ? "W/" + tag : tag;
+ }
+ __name(etag, "etag");
+ function isstats(obj) {
+ if (typeof Stats === "function" && obj instanceof Stats) {
+ return true;
+ }
+ return obj && typeof obj === "object" && "ctime" in obj && toString.call(obj.ctime) === "[object Date]" && "mtime" in obj && toString.call(obj.mtime) === "[object Date]" && "ino" in obj && typeof obj.ino === "number" && "size" in obj && typeof obj.size === "number";
+ }
+ __name(isstats, "isstats");
+ function stattag(stat3) {
+ var mtime = stat3.mtime.getTime().toString(16);
+ var size = stat3.size.toString(16);
+ return '"' + size + "-" + mtime + '"';
+ }
+ __name(stattag, "stattag");
+ }
+});
+
+// ../../node_modules/.pnpm/fresh@0.5.2/node_modules/fresh/index.js
+var require_fresh = __commonJS({
+ "../../node_modules/.pnpm/fresh@0.5.2/node_modules/fresh/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/;
+ module2.exports = fresh;
+ function fresh(reqHeaders, resHeaders) {
+ var modifiedSince = reqHeaders["if-modified-since"];
+ var noneMatch = reqHeaders["if-none-match"];
+ if (!modifiedSince && !noneMatch) {
+ return false;
+ }
+ var cacheControl = reqHeaders["cache-control"];
+ if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) {
+ return false;
+ }
+ if (noneMatch && noneMatch !== "*") {
+ var etag = resHeaders["etag"];
+ if (!etag) {
+ return false;
+ }
+ var etagStale = true;
+ var matches = parseTokenList(noneMatch);
+ for (var i = 0; i < matches.length; i++) {
+ var match = matches[i];
+ if (match === etag || match === "W/" + etag || "W/" + match === etag) {
+ etagStale = false;
+ break;
+ }
+ }
+ if (etagStale) {
+ return false;
+ }
+ }
+ if (modifiedSince) {
+ var lastModified = resHeaders["last-modified"];
+ var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince));
+ if (modifiedStale) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(fresh, "fresh");
+ function parseHttpDate(date) {
+ var timestamp = date && Date.parse(date);
+ return typeof timestamp === "number" ? timestamp : NaN;
+ }
+ __name(parseHttpDate, "parseHttpDate");
+ function parseTokenList(str) {
+ var end = 0;
+ var list = [];
+ var start = 0;
+ for (var i = 0, len = str.length; i < len; i++) {
+ switch (str.charCodeAt(i)) {
+ case 32:
+ if (start === end) {
+ start = end = i + 1;
+ }
+ break;
+ case 44:
+ list.push(str.substring(start, end));
+ start = end = i + 1;
+ break;
+ default:
+ end = i + 1;
+ break;
+ }
+ }
+ list.push(str.substring(start, end));
+ return list;
+ }
+ __name(parseTokenList, "parseTokenList");
+ }
+});
+
+// ../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/types.json
+var require_types = __commonJS({
+ "../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/types.json"(exports2, module2) {
+ module2.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomsvc+xml": ["atomsvc"], "application/bdoc": ["bdoc"], "application/ccxml+xml": ["ccxml"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["ecma"], "application/emma+xml": ["emma"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/font-tdpfr": ["pfr"], "application/font-woff": [], "application/font-woff2": [], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/prs.cww": ["cww"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": [], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": [], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": [], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": [], "application/x-msdownload": ["com", "bat"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["wmf", "emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": [], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "application/xaml+xml": ["xaml"], "application/xcap-diff+xml": ["xdf"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": [], "audio/adpcm": ["adp"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mp3": [], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/wav": ["wav"], "audio/wave": [], "audio/webm": ["weba"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": [], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": [], "audio/x-wav": [], "audio/xm": ["xm"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/apng": ["apng"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/ief": ["ief"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/ktx": ["ktx"], "image/png": ["png"], "image/prs.btif": ["btif"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/tiff": ["tiff", "tif"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": [], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/webp": ["webp"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": [], "image/x-pcx": ["pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/rfc822": ["eml", "mime"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.vtu": ["vtu"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["x3db", "x3dbz"], "model/x3d+vrml": ["x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/hjson": ["hjson"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/prs.lines.tag": ["dsc"], "text/richtext": ["rtx"], "text/rtf": [], "text/sgml": ["sgml", "sgm"], "text/slim": ["slim", "slm"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/vtt": ["vtt"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": [], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "text/xml": [], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/jpeg": ["jpgv"], "video/jpm": ["jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/webm": ["webm"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] };
+ }
+});
+
+// ../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js
+var require_mime = __commonJS({
+ "../../node_modules/.pnpm/mime@1.6.0/node_modules/mime/mime.js"(exports2, module2) {
+ init_import_meta_url();
+ var path45 = require("path");
+ var fs20 = require("fs");
+ function Mime() {
+ this.types = /* @__PURE__ */ Object.create(null);
+ this.extensions = /* @__PURE__ */ Object.create(null);
+ }
+ __name(Mime, "Mime");
+ Mime.prototype.define = function(map) {
+ for (var type in map) {
+ var exts = map[type];
+ for (var i = 0; i < exts.length; i++) {
+ if (process.env.DEBUG_MIME && this.types[exts[i]]) {
+ console.warn((this._loading || "define()").replace(/.*\//, ""), 'changes "' + exts[i] + '" extension type from ' + this.types[exts[i]] + " to " + type);
+ }
+ this.types[exts[i]] = type;
+ }
+ if (!this.extensions[type]) {
+ this.extensions[type] = exts[0];
+ }
+ }
+ };
+ Mime.prototype.load = function(file) {
+ this._loading = file;
+ var map = {}, content = fs20.readFileSync(file, "ascii"), lines = content.split(/[\r\n]+/);
+ lines.forEach(function(line) {
+ var fields = line.replace(/\s*#.*|^\s*|\s*$/g, "").split(/\s+/);
+ map[fields.shift()] = fields;
+ });
+ this.define(map);
+ this._loading = null;
+ };
+ Mime.prototype.lookup = function(path46, fallback) {
+ var ext = path46.replace(/^.*[\.\/\\]/, "").toLowerCase();
+ return this.types[ext] || fallback || this.default_type;
+ };
+ Mime.prototype.extension = function(mimeType) {
+ var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
+ return this.extensions[type];
+ };
+ var mime = new Mime();
+ mime.define(require_types());
+ mime.default_type = mime.lookup("bin");
+ mime.Mime = Mime;
+ mime.charsets = {
+ lookup: function(mimeType, fallback) {
+ return /^text\/|^application\/(javascript|json)/.test(mimeType) ? "UTF-8" : fallback;
+ }
+ };
+ module2.exports = mime;
+ }
+});
+
+// ../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js
+var require_ms2 = __commonJS({
+ "../../node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var s = 1e3;
+ var m = s * 60;
+ var h = m * 60;
+ var d = h * 24;
+ var w = d * 7;
+ var y = d * 365.25;
+ module2.exports = function(val, options14) {
+ options14 = options14 || {};
+ var type = typeof val;
+ if (type === "string" && val.length > 0) {
+ return parse4(val);
+ } else if (type === "number" && isFinite(val)) {
+ return options14.long ? fmtLong(val) : fmtShort(val);
+ }
+ throw new Error(
+ "val is not a non-empty string or a valid number. val=" + JSON.stringify(val)
+ );
+ };
+ function parse4(str) {
+ str = String(str);
+ if (str.length > 100) {
+ return;
+ }
+ var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
+ str
+ );
+ if (!match) {
+ return;
+ }
+ var n = parseFloat(match[1]);
+ var type = (match[2] || "ms").toLowerCase();
+ switch (type) {
+ case "years":
+ case "year":
+ case "yrs":
+ case "yr":
+ case "y":
+ return n * y;
+ case "weeks":
+ case "week":
+ case "w":
+ return n * w;
+ case "days":
+ case "day":
+ case "d":
+ return n * d;
+ case "hours":
+ case "hour":
+ case "hrs":
+ case "hr":
+ case "h":
+ return n * h;
+ case "minutes":
+ case "minute":
+ case "mins":
+ case "min":
+ case "m":
+ return n * m;
+ case "seconds":
+ case "second":
+ case "secs":
+ case "sec":
+ case "s":
+ return n * s;
+ case "milliseconds":
+ case "millisecond":
+ case "msecs":
+ case "msec":
+ case "ms":
+ return n;
+ default:
+ return void 0;
+ }
+ }
+ __name(parse4, "parse");
+ function fmtShort(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return Math.round(ms / d) + "d";
+ }
+ if (msAbs >= h) {
+ return Math.round(ms / h) + "h";
+ }
+ if (msAbs >= m) {
+ return Math.round(ms / m) + "m";
+ }
+ if (msAbs >= s) {
+ return Math.round(ms / s) + "s";
+ }
+ return ms + "ms";
+ }
+ __name(fmtShort, "fmtShort");
+ function fmtLong(ms) {
+ var msAbs = Math.abs(ms);
+ if (msAbs >= d) {
+ return plural(ms, msAbs, d, "day");
+ }
+ if (msAbs >= h) {
+ return plural(ms, msAbs, h, "hour");
+ }
+ if (msAbs >= m) {
+ return plural(ms, msAbs, m, "minute");
+ }
+ if (msAbs >= s) {
+ return plural(ms, msAbs, s, "second");
+ }
+ return ms + " ms";
+ }
+ __name(fmtLong, "fmtLong");
+ function plural(ms, msAbs, n, name) {
+ var isPlural = msAbs >= n * 1.5;
+ return Math.round(ms / n) + " " + name + (isPlural ? "s" : "");
+ }
+ __name(plural, "plural");
+ }
+});
+
+// ../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js
+var require_range_parser = __commonJS({
+ "../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = rangeParser;
+ function rangeParser(size, str, options14) {
+ if (typeof str !== "string") {
+ throw new TypeError("argument str must be a string");
+ }
+ var index = str.indexOf("=");
+ if (index === -1) {
+ return -2;
+ }
+ var arr = str.slice(index + 1).split(",");
+ var ranges = [];
+ ranges.type = str.slice(0, index);
+ for (var i = 0; i < arr.length; i++) {
+ var range = arr[i].split("-");
+ var start = parseInt(range[0], 10);
+ var end = parseInt(range[1], 10);
+ if (isNaN(start)) {
+ start = size - end;
+ end = size - 1;
+ } else if (isNaN(end)) {
+ end = size - 1;
+ }
+ if (end > size - 1) {
+ end = size - 1;
+ }
+ if (isNaN(start) || isNaN(end) || start > end || start < 0) {
+ continue;
+ }
+ ranges.push({
+ start,
+ end
+ });
+ }
+ if (ranges.length < 1) {
+ return -1;
+ }
+ return options14 && options14.combine ? combineRanges(ranges) : ranges;
+ }
+ __name(rangeParser, "rangeParser");
+ function combineRanges(ranges) {
+ var ordered = ranges.map(mapWithIndex).sort(sortByRangeStart);
+ for (var j = 0, i = 1; i < ordered.length; i++) {
+ var range = ordered[i];
+ var current = ordered[j];
+ if (range.start > current.end + 1) {
+ ordered[++j] = range;
+ } else if (range.end > current.end) {
+ current.end = range.end;
+ current.index = Math.min(current.index, range.index);
+ }
+ }
+ ordered.length = j + 1;
+ var combined = ordered.sort(sortByRangeIndex).map(mapWithoutIndex);
+ combined.type = ranges.type;
+ return combined;
+ }
+ __name(combineRanges, "combineRanges");
+ function mapWithIndex(range, index) {
+ return {
+ start: range.start,
+ end: range.end,
+ index
+ };
+ }
+ __name(mapWithIndex, "mapWithIndex");
+ function mapWithoutIndex(range) {
+ return {
+ start: range.start,
+ end: range.end
+ };
+ }
+ __name(mapWithoutIndex, "mapWithoutIndex");
+ function sortByRangeIndex(a, b) {
+ return a.index - b.index;
+ }
+ __name(sortByRangeIndex, "sortByRangeIndex");
+ function sortByRangeStart(a, b) {
+ return a.start - b.start;
+ }
+ __name(sortByRangeStart, "sortByRangeStart");
+ }
+});
+
+// ../../node_modules/.pnpm/send@0.18.0_supports-color@9.2.2/node_modules/send/index.js
+var require_send = __commonJS({
+ "../../node_modules/.pnpm/send@0.18.0_supports-color@9.2.2/node_modules/send/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var createError = require_http_errors();
+ var debug = require_src2()("send");
+ var deprecate = require_depd()("send");
+ var destroy = require_destroy();
+ var encodeUrl = require_encodeurl();
+ var escapeHtml = require_escape_html();
+ var etag = require_etag();
+ var fresh = require_fresh();
+ var fs20 = require("fs");
+ var mime = require_mime();
+ var ms = require_ms2();
+ var onFinished = require_on_finished();
+ var parseRange = require_range_parser();
+ var path45 = require("path");
+ var statuses = require_statuses();
+ var Stream = require("stream");
+ var util3 = require("util");
+ var extname4 = path45.extname;
+ var join12 = path45.join;
+ var normalize2 = path45.normalize;
+ var resolve18 = path45.resolve;
+ var sep2 = path45.sep;
+ var BYTES_RANGE_REGEXP = /^ *bytes=/;
+ var MAX_MAXAGE = 60 * 60 * 24 * 365 * 1e3;
+ var UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
+ module2.exports = send;
+ module2.exports.mime = mime;
+ function send(req, path46, options14) {
+ return new SendStream(req, path46, options14);
+ }
+ __name(send, "send");
+ function SendStream(req, path46, options14) {
+ Stream.call(this);
+ var opts = options14 || {};
+ this.options = opts;
+ this.path = path46;
+ this.req = req;
+ this._acceptRanges = opts.acceptRanges !== void 0 ? Boolean(opts.acceptRanges) : true;
+ this._cacheControl = opts.cacheControl !== void 0 ? Boolean(opts.cacheControl) : true;
+ this._etag = opts.etag !== void 0 ? Boolean(opts.etag) : true;
+ this._dotfiles = opts.dotfiles !== void 0 ? opts.dotfiles : "ignore";
+ if (this._dotfiles !== "ignore" && this._dotfiles !== "allow" && this._dotfiles !== "deny") {
+ throw new TypeError('dotfiles option must be "allow", "deny", or "ignore"');
+ }
+ this._hidden = Boolean(opts.hidden);
+ if (opts.hidden !== void 0) {
+ deprecate("hidden: use dotfiles: '" + (this._hidden ? "allow" : "ignore") + "' instead");
+ }
+ if (opts.dotfiles === void 0) {
+ this._dotfiles = void 0;
+ }
+ this._extensions = opts.extensions !== void 0 ? normalizeList(opts.extensions, "extensions option") : [];
+ this._immutable = opts.immutable !== void 0 ? Boolean(opts.immutable) : false;
+ this._index = opts.index !== void 0 ? normalizeList(opts.index, "index option") : ["index.html"];
+ this._lastModified = opts.lastModified !== void 0 ? Boolean(opts.lastModified) : true;
+ this._maxage = opts.maxAge || opts.maxage;
+ this._maxage = typeof this._maxage === "string" ? ms(this._maxage) : Number(this._maxage);
+ this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0;
+ this._root = opts.root ? resolve18(opts.root) : null;
+ if (!this._root && opts.from) {
+ this.from(opts.from);
+ }
+ }
+ __name(SendStream, "SendStream");
+ util3.inherits(SendStream, Stream);
+ SendStream.prototype.etag = deprecate.function(/* @__PURE__ */ __name(function etag2(val) {
+ this._etag = Boolean(val);
+ debug("etag %s", this._etag);
+ return this;
+ }, "etag"), "send.etag: pass etag as option");
+ SendStream.prototype.hidden = deprecate.function(/* @__PURE__ */ __name(function hidden(val) {
+ this._hidden = Boolean(val);
+ this._dotfiles = void 0;
+ debug("hidden %s", this._hidden);
+ return this;
+ }, "hidden"), "send.hidden: use dotfiles option");
+ SendStream.prototype.index = deprecate.function(/* @__PURE__ */ __name(function index(paths) {
+ var index2 = !paths ? [] : normalizeList(paths, "paths argument");
+ debug("index %o", paths);
+ this._index = index2;
+ return this;
+ }, "index"), "send.index: pass index as option");
+ SendStream.prototype.root = /* @__PURE__ */ __name(function root(path46) {
+ this._root = resolve18(String(path46));
+ debug("root %s", this._root);
+ return this;
+ }, "root");
+ SendStream.prototype.from = deprecate.function(
+ SendStream.prototype.root,
+ "send.from: pass root as option"
+ );
+ SendStream.prototype.root = deprecate.function(
+ SendStream.prototype.root,
+ "send.root: pass root as option"
+ );
+ SendStream.prototype.maxage = deprecate.function(/* @__PURE__ */ __name(function maxage(maxAge) {
+ this._maxage = typeof maxAge === "string" ? ms(maxAge) : Number(maxAge);
+ this._maxage = !isNaN(this._maxage) ? Math.min(Math.max(0, this._maxage), MAX_MAXAGE) : 0;
+ debug("max-age %d", this._maxage);
+ return this;
+ }, "maxage"), "send.maxage: pass maxAge as option");
+ SendStream.prototype.error = /* @__PURE__ */ __name(function error(status, err) {
+ if (hasListeners(this, "error")) {
+ return this.emit("error", createHttpError(status, err));
+ }
+ var res = this.res;
+ var msg = statuses.message[status] || String(status);
+ var doc = createHtmlDocument("Error", escapeHtml(msg));
+ clearHeaders(res);
+ if (err && err.headers) {
+ setHeaders(res, err.headers);
+ }
+ res.statusCode = status;
+ res.setHeader("Content-Type", "text/html; charset=UTF-8");
+ res.setHeader("Content-Length", Buffer.byteLength(doc));
+ res.setHeader("Content-Security-Policy", "default-src 'none'");
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ res.end(doc);
+ }, "error");
+ SendStream.prototype.hasTrailingSlash = /* @__PURE__ */ __name(function hasTrailingSlash() {
+ return this.path[this.path.length - 1] === "/";
+ }, "hasTrailingSlash");
+ SendStream.prototype.isConditionalGET = /* @__PURE__ */ __name(function isConditionalGET() {
+ return this.req.headers["if-match"] || this.req.headers["if-unmodified-since"] || this.req.headers["if-none-match"] || this.req.headers["if-modified-since"];
+ }, "isConditionalGET");
+ SendStream.prototype.isPreconditionFailure = /* @__PURE__ */ __name(function isPreconditionFailure() {
+ var req = this.req;
+ var res = this.res;
+ var match = req.headers["if-match"];
+ if (match) {
+ var etag2 = res.getHeader("ETag");
+ return !etag2 || match !== "*" && parseTokenList(match).every(function(match2) {
+ return match2 !== etag2 && match2 !== "W/" + etag2 && "W/" + match2 !== etag2;
+ });
+ }
+ var unmodifiedSince = parseHttpDate(req.headers["if-unmodified-since"]);
+ if (!isNaN(unmodifiedSince)) {
+ var lastModified = parseHttpDate(res.getHeader("Last-Modified"));
+ return isNaN(lastModified) || lastModified > unmodifiedSince;
+ }
+ return false;
+ }, "isPreconditionFailure");
+ SendStream.prototype.removeContentHeaderFields = /* @__PURE__ */ __name(function removeContentHeaderFields() {
+ var res = this.res;
+ res.removeHeader("Content-Encoding");
+ res.removeHeader("Content-Language");
+ res.removeHeader("Content-Length");
+ res.removeHeader("Content-Range");
+ res.removeHeader("Content-Type");
+ }, "removeContentHeaderFields");
+ SendStream.prototype.notModified = /* @__PURE__ */ __name(function notModified() {
+ var res = this.res;
+ debug("not modified");
+ this.removeContentHeaderFields();
+ res.statusCode = 304;
+ res.end();
+ }, "notModified");
+ SendStream.prototype.headersAlreadySent = /* @__PURE__ */ __name(function headersAlreadySent() {
+ var err = new Error("Can't set headers after they are sent.");
+ debug("headers already sent");
+ this.error(500, err);
+ }, "headersAlreadySent");
+ SendStream.prototype.isCachable = /* @__PURE__ */ __name(function isCachable() {
+ var statusCode = this.res.statusCode;
+ return statusCode >= 200 && statusCode < 300 || statusCode === 304;
+ }, "isCachable");
+ SendStream.prototype.onStatError = /* @__PURE__ */ __name(function onStatError(error) {
+ switch (error.code) {
+ case "ENAMETOOLONG":
+ case "ENOENT":
+ case "ENOTDIR":
+ this.error(404, error);
+ break;
+ default:
+ this.error(500, error);
+ break;
+ }
+ }, "onStatError");
+ SendStream.prototype.isFresh = /* @__PURE__ */ __name(function isFresh() {
+ return fresh(this.req.headers, {
+ etag: this.res.getHeader("ETag"),
+ "last-modified": this.res.getHeader("Last-Modified")
+ });
+ }, "isFresh");
+ SendStream.prototype.isRangeFresh = /* @__PURE__ */ __name(function isRangeFresh() {
+ var ifRange = this.req.headers["if-range"];
+ if (!ifRange) {
+ return true;
+ }
+ if (ifRange.indexOf('"') !== -1) {
+ var etag2 = this.res.getHeader("ETag");
+ return Boolean(etag2 && ifRange.indexOf(etag2) !== -1);
+ }
+ var lastModified = this.res.getHeader("Last-Modified");
+ return parseHttpDate(lastModified) <= parseHttpDate(ifRange);
+ }, "isRangeFresh");
+ SendStream.prototype.redirect = /* @__PURE__ */ __name(function redirect(path46) {
+ var res = this.res;
+ if (hasListeners(this, "directory")) {
+ this.emit("directory", res, path46);
+ return;
+ }
+ if (this.hasTrailingSlash()) {
+ this.error(403);
+ return;
+ }
+ var loc = encodeUrl(collapseLeadingSlashes(this.path + "/"));
+ var doc = createHtmlDocument("Redirecting", 'Redirecting to ' + escapeHtml(loc) + "");
+ res.statusCode = 301;
+ res.setHeader("Content-Type", "text/html; charset=UTF-8");
+ res.setHeader("Content-Length", Buffer.byteLength(doc));
+ res.setHeader("Content-Security-Policy", "default-src 'none'");
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ res.setHeader("Location", loc);
+ res.end(doc);
+ }, "redirect");
+ SendStream.prototype.pipe = /* @__PURE__ */ __name(function pipe(res) {
+ var root = this._root;
+ this.res = res;
+ var path46 = decode(this.path);
+ if (path46 === -1) {
+ this.error(400);
+ return res;
+ }
+ if (~path46.indexOf("\0")) {
+ this.error(400);
+ return res;
+ }
+ var parts;
+ if (root !== null) {
+ if (path46) {
+ path46 = normalize2("." + sep2 + path46);
+ }
+ if (UP_PATH_REGEXP.test(path46)) {
+ debug('malicious path "%s"', path46);
+ this.error(403);
+ return res;
+ }
+ parts = path46.split(sep2);
+ path46 = normalize2(join12(root, path46));
+ } else {
+ if (UP_PATH_REGEXP.test(path46)) {
+ debug('malicious path "%s"', path46);
+ this.error(403);
+ return res;
+ }
+ parts = normalize2(path46).split(sep2);
+ path46 = resolve18(path46);
+ }
+ if (containsDotFile(parts)) {
+ var access3 = this._dotfiles;
+ if (access3 === void 0) {
+ access3 = parts[parts.length - 1][0] === "." ? this._hidden ? "allow" : "ignore" : "allow";
+ }
+ debug('%s dotfile "%s"', access3, path46);
+ switch (access3) {
+ case "allow":
+ break;
+ case "deny":
+ this.error(403);
+ return res;
+ case "ignore":
+ default:
+ this.error(404);
+ return res;
+ }
+ }
+ if (this._index.length && this.hasTrailingSlash()) {
+ this.sendIndex(path46);
+ return res;
+ }
+ this.sendFile(path46);
+ return res;
+ }, "pipe");
+ SendStream.prototype.send = /* @__PURE__ */ __name(function send2(path46, stat3) {
+ var len = stat3.size;
+ var options14 = this.options;
+ var opts = {};
+ var res = this.res;
+ var req = this.req;
+ var ranges = req.headers.range;
+ var offset = options14.start || 0;
+ if (headersSent(res)) {
+ this.headersAlreadySent();
+ return;
+ }
+ debug('pipe "%s"', path46);
+ this.setHeader(path46, stat3);
+ this.type(path46);
+ if (this.isConditionalGET()) {
+ if (this.isPreconditionFailure()) {
+ this.error(412);
+ return;
+ }
+ if (this.isCachable() && this.isFresh()) {
+ this.notModified();
+ return;
+ }
+ }
+ len = Math.max(0, len - offset);
+ if (options14.end !== void 0) {
+ var bytes = options14.end - offset + 1;
+ if (len > bytes)
+ len = bytes;
+ }
+ if (this._acceptRanges && BYTES_RANGE_REGEXP.test(ranges)) {
+ ranges = parseRange(len, ranges, {
+ combine: true
+ });
+ if (!this.isRangeFresh()) {
+ debug("range stale");
+ ranges = -2;
+ }
+ if (ranges === -1) {
+ debug("range unsatisfiable");
+ res.setHeader("Content-Range", contentRange("bytes", len));
+ return this.error(416, {
+ headers: { "Content-Range": res.getHeader("Content-Range") }
+ });
+ }
+ if (ranges !== -2 && ranges.length === 1) {
+ debug("range %j", ranges);
+ res.statusCode = 206;
+ res.setHeader("Content-Range", contentRange("bytes", len, ranges[0]));
+ offset += ranges[0].start;
+ len = ranges[0].end - ranges[0].start + 1;
+ }
+ }
+ for (var prop in options14) {
+ opts[prop] = options14[prop];
+ }
+ opts.start = offset;
+ opts.end = Math.max(offset, offset + len - 1);
+ res.setHeader("Content-Length", len);
+ if (req.method === "HEAD") {
+ res.end();
+ return;
+ }
+ this.stream(path46, opts);
+ }, "send");
+ SendStream.prototype.sendFile = /* @__PURE__ */ __name(function sendFile(path46) {
+ var i = 0;
+ var self2 = this;
+ debug('stat "%s"', path46);
+ fs20.stat(path46, /* @__PURE__ */ __name(function onstat(err, stat3) {
+ if (err && err.code === "ENOENT" && !extname4(path46) && path46[path46.length - 1] !== sep2) {
+ return next(err);
+ }
+ if (err)
+ return self2.onStatError(err);
+ if (stat3.isDirectory())
+ return self2.redirect(path46);
+ self2.emit("file", path46, stat3);
+ self2.send(path46, stat3);
+ }, "onstat"));
+ function next(err) {
+ if (self2._extensions.length <= i) {
+ return err ? self2.onStatError(err) : self2.error(404);
+ }
+ var p = path46 + "." + self2._extensions[i++];
+ debug('stat "%s"', p);
+ fs20.stat(p, function(err2, stat3) {
+ if (err2)
+ return next(err2);
+ if (stat3.isDirectory())
+ return next();
+ self2.emit("file", p, stat3);
+ self2.send(p, stat3);
+ });
+ }
+ __name(next, "next");
+ }, "sendFile");
+ SendStream.prototype.sendIndex = /* @__PURE__ */ __name(function sendIndex(path46) {
+ var i = -1;
+ var self2 = this;
+ function next(err) {
+ if (++i >= self2._index.length) {
+ if (err)
+ return self2.onStatError(err);
+ return self2.error(404);
+ }
+ var p = join12(path46, self2._index[i]);
+ debug('stat "%s"', p);
+ fs20.stat(p, function(err2, stat3) {
+ if (err2)
+ return next(err2);
+ if (stat3.isDirectory())
+ return next();
+ self2.emit("file", p, stat3);
+ self2.send(p, stat3);
+ });
+ }
+ __name(next, "next");
+ next();
+ }, "sendIndex");
+ SendStream.prototype.stream = /* @__PURE__ */ __name(function stream2(path46, options14) {
+ var self2 = this;
+ var res = this.res;
+ var stream3 = fs20.createReadStream(path46, options14);
+ this.emit("stream", stream3);
+ stream3.pipe(res);
+ function cleanup() {
+ destroy(stream3, true);
+ }
+ __name(cleanup, "cleanup");
+ onFinished(res, cleanup);
+ stream3.on("error", /* @__PURE__ */ __name(function onerror(err) {
+ cleanup();
+ self2.onStatError(err);
+ }, "onerror"));
+ stream3.on("end", /* @__PURE__ */ __name(function onend() {
+ self2.emit("end");
+ }, "onend"));
+ }, "stream");
+ SendStream.prototype.type = /* @__PURE__ */ __name(function type(path46) {
+ var res = this.res;
+ if (res.getHeader("Content-Type"))
+ return;
+ var type2 = mime.lookup(path46);
+ if (!type2) {
+ debug("no content-type");
+ return;
+ }
+ var charset = mime.charsets.lookup(type2);
+ debug("content-type %s", type2);
+ res.setHeader("Content-Type", type2 + (charset ? "; charset=" + charset : ""));
+ }, "type");
+ SendStream.prototype.setHeader = /* @__PURE__ */ __name(function setHeader(path46, stat3) {
+ var res = this.res;
+ this.emit("headers", res, path46, stat3);
+ if (this._acceptRanges && !res.getHeader("Accept-Ranges")) {
+ debug("accept ranges");
+ res.setHeader("Accept-Ranges", "bytes");
+ }
+ if (this._cacheControl && !res.getHeader("Cache-Control")) {
+ var cacheControl = "public, max-age=" + Math.floor(this._maxage / 1e3);
+ if (this._immutable) {
+ cacheControl += ", immutable";
+ }
+ debug("cache-control %s", cacheControl);
+ res.setHeader("Cache-Control", cacheControl);
+ }
+ if (this._lastModified && !res.getHeader("Last-Modified")) {
+ var modified = stat3.mtime.toUTCString();
+ debug("modified %s", modified);
+ res.setHeader("Last-Modified", modified);
+ }
+ if (this._etag && !res.getHeader("ETag")) {
+ var val = etag(stat3);
+ debug("etag %s", val);
+ res.setHeader("ETag", val);
+ }
+ }, "setHeader");
+ function clearHeaders(res) {
+ var headers = getHeaderNames(res);
+ for (var i = 0; i < headers.length; i++) {
+ res.removeHeader(headers[i]);
+ }
+ }
+ __name(clearHeaders, "clearHeaders");
+ function collapseLeadingSlashes(str) {
+ for (var i = 0; i < str.length; i++) {
+ if (str[i] !== "/") {
+ break;
+ }
+ }
+ return i > 1 ? "/" + str.substr(i) : str;
+ }
+ __name(collapseLeadingSlashes, "collapseLeadingSlashes");
+ function containsDotFile(parts) {
+ for (var i = 0; i < parts.length; i++) {
+ var part = parts[i];
+ if (part.length > 1 && part[0] === ".") {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(containsDotFile, "containsDotFile");
+ function contentRange(type, size, range) {
+ return type + " " + (range ? range.start + "-" + range.end : "*") + "/" + size;
+ }
+ __name(contentRange, "contentRange");
+ function createHtmlDocument(title, body) {
+ return '\n\n\n\n' + title + "\n\n\n" + body + "
\n\n\n";
+ }
+ __name(createHtmlDocument, "createHtmlDocument");
+ function createHttpError(status, err) {
+ if (!err) {
+ return createError(status);
+ }
+ return err instanceof Error ? createError(status, err, { expose: false }) : createError(status, err);
+ }
+ __name(createHttpError, "createHttpError");
+ function decode(path46) {
+ try {
+ return decodeURIComponent(path46);
+ } catch (err) {
+ return -1;
+ }
+ }
+ __name(decode, "decode");
+ function getHeaderNames(res) {
+ return typeof res.getHeaderNames !== "function" ? Object.keys(res._headers || {}) : res.getHeaderNames();
+ }
+ __name(getHeaderNames, "getHeaderNames");
+ function hasListeners(emitter, type) {
+ var count = typeof emitter.listenerCount !== "function" ? emitter.listeners(type).length : emitter.listenerCount(type);
+ return count > 0;
+ }
+ __name(hasListeners, "hasListeners");
+ function headersSent(res) {
+ return typeof res.headersSent !== "boolean" ? Boolean(res._header) : res.headersSent;
+ }
+ __name(headersSent, "headersSent");
+ function normalizeList(val, name) {
+ var list = [].concat(val || []);
+ for (var i = 0; i < list.length; i++) {
+ if (typeof list[i] !== "string") {
+ throw new TypeError(name + " must be array of strings or false");
+ }
+ }
+ return list;
+ }
+ __name(normalizeList, "normalizeList");
+ function parseHttpDate(date) {
+ var timestamp = date && Date.parse(date);
+ return typeof timestamp === "number" ? timestamp : NaN;
+ }
+ __name(parseHttpDate, "parseHttpDate");
+ function parseTokenList(str) {
+ var end = 0;
+ var list = [];
+ var start = 0;
+ for (var i = 0, len = str.length; i < len; i++) {
+ switch (str.charCodeAt(i)) {
+ case 32:
+ if (start === end) {
+ start = end = i + 1;
+ }
+ break;
+ case 44:
+ if (start !== end) {
+ list.push(str.substring(start, end));
+ }
+ start = end = i + 1;
+ break;
+ default:
+ end = i + 1;
+ break;
+ }
+ }
+ if (start !== end) {
+ list.push(str.substring(start, end));
+ }
+ return list;
+ }
+ __name(parseTokenList, "parseTokenList");
+ function setHeaders(res, headers) {
+ var keys = Object.keys(headers);
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ res.setHeader(key, headers[key]);
+ }
+ }
+ __name(setHeaders, "setHeaders");
+ }
+});
+
+// ../../node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js
+var require_forwarded = __commonJS({
+ "../../node_modules/.pnpm/forwarded@0.2.0/node_modules/forwarded/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = forwarded;
+ function forwarded(req) {
+ if (!req) {
+ throw new TypeError("argument req is required");
+ }
+ var proxyAddrs = parse4(req.headers["x-forwarded-for"] || "");
+ var socketAddr = getSocketAddr(req);
+ var addrs = [socketAddr].concat(proxyAddrs);
+ return addrs;
+ }
+ __name(forwarded, "forwarded");
+ function getSocketAddr(req) {
+ return req.socket ? req.socket.remoteAddress : req.connection.remoteAddress;
+ }
+ __name(getSocketAddr, "getSocketAddr");
+ function parse4(header) {
+ var end = header.length;
+ var list = [];
+ var start = header.length;
+ for (var i = header.length - 1; i >= 0; i--) {
+ switch (header.charCodeAt(i)) {
+ case 32:
+ if (start === end) {
+ start = end = i;
+ }
+ break;
+ case 44:
+ if (start !== end) {
+ list.push(header.substring(start, end));
+ }
+ start = end = i;
+ break;
+ default:
+ start = i;
+ break;
+ }
+ }
+ if (start !== end) {
+ list.push(header.substring(start, end));
+ }
+ return list;
+ }
+ __name(parse4, "parse");
+ }
+});
+
+// ../../node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js
+var require_ipaddr = __commonJS({
+ "../../node_modules/.pnpm/ipaddr.js@1.9.1/node_modules/ipaddr.js/lib/ipaddr.js"(exports2, module2) {
+ init_import_meta_url();
+ (function() {
+ var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex;
+ ipaddr = {};
+ root = this;
+ if (typeof module2 !== "undefined" && module2 !== null && module2.exports) {
+ module2.exports = ipaddr;
+ } else {
+ root["ipaddr"] = ipaddr;
+ }
+ matchCIDR = /* @__PURE__ */ __name(function(first, second, partSize, cidrBits) {
+ var part, shift;
+ if (first.length !== second.length) {
+ throw new Error("ipaddr: cannot match CIDR for objects with different lengths");
+ }
+ part = 0;
+ while (cidrBits > 0) {
+ shift = partSize - cidrBits;
+ if (shift < 0) {
+ shift = 0;
+ }
+ if (first[part] >> shift !== second[part] >> shift) {
+ return false;
+ }
+ cidrBits -= partSize;
+ part += 1;
+ }
+ return true;
+ }, "matchCIDR");
+ ipaddr.subnetMatch = function(address, rangeList, defaultName) {
+ var k, len, rangeName, rangeSubnets, subnet;
+ if (defaultName == null) {
+ defaultName = "unicast";
+ }
+ for (rangeName in rangeList) {
+ rangeSubnets = rangeList[rangeName];
+ if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) {
+ rangeSubnets = [rangeSubnets];
+ }
+ for (k = 0, len = rangeSubnets.length; k < len; k++) {
+ subnet = rangeSubnets[k];
+ if (address.kind() === subnet[0].kind()) {
+ if (address.match.apply(address, subnet)) {
+ return rangeName;
+ }
+ }
+ }
+ }
+ return defaultName;
+ };
+ ipaddr.IPv4 = function() {
+ function IPv4(octets) {
+ var k, len, octet;
+ if (octets.length !== 4) {
+ throw new Error("ipaddr: ipv4 octet count should be 4");
+ }
+ for (k = 0, len = octets.length; k < len; k++) {
+ octet = octets[k];
+ if (!(0 <= octet && octet <= 255)) {
+ throw new Error("ipaddr: ipv4 octet should fit in 8 bits");
+ }
+ }
+ this.octets = octets;
+ }
+ __name(IPv4, "IPv4");
+ IPv4.prototype.kind = function() {
+ return "ipv4";
+ };
+ IPv4.prototype.toString = function() {
+ return this.octets.join(".");
+ };
+ IPv4.prototype.toNormalizedString = function() {
+ return this.toString();
+ };
+ IPv4.prototype.toByteArray = function() {
+ return this.octets.slice(0);
+ };
+ IPv4.prototype.match = function(other, cidrRange) {
+ var ref;
+ if (cidrRange === void 0) {
+ ref = other, other = ref[0], cidrRange = ref[1];
+ }
+ if (other.kind() !== "ipv4") {
+ throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one");
+ }
+ return matchCIDR(this.octets, other.octets, 8, cidrRange);
+ };
+ IPv4.prototype.SpecialRanges = {
+ unspecified: [[new IPv4([0, 0, 0, 0]), 8]],
+ broadcast: [[new IPv4([255, 255, 255, 255]), 32]],
+ multicast: [[new IPv4([224, 0, 0, 0]), 4]],
+ linkLocal: [[new IPv4([169, 254, 0, 0]), 16]],
+ loopback: [[new IPv4([127, 0, 0, 0]), 8]],
+ carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]],
+ "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]],
+ reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]]
+ };
+ IPv4.prototype.range = function() {
+ return ipaddr.subnetMatch(this, this.SpecialRanges);
+ };
+ IPv4.prototype.toIPv4MappedAddress = function() {
+ return ipaddr.IPv6.parse("::ffff:" + this.toString());
+ };
+ IPv4.prototype.prefixLengthFromSubnetMask = function() {
+ var cidr, i, k, octet, stop, zeros, zerotable;
+ zerotable = {
+ 0: 8,
+ 128: 7,
+ 192: 6,
+ 224: 5,
+ 240: 4,
+ 248: 3,
+ 252: 2,
+ 254: 1,
+ 255: 0
+ };
+ cidr = 0;
+ stop = false;
+ for (i = k = 3; k >= 0; i = k += -1) {
+ octet = this.octets[i];
+ if (octet in zerotable) {
+ zeros = zerotable[octet];
+ if (stop && zeros !== 0) {
+ return null;
+ }
+ if (zeros !== 8) {
+ stop = true;
+ }
+ cidr += zeros;
+ } else {
+ return null;
+ }
+ }
+ return 32 - cidr;
+ };
+ return IPv4;
+ }();
+ ipv4Part = "(0?\\d+|0x[a-f0-9]+)";
+ ipv4Regexes = {
+ fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", "i"),
+ longValue: new RegExp("^" + ipv4Part + "$", "i")
+ };
+ ipaddr.IPv4.parser = function(string) {
+ var match, parseIntAuto, part, shift, value;
+ parseIntAuto = /* @__PURE__ */ __name(function(string2) {
+ if (string2[0] === "0" && string2[1] !== "x") {
+ return parseInt(string2, 8);
+ } else {
+ return parseInt(string2);
+ }
+ }, "parseIntAuto");
+ if (match = string.match(ipv4Regexes.fourOctet)) {
+ return function() {
+ var k, len, ref, results;
+ ref = match.slice(1, 6);
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(parseIntAuto(part));
+ }
+ return results;
+ }();
+ } else if (match = string.match(ipv4Regexes.longValue)) {
+ value = parseIntAuto(match[1]);
+ if (value > 4294967295 || value < 0) {
+ throw new Error("ipaddr: address outside defined range");
+ }
+ return function() {
+ var k, results;
+ results = [];
+ for (shift = k = 0; k <= 24; shift = k += 8) {
+ results.push(value >> shift & 255);
+ }
+ return results;
+ }().reverse();
+ } else {
+ return null;
+ }
+ };
+ ipaddr.IPv6 = function() {
+ function IPv6(parts, zoneId) {
+ var i, k, l, len, part, ref;
+ if (parts.length === 16) {
+ this.parts = [];
+ for (i = k = 0; k <= 14; i = k += 2) {
+ this.parts.push(parts[i] << 8 | parts[i + 1]);
+ }
+ } else if (parts.length === 8) {
+ this.parts = parts;
+ } else {
+ throw new Error("ipaddr: ipv6 part count should be 8 or 16");
+ }
+ ref = this.parts;
+ for (l = 0, len = ref.length; l < len; l++) {
+ part = ref[l];
+ if (!(0 <= part && part <= 65535)) {
+ throw new Error("ipaddr: ipv6 part should fit in 16 bits");
+ }
+ }
+ if (zoneId) {
+ this.zoneId = zoneId;
+ }
+ }
+ __name(IPv6, "IPv6");
+ IPv6.prototype.kind = function() {
+ return "ipv6";
+ };
+ IPv6.prototype.toString = function() {
+ return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, "::");
+ };
+ IPv6.prototype.toRFC5952String = function() {
+ var bestMatchIndex, bestMatchLength, match, regex, string;
+ regex = /((^|:)(0(:|$)){2,})/g;
+ string = this.toNormalizedString();
+ bestMatchIndex = 0;
+ bestMatchLength = -1;
+ while (match = regex.exec(string)) {
+ if (match[0].length > bestMatchLength) {
+ bestMatchIndex = match.index;
+ bestMatchLength = match[0].length;
+ }
+ }
+ if (bestMatchLength < 0) {
+ return string;
+ }
+ return string.substring(0, bestMatchIndex) + "::" + string.substring(bestMatchIndex + bestMatchLength);
+ };
+ IPv6.prototype.toByteArray = function() {
+ var bytes, k, len, part, ref;
+ bytes = [];
+ ref = this.parts;
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ bytes.push(part >> 8);
+ bytes.push(part & 255);
+ }
+ return bytes;
+ };
+ IPv6.prototype.toNormalizedString = function() {
+ var addr, part, suffix;
+ addr = function() {
+ var k, len, ref, results;
+ ref = this.parts;
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(part.toString(16));
+ }
+ return results;
+ }.call(this).join(":");
+ suffix = "";
+ if (this.zoneId) {
+ suffix = "%" + this.zoneId;
+ }
+ return addr + suffix;
+ };
+ IPv6.prototype.toFixedLengthString = function() {
+ var addr, part, suffix;
+ addr = function() {
+ var k, len, ref, results;
+ ref = this.parts;
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(part.toString(16).padStart(4, "0"));
+ }
+ return results;
+ }.call(this).join(":");
+ suffix = "";
+ if (this.zoneId) {
+ suffix = "%" + this.zoneId;
+ }
+ return addr + suffix;
+ };
+ IPv6.prototype.match = function(other, cidrRange) {
+ var ref;
+ if (cidrRange === void 0) {
+ ref = other, other = ref[0], cidrRange = ref[1];
+ }
+ if (other.kind() !== "ipv6") {
+ throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one");
+ }
+ return matchCIDR(this.parts, other.parts, 16, cidrRange);
+ };
+ IPv6.prototype.SpecialRanges = {
+ unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128],
+ linkLocal: [new IPv6([65152, 0, 0, 0, 0, 0, 0, 0]), 10],
+ multicast: [new IPv6([65280, 0, 0, 0, 0, 0, 0, 0]), 8],
+ loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128],
+ uniqueLocal: [new IPv6([64512, 0, 0, 0, 0, 0, 0, 0]), 7],
+ ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 65535, 0, 0]), 96],
+ rfc6145: [new IPv6([0, 0, 0, 0, 65535, 0, 0, 0]), 96],
+ rfc6052: [new IPv6([100, 65435, 0, 0, 0, 0, 0, 0]), 96],
+ "6to4": [new IPv6([8194, 0, 0, 0, 0, 0, 0, 0]), 16],
+ teredo: [new IPv6([8193, 0, 0, 0, 0, 0, 0, 0]), 32],
+ reserved: [[new IPv6([8193, 3512, 0, 0, 0, 0, 0, 0]), 32]]
+ };
+ IPv6.prototype.range = function() {
+ return ipaddr.subnetMatch(this, this.SpecialRanges);
+ };
+ IPv6.prototype.isIPv4MappedAddress = function() {
+ return this.range() === "ipv4Mapped";
+ };
+ IPv6.prototype.toIPv4Address = function() {
+ var high, low, ref;
+ if (!this.isIPv4MappedAddress()) {
+ throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4");
+ }
+ ref = this.parts.slice(-2), high = ref[0], low = ref[1];
+ return new ipaddr.IPv4([high >> 8, high & 255, low >> 8, low & 255]);
+ };
+ IPv6.prototype.prefixLengthFromSubnetMask = function() {
+ var cidr, i, k, part, stop, zeros, zerotable;
+ zerotable = {
+ 0: 16,
+ 32768: 15,
+ 49152: 14,
+ 57344: 13,
+ 61440: 12,
+ 63488: 11,
+ 64512: 10,
+ 65024: 9,
+ 65280: 8,
+ 65408: 7,
+ 65472: 6,
+ 65504: 5,
+ 65520: 4,
+ 65528: 3,
+ 65532: 2,
+ 65534: 1,
+ 65535: 0
+ };
+ cidr = 0;
+ stop = false;
+ for (i = k = 7; k >= 0; i = k += -1) {
+ part = this.parts[i];
+ if (part in zerotable) {
+ zeros = zerotable[part];
+ if (stop && zeros !== 0) {
+ return null;
+ }
+ if (zeros !== 16) {
+ stop = true;
+ }
+ cidr += zeros;
+ } else {
+ return null;
+ }
+ }
+ return 128 - cidr;
+ };
+ return IPv6;
+ }();
+ ipv6Part = "(?:[0-9a-f]+::?)+";
+ zoneIndex = "%[0-9a-z]{1,}";
+ ipv6Regexes = {
+ zoneIndex: new RegExp(zoneIndex, "i"),
+ "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", "i"),
+ transitional: new RegExp("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)" + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), "i")
+ };
+ expandIPv6 = /* @__PURE__ */ __name(function(string, parts) {
+ var colonCount, lastColon, part, replacement, replacementCount, zoneId;
+ if (string.indexOf("::") !== string.lastIndexOf("::")) {
+ return null;
+ }
+ zoneId = (string.match(ipv6Regexes["zoneIndex"]) || [])[0];
+ if (zoneId) {
+ zoneId = zoneId.substring(1);
+ string = string.replace(/%.+$/, "");
+ }
+ colonCount = 0;
+ lastColon = -1;
+ while ((lastColon = string.indexOf(":", lastColon + 1)) >= 0) {
+ colonCount++;
+ }
+ if (string.substr(0, 2) === "::") {
+ colonCount--;
+ }
+ if (string.substr(-2, 2) === "::") {
+ colonCount--;
+ }
+ if (colonCount > parts) {
+ return null;
+ }
+ replacementCount = parts - colonCount;
+ replacement = ":";
+ while (replacementCount--) {
+ replacement += "0:";
+ }
+ string = string.replace("::", replacement);
+ if (string[0] === ":") {
+ string = string.slice(1);
+ }
+ if (string[string.length - 1] === ":") {
+ string = string.slice(0, -1);
+ }
+ parts = function() {
+ var k, len, ref, results;
+ ref = string.split(":");
+ results = [];
+ for (k = 0, len = ref.length; k < len; k++) {
+ part = ref[k];
+ results.push(parseInt(part, 16));
+ }
+ return results;
+ }();
+ return {
+ parts,
+ zoneId
+ };
+ }, "expandIPv6");
+ ipaddr.IPv6.parser = function(string) {
+ var addr, k, len, match, octet, octets, zoneId;
+ if (ipv6Regexes["native"].test(string)) {
+ return expandIPv6(string, 8);
+ } else if (match = string.match(ipv6Regexes["transitional"])) {
+ zoneId = match[6] || "";
+ addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6);
+ if (addr.parts) {
+ octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])];
+ for (k = 0, len = octets.length; k < len; k++) {
+ octet = octets[k];
+ if (!(0 <= octet && octet <= 255)) {
+ return null;
+ }
+ }
+ addr.parts.push(octets[0] << 8 | octets[1]);
+ addr.parts.push(octets[2] << 8 | octets[3]);
+ return {
+ parts: addr.parts,
+ zoneId: addr.zoneId
+ };
+ }
+ }
+ return null;
+ };
+ ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) {
+ return this.parser(string) !== null;
+ };
+ ipaddr.IPv4.isValid = function(string) {
+ var e2;
+ try {
+ new this(this.parser(string));
+ return true;
+ } catch (error1) {
+ e2 = error1;
+ return false;
+ }
+ };
+ ipaddr.IPv4.isValidFourPartDecimal = function(string) {
+ if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) {
+ return true;
+ } else {
+ return false;
+ }
+ };
+ ipaddr.IPv6.isValid = function(string) {
+ var addr, e2;
+ if (typeof string === "string" && string.indexOf(":") === -1) {
+ return false;
+ }
+ try {
+ addr = this.parser(string);
+ new this(addr.parts, addr.zoneId);
+ return true;
+ } catch (error1) {
+ e2 = error1;
+ return false;
+ }
+ };
+ ipaddr.IPv4.parse = function(string) {
+ var parts;
+ parts = this.parser(string);
+ if (parts === null) {
+ throw new Error("ipaddr: string is not formatted like ip address");
+ }
+ return new this(parts);
+ };
+ ipaddr.IPv6.parse = function(string) {
+ var addr;
+ addr = this.parser(string);
+ if (addr.parts === null) {
+ throw new Error("ipaddr: string is not formatted like ip address");
+ }
+ return new this(addr.parts, addr.zoneId);
+ };
+ ipaddr.IPv4.parseCIDR = function(string) {
+ var maskLength, match, parsed;
+ if (match = string.match(/^(.+)\/(\d+)$/)) {
+ maskLength = parseInt(match[2]);
+ if (maskLength >= 0 && maskLength <= 32) {
+ parsed = [this.parse(match[1]), maskLength];
+ Object.defineProperty(parsed, "toString", {
+ value: function() {
+ return this.join("/");
+ }
+ });
+ return parsed;
+ }
+ }
+ throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range");
+ };
+ ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) {
+ var filledOctetCount, j, octets;
+ prefix = parseInt(prefix);
+ if (prefix < 0 || prefix > 32) {
+ throw new Error("ipaddr: invalid IPv4 prefix length");
+ }
+ octets = [0, 0, 0, 0];
+ j = 0;
+ filledOctetCount = Math.floor(prefix / 8);
+ while (j < filledOctetCount) {
+ octets[j] = 255;
+ j++;
+ }
+ if (filledOctetCount < 4) {
+ octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - prefix % 8;
+ }
+ return new this(octets);
+ };
+ ipaddr.IPv4.broadcastAddressFromCIDR = function(string) {
+ var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
+ try {
+ cidr = this.parseCIDR(string);
+ ipInterfaceOctets = cidr[0].toByteArray();
+ subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
+ octets = [];
+ i = 0;
+ while (i < 4) {
+ octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255);
+ i++;
+ }
+ return new this(octets);
+ } catch (error1) {
+ error = error1;
+ throw new Error("ipaddr: the address does not have IPv4 CIDR format");
+ }
+ };
+ ipaddr.IPv4.networkAddressFromCIDR = function(string) {
+ var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets;
+ try {
+ cidr = this.parseCIDR(string);
+ ipInterfaceOctets = cidr[0].toByteArray();
+ subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray();
+ octets = [];
+ i = 0;
+ while (i < 4) {
+ octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10));
+ i++;
+ }
+ return new this(octets);
+ } catch (error1) {
+ error = error1;
+ throw new Error("ipaddr: the address does not have IPv4 CIDR format");
+ }
+ };
+ ipaddr.IPv6.parseCIDR = function(string) {
+ var maskLength, match, parsed;
+ if (match = string.match(/^(.+)\/(\d+)$/)) {
+ maskLength = parseInt(match[2]);
+ if (maskLength >= 0 && maskLength <= 128) {
+ parsed = [this.parse(match[1]), maskLength];
+ Object.defineProperty(parsed, "toString", {
+ value: function() {
+ return this.join("/");
+ }
+ });
+ return parsed;
+ }
+ }
+ throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range");
+ };
+ ipaddr.isValid = function(string) {
+ return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string);
+ };
+ ipaddr.parse = function(string) {
+ if (ipaddr.IPv6.isValid(string)) {
+ return ipaddr.IPv6.parse(string);
+ } else if (ipaddr.IPv4.isValid(string)) {
+ return ipaddr.IPv4.parse(string);
+ } else {
+ throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format");
+ }
+ };
+ ipaddr.parseCIDR = function(string) {
+ var e2;
+ try {
+ return ipaddr.IPv6.parseCIDR(string);
+ } catch (error1) {
+ e2 = error1;
+ try {
+ return ipaddr.IPv4.parseCIDR(string);
+ } catch (error12) {
+ e2 = error12;
+ throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format");
+ }
+ }
+ };
+ ipaddr.fromByteArray = function(bytes) {
+ var length;
+ length = bytes.length;
+ if (length === 4) {
+ return new ipaddr.IPv4(bytes);
+ } else if (length === 16) {
+ return new ipaddr.IPv6(bytes);
+ } else {
+ throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address");
+ }
+ };
+ ipaddr.process = function(string) {
+ var addr;
+ addr = this.parse(string);
+ if (addr.kind() === "ipv6" && addr.isIPv4MappedAddress()) {
+ return addr.toIPv4Address();
+ } else {
+ return addr;
+ }
+ };
+ }).call(exports2);
+ }
+});
+
+// ../../node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js
+var require_proxy_addr = __commonJS({
+ "../../node_modules/.pnpm/proxy-addr@2.0.7/node_modules/proxy-addr/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = proxyaddr;
+ module2.exports.all = alladdrs;
+ module2.exports.compile = compile;
+ var forwarded = require_forwarded();
+ var ipaddr = require_ipaddr();
+ var DIGIT_REGEXP = /^[0-9]+$/;
+ var isip = ipaddr.isValid;
+ var parseip = ipaddr.parse;
+ var IP_RANGES = {
+ linklocal: ["169.254.0.0/16", "fe80::/10"],
+ loopback: ["127.0.0.1/8", "::1/128"],
+ uniquelocal: ["10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16", "fc00::/7"]
+ };
+ function alladdrs(req, trust) {
+ var addrs = forwarded(req);
+ if (!trust) {
+ return addrs;
+ }
+ if (typeof trust !== "function") {
+ trust = compile(trust);
+ }
+ for (var i = 0; i < addrs.length - 1; i++) {
+ if (trust(addrs[i], i))
+ continue;
+ addrs.length = i + 1;
+ }
+ return addrs;
+ }
+ __name(alladdrs, "alladdrs");
+ function compile(val) {
+ if (!val) {
+ throw new TypeError("argument is required");
+ }
+ var trust;
+ if (typeof val === "string") {
+ trust = [val];
+ } else if (Array.isArray(val)) {
+ trust = val.slice();
+ } else {
+ throw new TypeError("unsupported trust argument");
+ }
+ for (var i = 0; i < trust.length; i++) {
+ val = trust[i];
+ if (!Object.prototype.hasOwnProperty.call(IP_RANGES, val)) {
+ continue;
+ }
+ val = IP_RANGES[val];
+ trust.splice.apply(trust, [i, 1].concat(val));
+ i += val.length - 1;
+ }
+ return compileTrust(compileRangeSubnets(trust));
+ }
+ __name(compile, "compile");
+ function compileRangeSubnets(arr) {
+ var rangeSubnets = new Array(arr.length);
+ for (var i = 0; i < arr.length; i++) {
+ rangeSubnets[i] = parseipNotation(arr[i]);
+ }
+ return rangeSubnets;
+ }
+ __name(compileRangeSubnets, "compileRangeSubnets");
+ function compileTrust(rangeSubnets) {
+ var len = rangeSubnets.length;
+ return len === 0 ? trustNone : len === 1 ? trustSingle(rangeSubnets[0]) : trustMulti(rangeSubnets);
+ }
+ __name(compileTrust, "compileTrust");
+ function parseipNotation(note) {
+ var pos = note.lastIndexOf("/");
+ var str = pos !== -1 ? note.substring(0, pos) : note;
+ if (!isip(str)) {
+ throw new TypeError("invalid IP address: " + str);
+ }
+ var ip2 = parseip(str);
+ if (pos === -1 && ip2.kind() === "ipv6" && ip2.isIPv4MappedAddress()) {
+ ip2 = ip2.toIPv4Address();
+ }
+ var max = ip2.kind() === "ipv6" ? 128 : 32;
+ var range = pos !== -1 ? note.substring(pos + 1, note.length) : null;
+ if (range === null) {
+ range = max;
+ } else if (DIGIT_REGEXP.test(range)) {
+ range = parseInt(range, 10);
+ } else if (ip2.kind() === "ipv4" && isip(range)) {
+ range = parseNetmask(range);
+ } else {
+ range = null;
+ }
+ if (range <= 0 || range > max) {
+ throw new TypeError("invalid range on address: " + note);
+ }
+ return [ip2, range];
+ }
+ __name(parseipNotation, "parseipNotation");
+ function parseNetmask(netmask) {
+ var ip2 = parseip(netmask);
+ var kind = ip2.kind();
+ return kind === "ipv4" ? ip2.prefixLengthFromSubnetMask() : null;
+ }
+ __name(parseNetmask, "parseNetmask");
+ function proxyaddr(req, trust) {
+ if (!req) {
+ throw new TypeError("req argument is required");
+ }
+ if (!trust) {
+ throw new TypeError("trust argument is required");
+ }
+ var addrs = alladdrs(req, trust);
+ var addr = addrs[addrs.length - 1];
+ return addr;
+ }
+ __name(proxyaddr, "proxyaddr");
+ function trustNone() {
+ return false;
+ }
+ __name(trustNone, "trustNone");
+ function trustMulti(subnets) {
+ return /* @__PURE__ */ __name(function trust(addr) {
+ if (!isip(addr))
+ return false;
+ var ip2 = parseip(addr);
+ var ipconv;
+ var kind = ip2.kind();
+ for (var i = 0; i < subnets.length; i++) {
+ var subnet = subnets[i];
+ var subnetip = subnet[0];
+ var subnetkind = subnetip.kind();
+ var subnetrange = subnet[1];
+ var trusted = ip2;
+ if (kind !== subnetkind) {
+ if (subnetkind === "ipv4" && !ip2.isIPv4MappedAddress()) {
+ continue;
+ }
+ if (!ipconv) {
+ ipconv = subnetkind === "ipv4" ? ip2.toIPv4Address() : ip2.toIPv4MappedAddress();
+ }
+ trusted = ipconv;
+ }
+ if (trusted.match(subnetip, subnetrange)) {
+ return true;
+ }
+ }
+ return false;
+ }, "trust");
+ }
+ __name(trustMulti, "trustMulti");
+ function trustSingle(subnet) {
+ var subnetip = subnet[0];
+ var subnetkind = subnetip.kind();
+ var subnetisipv4 = subnetkind === "ipv4";
+ var subnetrange = subnet[1];
+ return /* @__PURE__ */ __name(function trust(addr) {
+ if (!isip(addr))
+ return false;
+ var ip2 = parseip(addr);
+ var kind = ip2.kind();
+ if (kind !== subnetkind) {
+ if (subnetisipv4 && !ip2.isIPv4MappedAddress()) {
+ return false;
+ }
+ ip2 = subnetisipv4 ? ip2.toIPv4Address() : ip2.toIPv4MappedAddress();
+ }
+ return ip2.match(subnetip, subnetrange);
+ }, "trust");
+ }
+ __name(trustSingle, "trustSingle");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/utils.js
+var require_utils5 = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/utils.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var Buffer3 = require_safe_buffer().Buffer;
+ var contentDisposition = require_content_disposition();
+ var contentType = require_content_type();
+ var deprecate = require_depd()("express");
+ var flatten = require_array_flatten();
+ var mime = require_send().mime;
+ var etag = require_etag();
+ var proxyaddr = require_proxy_addr();
+ var qs = require_lib4();
+ var querystring = require("querystring");
+ exports2.etag = createETagGenerator({ weak: false });
+ exports2.wetag = createETagGenerator({ weak: true });
+ exports2.isAbsolute = function(path45) {
+ if ("/" === path45[0])
+ return true;
+ if (":" === path45[1] && ("\\" === path45[2] || "/" === path45[2]))
+ return true;
+ if ("\\\\" === path45.substring(0, 2))
+ return true;
+ };
+ exports2.flatten = deprecate.function(
+ flatten,
+ "utils.flatten: use array-flatten npm module instead"
+ );
+ exports2.normalizeType = function(type) {
+ return ~type.indexOf("/") ? acceptParams(type) : { value: mime.lookup(type), params: {} };
+ };
+ exports2.normalizeTypes = function(types) {
+ var ret = [];
+ for (var i = 0; i < types.length; ++i) {
+ ret.push(exports2.normalizeType(types[i]));
+ }
+ return ret;
+ };
+ exports2.contentDisposition = deprecate.function(
+ contentDisposition,
+ "utils.contentDisposition: use content-disposition npm module instead"
+ );
+ function acceptParams(str, index) {
+ var parts = str.split(/ *; */);
+ var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index };
+ for (var i = 1; i < parts.length; ++i) {
+ var pms = parts[i].split(/ *= */);
+ if ("q" === pms[0]) {
+ ret.quality = parseFloat(pms[1]);
+ } else {
+ ret.params[pms[0]] = pms[1];
+ }
+ }
+ return ret;
+ }
+ __name(acceptParams, "acceptParams");
+ exports2.compileETag = function(val) {
+ var fn2;
+ if (typeof val === "function") {
+ return val;
+ }
+ switch (val) {
+ case true:
+ case "weak":
+ fn2 = exports2.wetag;
+ break;
+ case false:
+ break;
+ case "strong":
+ fn2 = exports2.etag;
+ break;
+ default:
+ throw new TypeError("unknown value for etag function: " + val);
+ }
+ return fn2;
+ };
+ exports2.compileQueryParser = /* @__PURE__ */ __name(function compileQueryParser(val) {
+ var fn2;
+ if (typeof val === "function") {
+ return val;
+ }
+ switch (val) {
+ case true:
+ case "simple":
+ fn2 = querystring.parse;
+ break;
+ case false:
+ fn2 = newObject;
+ break;
+ case "extended":
+ fn2 = parseExtendedQueryString;
+ break;
+ default:
+ throw new TypeError("unknown value for query parser function: " + val);
+ }
+ return fn2;
+ }, "compileQueryParser");
+ exports2.compileTrust = function(val) {
+ if (typeof val === "function")
+ return val;
+ if (val === true) {
+ return function() {
+ return true;
+ };
+ }
+ if (typeof val === "number") {
+ return function(a, i) {
+ return i < val;
+ };
+ }
+ if (typeof val === "string") {
+ val = val.split(",").map(function(v) {
+ return v.trim();
+ });
+ }
+ return proxyaddr.compile(val || []);
+ };
+ exports2.setCharset = /* @__PURE__ */ __name(function setCharset(type, charset) {
+ if (!type || !charset) {
+ return type;
+ }
+ var parsed = contentType.parse(type);
+ parsed.parameters.charset = charset;
+ return contentType.format(parsed);
+ }, "setCharset");
+ function createETagGenerator(options14) {
+ return /* @__PURE__ */ __name(function generateETag(body, encoding) {
+ var buf = !Buffer3.isBuffer(body) ? Buffer3.from(body, encoding) : body;
+ return etag(buf, options14);
+ }, "generateETag");
+ }
+ __name(createETagGenerator, "createETagGenerator");
+ function parseExtendedQueryString(str) {
+ return qs.parse(str, {
+ allowPrototypes: true
+ });
+ }
+ __name(parseExtendedQueryString, "parseExtendedQueryString");
+ function newObject() {
+ return {};
+ }
+ __name(newObject, "newObject");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/application.js
+var require_application = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/application.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var finalhandler = require_finalhandler();
+ var Router = require_router();
+ var methods = require_methods();
+ var middleware = require_init();
+ var query = require_query();
+ var debug = require_src2()("express:application");
+ var View = require_view();
+ var http3 = require("http");
+ var compileETag = require_utils5().compileETag;
+ var compileQueryParser = require_utils5().compileQueryParser;
+ var compileTrust = require_utils5().compileTrust;
+ var deprecate = require_depd()("express");
+ var flatten = require_array_flatten();
+ var merge = require_utils_merge();
+ var resolve18 = require("path").resolve;
+ var setPrototypeOf = require_setprototypeof();
+ var hasOwnProperty2 = Object.prototype.hasOwnProperty;
+ var slice = Array.prototype.slice;
+ var app = exports2 = module2.exports = {};
+ var trustProxyDefaultSymbol = "@@symbol:trust_proxy_default";
+ app.init = /* @__PURE__ */ __name(function init() {
+ this.cache = {};
+ this.engines = {};
+ this.settings = {};
+ this.defaultConfiguration();
+ }, "init");
+ app.defaultConfiguration = /* @__PURE__ */ __name(function defaultConfiguration() {
+ var env5 = "production";
+ this.enable("x-powered-by");
+ this.set("etag", "weak");
+ this.set("env", env5);
+ this.set("query parser", "extended");
+ this.set("subdomain offset", 2);
+ this.set("trust proxy", false);
+ Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
+ configurable: true,
+ value: true
+ });
+ debug("booting in %s mode", env5);
+ this.on("mount", /* @__PURE__ */ __name(function onmount(parent) {
+ if (this.settings[trustProxyDefaultSymbol] === true && typeof parent.settings["trust proxy fn"] === "function") {
+ delete this.settings["trust proxy"];
+ delete this.settings["trust proxy fn"];
+ }
+ setPrototypeOf(this.request, parent.request);
+ setPrototypeOf(this.response, parent.response);
+ setPrototypeOf(this.engines, parent.engines);
+ setPrototypeOf(this.settings, parent.settings);
+ }, "onmount"));
+ this.locals = /* @__PURE__ */ Object.create(null);
+ this.mountpath = "/";
+ this.locals.settings = this.settings;
+ this.set("view", View);
+ this.set("views", resolve18("views"));
+ this.set("jsonp callback name", "callback");
+ if (env5 === "production") {
+ this.enable("view cache");
+ }
+ Object.defineProperty(this, "router", {
+ get: function() {
+ throw new Error("'app.router' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.");
+ }
+ });
+ }, "defaultConfiguration");
+ app.lazyrouter = /* @__PURE__ */ __name(function lazyrouter() {
+ if (!this._router) {
+ this._router = new Router({
+ caseSensitive: this.enabled("case sensitive routing"),
+ strict: this.enabled("strict routing")
+ });
+ this._router.use(query(this.get("query parser fn")));
+ this._router.use(middleware.init(this));
+ }
+ }, "lazyrouter");
+ app.handle = /* @__PURE__ */ __name(function handle(req, res, callback) {
+ var router = this._router;
+ var done = callback || finalhandler(req, res, {
+ env: this.get("env"),
+ onerror: logerror.bind(this)
+ });
+ if (!router) {
+ debug("no routes defined on app");
+ done();
+ return;
+ }
+ router.handle(req, res, done);
+ }, "handle");
+ app.use = /* @__PURE__ */ __name(function use(fn2) {
+ var offset = 0;
+ var path45 = "/";
+ if (typeof fn2 !== "function") {
+ var arg = fn2;
+ while (Array.isArray(arg) && arg.length !== 0) {
+ arg = arg[0];
+ }
+ if (typeof arg !== "function") {
+ offset = 1;
+ path45 = fn2;
+ }
+ }
+ var fns = flatten(slice.call(arguments, offset));
+ if (fns.length === 0) {
+ throw new TypeError("app.use() requires a middleware function");
+ }
+ this.lazyrouter();
+ var router = this._router;
+ fns.forEach(function(fn3) {
+ if (!fn3 || !fn3.handle || !fn3.set) {
+ return router.use(path45, fn3);
+ }
+ debug(".use app under %s", path45);
+ fn3.mountpath = path45;
+ fn3.parent = this;
+ router.use(path45, /* @__PURE__ */ __name(function mounted_app(req, res, next) {
+ var orig = req.app;
+ fn3.handle(req, res, function(err) {
+ setPrototypeOf(req, orig.request);
+ setPrototypeOf(res, orig.response);
+ next(err);
+ });
+ }, "mounted_app"));
+ fn3.emit("mount", this);
+ }, this);
+ return this;
+ }, "use");
+ app.route = /* @__PURE__ */ __name(function route2(path45) {
+ this.lazyrouter();
+ return this._router.route(path45);
+ }, "route");
+ app.engine = /* @__PURE__ */ __name(function engine(ext, fn2) {
+ if (typeof fn2 !== "function") {
+ throw new Error("callback function required");
+ }
+ var extension = ext[0] !== "." ? "." + ext : ext;
+ this.engines[extension] = fn2;
+ return this;
+ }, "engine");
+ app.param = /* @__PURE__ */ __name(function param(name, fn2) {
+ this.lazyrouter();
+ if (Array.isArray(name)) {
+ for (var i = 0; i < name.length; i++) {
+ this.param(name[i], fn2);
+ }
+ return this;
+ }
+ this._router.param(name, fn2);
+ return this;
+ }, "param");
+ app.set = /* @__PURE__ */ __name(function set(setting, val) {
+ if (arguments.length === 1) {
+ var settings = this.settings;
+ while (settings && settings !== Object.prototype) {
+ if (hasOwnProperty2.call(settings, setting)) {
+ return settings[setting];
+ }
+ settings = Object.getPrototypeOf(settings);
+ }
+ return void 0;
+ }
+ debug('set "%s" to %o', setting, val);
+ this.settings[setting] = val;
+ switch (setting) {
+ case "etag":
+ this.set("etag fn", compileETag(val));
+ break;
+ case "query parser":
+ this.set("query parser fn", compileQueryParser(val));
+ break;
+ case "trust proxy":
+ this.set("trust proxy fn", compileTrust(val));
+ Object.defineProperty(this.settings, trustProxyDefaultSymbol, {
+ configurable: true,
+ value: false
+ });
+ break;
+ }
+ return this;
+ }, "set");
+ app.path = /* @__PURE__ */ __name(function path45() {
+ return this.parent ? this.parent.path() + this.mountpath : "";
+ }, "path");
+ app.enabled = /* @__PURE__ */ __name(function enabled(setting) {
+ return Boolean(this.set(setting));
+ }, "enabled");
+ app.disabled = /* @__PURE__ */ __name(function disabled(setting) {
+ return !this.set(setting);
+ }, "disabled");
+ app.enable = /* @__PURE__ */ __name(function enable(setting) {
+ return this.set(setting, true);
+ }, "enable");
+ app.disable = /* @__PURE__ */ __name(function disable(setting) {
+ return this.set(setting, false);
+ }, "disable");
+ methods.forEach(function(method) {
+ app[method] = function(path45) {
+ if (method === "get" && arguments.length === 1) {
+ return this.set(path45);
+ }
+ this.lazyrouter();
+ var route2 = this._router.route(path45);
+ route2[method].apply(route2, slice.call(arguments, 1));
+ return this;
+ };
+ });
+ app.all = /* @__PURE__ */ __name(function all2(path45) {
+ this.lazyrouter();
+ var route2 = this._router.route(path45);
+ var args = slice.call(arguments, 1);
+ for (var i = 0; i < methods.length; i++) {
+ route2[methods[i]].apply(route2, args);
+ }
+ return this;
+ }, "all");
+ app.del = deprecate.function(app.delete, "app.del: Use app.delete instead");
+ app.render = /* @__PURE__ */ __name(function render7(name, options14, callback) {
+ var cache2 = this.cache;
+ var done = callback;
+ var engines = this.engines;
+ var opts = options14;
+ var renderOptions = {};
+ var view;
+ if (typeof options14 === "function") {
+ done = options14;
+ opts = {};
+ }
+ merge(renderOptions, this.locals);
+ if (opts._locals) {
+ merge(renderOptions, opts._locals);
+ }
+ merge(renderOptions, opts);
+ if (renderOptions.cache == null) {
+ renderOptions.cache = this.enabled("view cache");
+ }
+ if (renderOptions.cache) {
+ view = cache2[name];
+ }
+ if (!view) {
+ var View2 = this.get("view");
+ view = new View2(name, {
+ defaultEngine: this.get("view engine"),
+ root: this.get("views"),
+ engines
+ });
+ if (!view.path) {
+ var dirs = Array.isArray(view.root) && view.root.length > 1 ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' : 'directory "' + view.root + '"';
+ var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs);
+ err.view = view;
+ return done(err);
+ }
+ if (renderOptions.cache) {
+ cache2[name] = view;
+ }
+ }
+ tryRender(view, renderOptions, done);
+ }, "render");
+ app.listen = /* @__PURE__ */ __name(function listen() {
+ var server2 = http3.createServer(this);
+ return server2.listen.apply(server2, arguments);
+ }, "listen");
+ function logerror(err) {
+ if (this.get("env") !== "test")
+ console.error(err.stack || err.toString());
+ }
+ __name(logerror, "logerror");
+ function tryRender(view, options14, callback) {
+ try {
+ view.render(options14, callback);
+ } catch (err) {
+ callback(err);
+ }
+ }
+ __name(tryRender, "tryRender");
+ }
+});
+
+// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/charset.js
+var require_charset = __commonJS({
+ "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/charset.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = preferredCharsets;
+ module2.exports.preferredCharsets = preferredCharsets;
+ var simpleCharsetRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
+ function parseAcceptCharset(accept) {
+ var accepts = accept.split(",");
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var charset = parseCharset(accepts[i].trim(), i);
+ if (charset) {
+ accepts[j++] = charset;
+ }
+ }
+ accepts.length = j;
+ return accepts;
+ }
+ __name(parseAcceptCharset, "parseAcceptCharset");
+ function parseCharset(str, i) {
+ var match = simpleCharsetRegExp.exec(str);
+ if (!match)
+ return null;
+ var charset = match[1];
+ var q = 1;
+ if (match[2]) {
+ var params = match[2].split(";");
+ for (var j = 0; j < params.length; j++) {
+ var p = params[j].trim().split("=");
+ if (p[0] === "q") {
+ q = parseFloat(p[1]);
+ break;
+ }
+ }
+ }
+ return {
+ charset,
+ q,
+ i
+ };
+ }
+ __name(parseCharset, "parseCharset");
+ function getCharsetPriority(charset, accepted, index) {
+ var priority = { o: -1, q: 0, s: 0 };
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify(charset, accepted[i], index);
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+ return priority;
+ }
+ __name(getCharsetPriority, "getCharsetPriority");
+ function specify(charset, spec, index) {
+ var s = 0;
+ if (spec.charset.toLowerCase() === charset.toLowerCase()) {
+ s |= 1;
+ } else if (spec.charset !== "*") {
+ return null;
+ }
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s
+ };
+ }
+ __name(specify, "specify");
+ function preferredCharsets(accept, provided) {
+ var accepts = parseAcceptCharset(accept === void 0 ? "*" : accept || "");
+ if (!provided) {
+ return accepts.filter(isQuality).sort(compareSpecs).map(getFullCharset);
+ }
+ var priorities = provided.map(/* @__PURE__ */ __name(function getPriority(type, index) {
+ return getCharsetPriority(type, accepts, index);
+ }, "getPriority"));
+ return priorities.filter(isQuality).sort(compareSpecs).map(/* @__PURE__ */ __name(function getCharset(priority) {
+ return provided[priorities.indexOf(priority)];
+ }, "getCharset"));
+ }
+ __name(preferredCharsets, "preferredCharsets");
+ function compareSpecs(a, b) {
+ return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
+ }
+ __name(compareSpecs, "compareSpecs");
+ function getFullCharset(spec) {
+ return spec.charset;
+ }
+ __name(getFullCharset, "getFullCharset");
+ function isQuality(spec) {
+ return spec.q > 0;
+ }
+ __name(isQuality, "isQuality");
+ }
+});
+
+// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/encoding.js
+var require_encoding2 = __commonJS({
+ "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/encoding.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = preferredEncodings;
+ module2.exports.preferredEncodings = preferredEncodings;
+ var simpleEncodingRegExp = /^\s*([^\s;]+)\s*(?:;(.*))?$/;
+ function parseAcceptEncoding(accept) {
+ var accepts = accept.split(",");
+ var hasIdentity = false;
+ var minQuality = 1;
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var encoding = parseEncoding(accepts[i].trim(), i);
+ if (encoding) {
+ accepts[j++] = encoding;
+ hasIdentity = hasIdentity || specify("identity", encoding);
+ minQuality = Math.min(minQuality, encoding.q || 1);
+ }
+ }
+ if (!hasIdentity) {
+ accepts[j++] = {
+ encoding: "identity",
+ q: minQuality,
+ i
+ };
+ }
+ accepts.length = j;
+ return accepts;
+ }
+ __name(parseAcceptEncoding, "parseAcceptEncoding");
+ function parseEncoding(str, i) {
+ var match = simpleEncodingRegExp.exec(str);
+ if (!match)
+ return null;
+ var encoding = match[1];
+ var q = 1;
+ if (match[2]) {
+ var params = match[2].split(";");
+ for (var j = 0; j < params.length; j++) {
+ var p = params[j].trim().split("=");
+ if (p[0] === "q") {
+ q = parseFloat(p[1]);
+ break;
+ }
+ }
+ }
+ return {
+ encoding,
+ q,
+ i
+ };
+ }
+ __name(parseEncoding, "parseEncoding");
+ function getEncodingPriority(encoding, accepted, index) {
+ var priority = { o: -1, q: 0, s: 0 };
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify(encoding, accepted[i], index);
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+ return priority;
+ }
+ __name(getEncodingPriority, "getEncodingPriority");
+ function specify(encoding, spec, index) {
+ var s = 0;
+ if (spec.encoding.toLowerCase() === encoding.toLowerCase()) {
+ s |= 1;
+ } else if (spec.encoding !== "*") {
+ return null;
+ }
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s
+ };
+ }
+ __name(specify, "specify");
+ function preferredEncodings(accept, provided) {
+ var accepts = parseAcceptEncoding(accept || "");
+ if (!provided) {
+ return accepts.filter(isQuality).sort(compareSpecs).map(getFullEncoding);
+ }
+ var priorities = provided.map(/* @__PURE__ */ __name(function getPriority(type, index) {
+ return getEncodingPriority(type, accepts, index);
+ }, "getPriority"));
+ return priorities.filter(isQuality).sort(compareSpecs).map(/* @__PURE__ */ __name(function getEncoding(priority) {
+ return provided[priorities.indexOf(priority)];
+ }, "getEncoding"));
+ }
+ __name(preferredEncodings, "preferredEncodings");
+ function compareSpecs(a, b) {
+ return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
+ }
+ __name(compareSpecs, "compareSpecs");
+ function getFullEncoding(spec) {
+ return spec.encoding;
+ }
+ __name(getFullEncoding, "getFullEncoding");
+ function isQuality(spec) {
+ return spec.q > 0;
+ }
+ __name(isQuality, "isQuality");
+ }
+});
+
+// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/language.js
+var require_language = __commonJS({
+ "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/language.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = preferredLanguages;
+ module2.exports.preferredLanguages = preferredLanguages;
+ var simpleLanguageRegExp = /^\s*([^\s\-;]+)(?:-([^\s;]+))?\s*(?:;(.*))?$/;
+ function parseAcceptLanguage(accept) {
+ var accepts = accept.split(",");
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var language = parseLanguage(accepts[i].trim(), i);
+ if (language) {
+ accepts[j++] = language;
+ }
+ }
+ accepts.length = j;
+ return accepts;
+ }
+ __name(parseAcceptLanguage, "parseAcceptLanguage");
+ function parseLanguage(str, i) {
+ var match = simpleLanguageRegExp.exec(str);
+ if (!match)
+ return null;
+ var prefix = match[1];
+ var suffix = match[2];
+ var full = prefix;
+ if (suffix)
+ full += "-" + suffix;
+ var q = 1;
+ if (match[3]) {
+ var params = match[3].split(";");
+ for (var j = 0; j < params.length; j++) {
+ var p = params[j].split("=");
+ if (p[0] === "q")
+ q = parseFloat(p[1]);
+ }
+ }
+ return {
+ prefix,
+ suffix,
+ q,
+ i,
+ full
+ };
+ }
+ __name(parseLanguage, "parseLanguage");
+ function getLanguagePriority(language, accepted, index) {
+ var priority = { o: -1, q: 0, s: 0 };
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify(language, accepted[i], index);
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+ return priority;
+ }
+ __name(getLanguagePriority, "getLanguagePriority");
+ function specify(language, spec, index) {
+ var p = parseLanguage(language);
+ if (!p)
+ return null;
+ var s = 0;
+ if (spec.full.toLowerCase() === p.full.toLowerCase()) {
+ s |= 4;
+ } else if (spec.prefix.toLowerCase() === p.full.toLowerCase()) {
+ s |= 2;
+ } else if (spec.full.toLowerCase() === p.prefix.toLowerCase()) {
+ s |= 1;
+ } else if (spec.full !== "*") {
+ return null;
+ }
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s
+ };
+ }
+ __name(specify, "specify");
+ function preferredLanguages(accept, provided) {
+ var accepts = parseAcceptLanguage(accept === void 0 ? "*" : accept || "");
+ if (!provided) {
+ return accepts.filter(isQuality).sort(compareSpecs).map(getFullLanguage);
+ }
+ var priorities = provided.map(/* @__PURE__ */ __name(function getPriority(type, index) {
+ return getLanguagePriority(type, accepts, index);
+ }, "getPriority"));
+ return priorities.filter(isQuality).sort(compareSpecs).map(/* @__PURE__ */ __name(function getLanguage(priority) {
+ return provided[priorities.indexOf(priority)];
+ }, "getLanguage"));
+ }
+ __name(preferredLanguages, "preferredLanguages");
+ function compareSpecs(a, b) {
+ return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
+ }
+ __name(compareSpecs, "compareSpecs");
+ function getFullLanguage(spec) {
+ return spec.full;
+ }
+ __name(getFullLanguage, "getFullLanguage");
+ function isQuality(spec) {
+ return spec.q > 0;
+ }
+ __name(isQuality, "isQuality");
+ }
+});
+
+// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/mediaType.js
+var require_mediaType = __commonJS({
+ "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/lib/mediaType.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = preferredMediaTypes;
+ module2.exports.preferredMediaTypes = preferredMediaTypes;
+ var simpleMediaTypeRegExp = /^\s*([^\s\/;]+)\/([^;\s]+)\s*(?:;(.*))?$/;
+ function parseAccept(accept) {
+ var accepts = splitMediaTypes(accept);
+ for (var i = 0, j = 0; i < accepts.length; i++) {
+ var mediaType = parseMediaType(accepts[i].trim(), i);
+ if (mediaType) {
+ accepts[j++] = mediaType;
+ }
+ }
+ accepts.length = j;
+ return accepts;
+ }
+ __name(parseAccept, "parseAccept");
+ function parseMediaType(str, i) {
+ var match = simpleMediaTypeRegExp.exec(str);
+ if (!match)
+ return null;
+ var params = /* @__PURE__ */ Object.create(null);
+ var q = 1;
+ var subtype = match[2];
+ var type = match[1];
+ if (match[3]) {
+ var kvps = splitParameters(match[3]).map(splitKeyValuePair);
+ for (var j = 0; j < kvps.length; j++) {
+ var pair = kvps[j];
+ var key = pair[0].toLowerCase();
+ var val = pair[1];
+ var value = val && val[0] === '"' && val[val.length - 1] === '"' ? val.substr(1, val.length - 2) : val;
+ if (key === "q") {
+ q = parseFloat(value);
+ break;
+ }
+ params[key] = value;
+ }
+ }
+ return {
+ type,
+ subtype,
+ params,
+ q,
+ i
+ };
+ }
+ __name(parseMediaType, "parseMediaType");
+ function getMediaTypePriority(type, accepted, index) {
+ var priority = { o: -1, q: 0, s: 0 };
+ for (var i = 0; i < accepted.length; i++) {
+ var spec = specify(type, accepted[i], index);
+ if (spec && (priority.s - spec.s || priority.q - spec.q || priority.o - spec.o) < 0) {
+ priority = spec;
+ }
+ }
+ return priority;
+ }
+ __name(getMediaTypePriority, "getMediaTypePriority");
+ function specify(type, spec, index) {
+ var p = parseMediaType(type);
+ var s = 0;
+ if (!p) {
+ return null;
+ }
+ if (spec.type.toLowerCase() == p.type.toLowerCase()) {
+ s |= 4;
+ } else if (spec.type != "*") {
+ return null;
+ }
+ if (spec.subtype.toLowerCase() == p.subtype.toLowerCase()) {
+ s |= 2;
+ } else if (spec.subtype != "*") {
+ return null;
+ }
+ var keys = Object.keys(spec.params);
+ if (keys.length > 0) {
+ if (keys.every(function(k) {
+ return spec.params[k] == "*" || (spec.params[k] || "").toLowerCase() == (p.params[k] || "").toLowerCase();
+ })) {
+ s |= 1;
+ } else {
+ return null;
+ }
+ }
+ return {
+ i: index,
+ o: spec.i,
+ q: spec.q,
+ s
+ };
+ }
+ __name(specify, "specify");
+ function preferredMediaTypes(accept, provided) {
+ var accepts = parseAccept(accept === void 0 ? "*/*" : accept || "");
+ if (!provided) {
+ return accepts.filter(isQuality).sort(compareSpecs).map(getFullType);
+ }
+ var priorities = provided.map(/* @__PURE__ */ __name(function getPriority(type, index) {
+ return getMediaTypePriority(type, accepts, index);
+ }, "getPriority"));
+ return priorities.filter(isQuality).sort(compareSpecs).map(/* @__PURE__ */ __name(function getType3(priority) {
+ return provided[priorities.indexOf(priority)];
+ }, "getType"));
+ }
+ __name(preferredMediaTypes, "preferredMediaTypes");
+ function compareSpecs(a, b) {
+ return b.q - a.q || b.s - a.s || a.o - b.o || a.i - b.i || 0;
+ }
+ __name(compareSpecs, "compareSpecs");
+ function getFullType(spec) {
+ return spec.type + "/" + spec.subtype;
+ }
+ __name(getFullType, "getFullType");
+ function isQuality(spec) {
+ return spec.q > 0;
+ }
+ __name(isQuality, "isQuality");
+ function quoteCount(string) {
+ var count = 0;
+ var index = 0;
+ while ((index = string.indexOf('"', index)) !== -1) {
+ count++;
+ index++;
+ }
+ return count;
+ }
+ __name(quoteCount, "quoteCount");
+ function splitKeyValuePair(str) {
+ var index = str.indexOf("=");
+ var key;
+ var val;
+ if (index === -1) {
+ key = str;
+ } else {
+ key = str.substr(0, index);
+ val = str.substr(index + 1);
+ }
+ return [key, val];
+ }
+ __name(splitKeyValuePair, "splitKeyValuePair");
+ function splitMediaTypes(accept) {
+ var accepts = accept.split(",");
+ for (var i = 1, j = 0; i < accepts.length; i++) {
+ if (quoteCount(accepts[j]) % 2 == 0) {
+ accepts[++j] = accepts[i];
+ } else {
+ accepts[j] += "," + accepts[i];
+ }
+ }
+ accepts.length = j + 1;
+ return accepts;
+ }
+ __name(splitMediaTypes, "splitMediaTypes");
+ function splitParameters(str) {
+ var parameters = str.split(";");
+ for (var i = 1, j = 0; i < parameters.length; i++) {
+ if (quoteCount(parameters[j]) % 2 == 0) {
+ parameters[++j] = parameters[i];
+ } else {
+ parameters[j] += ";" + parameters[i];
+ }
+ }
+ parameters.length = j + 1;
+ for (var i = 0; i < parameters.length; i++) {
+ parameters[i] = parameters[i].trim();
+ }
+ return parameters;
+ }
+ __name(splitParameters, "splitParameters");
+ }
+});
+
+// ../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/index.js
+var require_negotiator = __commonJS({
+ "../../node_modules/.pnpm/negotiator@0.6.3/node_modules/negotiator/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var preferredCharsets = require_charset();
+ var preferredEncodings = require_encoding2();
+ var preferredLanguages = require_language();
+ var preferredMediaTypes = require_mediaType();
+ module2.exports = Negotiator;
+ module2.exports.Negotiator = Negotiator;
+ function Negotiator(request) {
+ if (!(this instanceof Negotiator)) {
+ return new Negotiator(request);
+ }
+ this.request = request;
+ }
+ __name(Negotiator, "Negotiator");
+ Negotiator.prototype.charset = /* @__PURE__ */ __name(function charset(available) {
+ var set = this.charsets(available);
+ return set && set[0];
+ }, "charset");
+ Negotiator.prototype.charsets = /* @__PURE__ */ __name(function charsets(available) {
+ return preferredCharsets(this.request.headers["accept-charset"], available);
+ }, "charsets");
+ Negotiator.prototype.encoding = /* @__PURE__ */ __name(function encoding(available) {
+ var set = this.encodings(available);
+ return set && set[0];
+ }, "encoding");
+ Negotiator.prototype.encodings = /* @__PURE__ */ __name(function encodings(available) {
+ return preferredEncodings(this.request.headers["accept-encoding"], available);
+ }, "encodings");
+ Negotiator.prototype.language = /* @__PURE__ */ __name(function language(available) {
+ var set = this.languages(available);
+ return set && set[0];
+ }, "language");
+ Negotiator.prototype.languages = /* @__PURE__ */ __name(function languages(available) {
+ return preferredLanguages(this.request.headers["accept-language"], available);
+ }, "languages");
+ Negotiator.prototype.mediaType = /* @__PURE__ */ __name(function mediaType(available) {
+ var set = this.mediaTypes(available);
+ return set && set[0];
+ }, "mediaType");
+ Negotiator.prototype.mediaTypes = /* @__PURE__ */ __name(function mediaTypes(available) {
+ return preferredMediaTypes(this.request.headers.accept, available);
+ }, "mediaTypes");
+ Negotiator.prototype.preferredCharset = Negotiator.prototype.charset;
+ Negotiator.prototype.preferredCharsets = Negotiator.prototype.charsets;
+ Negotiator.prototype.preferredEncoding = Negotiator.prototype.encoding;
+ Negotiator.prototype.preferredEncodings = Negotiator.prototype.encodings;
+ Negotiator.prototype.preferredLanguage = Negotiator.prototype.language;
+ Negotiator.prototype.preferredLanguages = Negotiator.prototype.languages;
+ Negotiator.prototype.preferredMediaType = Negotiator.prototype.mediaType;
+ Negotiator.prototype.preferredMediaTypes = Negotiator.prototype.mediaTypes;
+ }
+});
+
+// ../../node_modules/.pnpm/accepts@1.3.8/node_modules/accepts/index.js
+var require_accepts = __commonJS({
+ "../../node_modules/.pnpm/accepts@1.3.8/node_modules/accepts/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var Negotiator = require_negotiator();
+ var mime = require_mime_types();
+ module2.exports = Accepts;
+ function Accepts(req) {
+ if (!(this instanceof Accepts)) {
+ return new Accepts(req);
+ }
+ this.headers = req.headers;
+ this.negotiator = new Negotiator(req);
+ }
+ __name(Accepts, "Accepts");
+ Accepts.prototype.type = Accepts.prototype.types = function(types_) {
+ var types = types_;
+ if (types && !Array.isArray(types)) {
+ types = new Array(arguments.length);
+ for (var i = 0; i < types.length; i++) {
+ types[i] = arguments[i];
+ }
+ }
+ if (!types || types.length === 0) {
+ return this.negotiator.mediaTypes();
+ }
+ if (!this.headers.accept) {
+ return types[0];
+ }
+ var mimes = types.map(extToMime);
+ var accepts = this.negotiator.mediaTypes(mimes.filter(validMime));
+ var first = accepts[0];
+ return first ? types[mimes.indexOf(first)] : false;
+ };
+ Accepts.prototype.encoding = Accepts.prototype.encodings = function(encodings_) {
+ var encodings = encodings_;
+ if (encodings && !Array.isArray(encodings)) {
+ encodings = new Array(arguments.length);
+ for (var i = 0; i < encodings.length; i++) {
+ encodings[i] = arguments[i];
+ }
+ }
+ if (!encodings || encodings.length === 0) {
+ return this.negotiator.encodings();
+ }
+ return this.negotiator.encodings(encodings)[0] || false;
+ };
+ Accepts.prototype.charset = Accepts.prototype.charsets = function(charsets_) {
+ var charsets = charsets_;
+ if (charsets && !Array.isArray(charsets)) {
+ charsets = new Array(arguments.length);
+ for (var i = 0; i < charsets.length; i++) {
+ charsets[i] = arguments[i];
+ }
+ }
+ if (!charsets || charsets.length === 0) {
+ return this.negotiator.charsets();
+ }
+ return this.negotiator.charsets(charsets)[0] || false;
+ };
+ Accepts.prototype.lang = Accepts.prototype.langs = Accepts.prototype.language = Accepts.prototype.languages = function(languages_) {
+ var languages = languages_;
+ if (languages && !Array.isArray(languages)) {
+ languages = new Array(arguments.length);
+ for (var i = 0; i < languages.length; i++) {
+ languages[i] = arguments[i];
+ }
+ }
+ if (!languages || languages.length === 0) {
+ return this.negotiator.languages();
+ }
+ return this.negotiator.languages(languages)[0] || false;
+ };
+ function extToMime(type) {
+ return type.indexOf("/") === -1 ? mime.lookup(type) : type;
+ }
+ __name(extToMime, "extToMime");
+ function validMime(type) {
+ return typeof type === "string";
+ }
+ __name(validMime, "validMime");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/request.js
+var require_request3 = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/request.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var accepts = require_accepts();
+ var deprecate = require_depd()("express");
+ var isIP = require("net").isIP;
+ var typeis = require_type_is();
+ var http3 = require("http");
+ var fresh = require_fresh();
+ var parseRange = require_range_parser();
+ var parse4 = require_parseurl();
+ var proxyaddr = require_proxy_addr();
+ var req = Object.create(http3.IncomingMessage.prototype);
+ module2.exports = req;
+ req.get = req.header = /* @__PURE__ */ __name(function header(name) {
+ if (!name) {
+ throw new TypeError("name argument is required to req.get");
+ }
+ if (typeof name !== "string") {
+ throw new TypeError("name must be a string to req.get");
+ }
+ var lc = name.toLowerCase();
+ switch (lc) {
+ case "referer":
+ case "referrer":
+ return this.headers.referrer || this.headers.referer;
+ default:
+ return this.headers[lc];
+ }
+ }, "header");
+ req.accepts = function() {
+ var accept = accepts(this);
+ return accept.types.apply(accept, arguments);
+ };
+ req.acceptsEncodings = function() {
+ var accept = accepts(this);
+ return accept.encodings.apply(accept, arguments);
+ };
+ req.acceptsEncoding = deprecate.function(
+ req.acceptsEncodings,
+ "req.acceptsEncoding: Use acceptsEncodings instead"
+ );
+ req.acceptsCharsets = function() {
+ var accept = accepts(this);
+ return accept.charsets.apply(accept, arguments);
+ };
+ req.acceptsCharset = deprecate.function(
+ req.acceptsCharsets,
+ "req.acceptsCharset: Use acceptsCharsets instead"
+ );
+ req.acceptsLanguages = function() {
+ var accept = accepts(this);
+ return accept.languages.apply(accept, arguments);
+ };
+ req.acceptsLanguage = deprecate.function(
+ req.acceptsLanguages,
+ "req.acceptsLanguage: Use acceptsLanguages instead"
+ );
+ req.range = /* @__PURE__ */ __name(function range(size, options14) {
+ var range2 = this.get("Range");
+ if (!range2)
+ return;
+ return parseRange(size, range2, options14);
+ }, "range");
+ req.param = /* @__PURE__ */ __name(function param(name, defaultValue) {
+ var params = this.params || {};
+ var body = this.body || {};
+ var query = this.query || {};
+ var args = arguments.length === 1 ? "name" : "name, default";
+ deprecate("req.param(" + args + "): Use req.params, req.body, or req.query instead");
+ if (null != params[name] && params.hasOwnProperty(name))
+ return params[name];
+ if (null != body[name])
+ return body[name];
+ if (null != query[name])
+ return query[name];
+ return defaultValue;
+ }, "param");
+ req.is = /* @__PURE__ */ __name(function is2(types) {
+ var arr = types;
+ if (!Array.isArray(types)) {
+ arr = new Array(arguments.length);
+ for (var i = 0; i < arr.length; i++) {
+ arr[i] = arguments[i];
+ }
+ }
+ return typeis(this, arr);
+ }, "is");
+ defineGetter(req, "protocol", /* @__PURE__ */ __name(function protocol() {
+ var proto = this.connection.encrypted ? "https" : "http";
+ var trust = this.app.get("trust proxy fn");
+ if (!trust(this.connection.remoteAddress, 0)) {
+ return proto;
+ }
+ var header = this.get("X-Forwarded-Proto") || proto;
+ var index = header.indexOf(",");
+ return index !== -1 ? header.substring(0, index).trim() : header.trim();
+ }, "protocol"));
+ defineGetter(req, "secure", /* @__PURE__ */ __name(function secure() {
+ return this.protocol === "https";
+ }, "secure"));
+ defineGetter(req, "ip", /* @__PURE__ */ __name(function ip2() {
+ var trust = this.app.get("trust proxy fn");
+ return proxyaddr(this, trust);
+ }, "ip"));
+ defineGetter(req, "ips", /* @__PURE__ */ __name(function ips() {
+ var trust = this.app.get("trust proxy fn");
+ var addrs = proxyaddr.all(this, trust);
+ addrs.reverse().pop();
+ return addrs;
+ }, "ips"));
+ defineGetter(req, "subdomains", /* @__PURE__ */ __name(function subdomains() {
+ var hostname = this.hostname;
+ if (!hostname)
+ return [];
+ var offset = this.app.get("subdomain offset");
+ var subdomains2 = !isIP(hostname) ? hostname.split(".").reverse() : [hostname];
+ return subdomains2.slice(offset);
+ }, "subdomains"));
+ defineGetter(req, "path", /* @__PURE__ */ __name(function path45() {
+ return parse4(this).pathname;
+ }, "path"));
+ defineGetter(req, "hostname", /* @__PURE__ */ __name(function hostname() {
+ var trust = this.app.get("trust proxy fn");
+ var host = this.get("X-Forwarded-Host");
+ if (!host || !trust(this.connection.remoteAddress, 0)) {
+ host = this.get("Host");
+ } else if (host.indexOf(",") !== -1) {
+ host = host.substring(0, host.indexOf(",")).trimRight();
+ }
+ if (!host)
+ return;
+ var offset = host[0] === "[" ? host.indexOf("]") + 1 : 0;
+ var index = host.indexOf(":", offset);
+ return index !== -1 ? host.substring(0, index) : host;
+ }, "hostname"));
+ defineGetter(req, "host", deprecate.function(/* @__PURE__ */ __name(function host() {
+ return this.hostname;
+ }, "host"), "req.host: Use req.hostname instead"));
+ defineGetter(req, "fresh", function() {
+ var method = this.method;
+ var res = this.res;
+ var status = res.statusCode;
+ if ("GET" !== method && "HEAD" !== method)
+ return false;
+ if (status >= 200 && status < 300 || 304 === status) {
+ return fresh(this.headers, {
+ "etag": res.get("ETag"),
+ "last-modified": res.get("Last-Modified")
+ });
+ }
+ return false;
+ });
+ defineGetter(req, "stale", /* @__PURE__ */ __name(function stale() {
+ return !this.fresh;
+ }, "stale"));
+ defineGetter(req, "xhr", /* @__PURE__ */ __name(function xhr() {
+ var val = this.get("X-Requested-With") || "";
+ return val.toLowerCase() === "xmlhttprequest";
+ }, "xhr"));
+ function defineGetter(obj, name, getter) {
+ Object.defineProperty(obj, name, {
+ configurable: true,
+ enumerable: true,
+ get: getter
+ });
+ }
+ __name(defineGetter, "defineGetter");
+ }
+});
+
+// ../../node_modules/.pnpm/cookie-signature@1.0.6/node_modules/cookie-signature/index.js
+var require_cookie_signature = __commonJS({
+ "../../node_modules/.pnpm/cookie-signature@1.0.6/node_modules/cookie-signature/index.js"(exports2) {
+ init_import_meta_url();
+ var crypto6 = require("crypto");
+ exports2.sign = function(val, secret2) {
+ if ("string" != typeof val)
+ throw new TypeError("Cookie value must be provided as a string.");
+ if ("string" != typeof secret2)
+ throw new TypeError("Secret string must be provided.");
+ return val + "." + crypto6.createHmac("sha256", secret2).update(val).digest("base64").replace(/\=+$/, "");
+ };
+ exports2.unsign = function(val, secret2) {
+ if ("string" != typeof val)
+ throw new TypeError("Signed cookie string must be provided.");
+ if ("string" != typeof secret2)
+ throw new TypeError("Secret string must be provided.");
+ var str = val.slice(0, val.lastIndexOf(".")), mac = exports2.sign(str, secret2);
+ return sha1(mac) == sha1(val) ? str : false;
+ };
+ function sha1(str) {
+ return crypto6.createHash("sha1").update(str).digest("hex");
+ }
+ __name(sha1, "sha1");
+ }
+});
+
+// ../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js
+var require_cookie = __commonJS({
+ "../../node_modules/.pnpm/cookie@0.5.0/node_modules/cookie/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ exports2.parse = parse4;
+ exports2.serialize = serialize;
+ var __toString = Object.prototype.toString;
+ var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;
+ function parse4(str, options14) {
+ if (typeof str !== "string") {
+ throw new TypeError("argument str must be a string");
+ }
+ var obj = {};
+ var opt = options14 || {};
+ var dec = opt.decode || decode;
+ var index = 0;
+ while (index < str.length) {
+ var eqIdx = str.indexOf("=", index);
+ if (eqIdx === -1) {
+ break;
+ }
+ var endIdx = str.indexOf(";", index);
+ if (endIdx === -1) {
+ endIdx = str.length;
+ } else if (endIdx < eqIdx) {
+ index = str.lastIndexOf(";", eqIdx - 1) + 1;
+ continue;
+ }
+ var key = str.slice(index, eqIdx).trim();
+ if (void 0 === obj[key]) {
+ var val = str.slice(eqIdx + 1, endIdx).trim();
+ if (val.charCodeAt(0) === 34) {
+ val = val.slice(1, -1);
+ }
+ obj[key] = tryDecode(val, dec);
+ }
+ index = endIdx + 1;
+ }
+ return obj;
+ }
+ __name(parse4, "parse");
+ function serialize(name, val, options14) {
+ var opt = options14 || {};
+ var enc = opt.encode || encode;
+ if (typeof enc !== "function") {
+ throw new TypeError("option encode is invalid");
+ }
+ if (!fieldContentRegExp.test(name)) {
+ throw new TypeError("argument name is invalid");
+ }
+ var value = enc(val);
+ if (value && !fieldContentRegExp.test(value)) {
+ throw new TypeError("argument val is invalid");
+ }
+ var str = name + "=" + value;
+ if (null != opt.maxAge) {
+ var maxAge = opt.maxAge - 0;
+ if (isNaN(maxAge) || !isFinite(maxAge)) {
+ throw new TypeError("option maxAge is invalid");
+ }
+ str += "; Max-Age=" + Math.floor(maxAge);
+ }
+ if (opt.domain) {
+ if (!fieldContentRegExp.test(opt.domain)) {
+ throw new TypeError("option domain is invalid");
+ }
+ str += "; Domain=" + opt.domain;
+ }
+ if (opt.path) {
+ if (!fieldContentRegExp.test(opt.path)) {
+ throw new TypeError("option path is invalid");
+ }
+ str += "; Path=" + opt.path;
+ }
+ if (opt.expires) {
+ var expires = opt.expires;
+ if (!isDate(expires) || isNaN(expires.valueOf())) {
+ throw new TypeError("option expires is invalid");
+ }
+ str += "; Expires=" + expires.toUTCString();
+ }
+ if (opt.httpOnly) {
+ str += "; HttpOnly";
+ }
+ if (opt.secure) {
+ str += "; Secure";
+ }
+ if (opt.priority) {
+ var priority = typeof opt.priority === "string" ? opt.priority.toLowerCase() : opt.priority;
+ switch (priority) {
+ case "low":
+ str += "; Priority=Low";
+ break;
+ case "medium":
+ str += "; Priority=Medium";
+ break;
+ case "high":
+ str += "; Priority=High";
+ break;
+ default:
+ throw new TypeError("option priority is invalid");
+ }
+ }
+ if (opt.sameSite) {
+ var sameSite = typeof opt.sameSite === "string" ? opt.sameSite.toLowerCase() : opt.sameSite;
+ switch (sameSite) {
+ case true:
+ str += "; SameSite=Strict";
+ break;
+ case "lax":
+ str += "; SameSite=Lax";
+ break;
+ case "strict":
+ str += "; SameSite=Strict";
+ break;
+ case "none":
+ str += "; SameSite=None";
+ break;
+ default:
+ throw new TypeError("option sameSite is invalid");
+ }
+ }
+ return str;
+ }
+ __name(serialize, "serialize");
+ function decode(str) {
+ return str.indexOf("%") !== -1 ? decodeURIComponent(str) : str;
+ }
+ __name(decode, "decode");
+ function encode(val) {
+ return encodeURIComponent(val);
+ }
+ __name(encode, "encode");
+ function isDate(val) {
+ return __toString.call(val) === "[object Date]" || val instanceof Date;
+ }
+ __name(isDate, "isDate");
+ function tryDecode(str, decode2) {
+ try {
+ return decode2(str);
+ } catch (e2) {
+ return str;
+ }
+ }
+ __name(tryDecode, "tryDecode");
+ }
+});
+
+// ../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js
+var require_vary = __commonJS({
+ "../../node_modules/.pnpm/vary@1.1.2/node_modules/vary/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = vary;
+ module2.exports.append = append;
+ var FIELD_NAME_REGEXP = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
+ function append(header, field) {
+ if (typeof header !== "string") {
+ throw new TypeError("header argument is required");
+ }
+ if (!field) {
+ throw new TypeError("field argument is required");
+ }
+ var fields = !Array.isArray(field) ? parse4(String(field)) : field;
+ for (var j = 0; j < fields.length; j++) {
+ if (!FIELD_NAME_REGEXP.test(fields[j])) {
+ throw new TypeError("field argument contains an invalid header name");
+ }
+ }
+ if (header === "*") {
+ return header;
+ }
+ var val = header;
+ var vals = parse4(header.toLowerCase());
+ if (fields.indexOf("*") !== -1 || vals.indexOf("*") !== -1) {
+ return "*";
+ }
+ for (var i = 0; i < fields.length; i++) {
+ var fld = fields[i].toLowerCase();
+ if (vals.indexOf(fld) === -1) {
+ vals.push(fld);
+ val = val ? val + ", " + fields[i] : fields[i];
+ }
+ }
+ return val;
+ }
+ __name(append, "append");
+ function parse4(header) {
+ var end = 0;
+ var list = [];
+ var start = 0;
+ for (var i = 0, len = header.length; i < len; i++) {
+ switch (header.charCodeAt(i)) {
+ case 32:
+ if (start === end) {
+ start = end = i + 1;
+ }
+ break;
+ case 44:
+ list.push(header.substring(start, end));
+ start = end = i + 1;
+ break;
+ default:
+ end = i + 1;
+ break;
+ }
+ }
+ list.push(header.substring(start, end));
+ return list;
+ }
+ __name(parse4, "parse");
+ function vary(res, field) {
+ if (!res || !res.getHeader || !res.setHeader) {
+ throw new TypeError("res argument is required");
+ }
+ var val = res.getHeader("Vary") || "";
+ var header = Array.isArray(val) ? val.join(", ") : String(val);
+ if (val = append(header, field)) {
+ res.setHeader("Vary", val);
+ }
+ }
+ __name(vary, "vary");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/response.js
+var require_response2 = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/response.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var Buffer3 = require_safe_buffer().Buffer;
+ var contentDisposition = require_content_disposition();
+ var createError = require_http_errors();
+ var deprecate = require_depd()("express");
+ var encodeUrl = require_encodeurl();
+ var escapeHtml = require_escape_html();
+ var http3 = require("http");
+ var isAbsolute = require_utils5().isAbsolute;
+ var onFinished = require_on_finished();
+ var path45 = require("path");
+ var statuses = require_statuses();
+ var merge = require_utils_merge();
+ var sign = require_cookie_signature().sign;
+ var normalizeType = require_utils5().normalizeType;
+ var normalizeTypes = require_utils5().normalizeTypes;
+ var setCharset = require_utils5().setCharset;
+ var cookie = require_cookie();
+ var send = require_send();
+ var extname4 = path45.extname;
+ var mime = send.mime;
+ var resolve18 = path45.resolve;
+ var vary = require_vary();
+ var res = Object.create(http3.ServerResponse.prototype);
+ module2.exports = res;
+ var charsetRegExp = /;\s*charset\s*=/;
+ res.status = /* @__PURE__ */ __name(function status(code) {
+ if ((typeof code === "string" || Math.floor(code) !== code) && code > 99 && code < 1e3) {
+ deprecate("res.status(" + JSON.stringify(code) + "): use res.status(" + Math.floor(code) + ") instead");
+ }
+ this.statusCode = code;
+ return this;
+ }, "status");
+ res.links = function(links) {
+ var link = this.get("Link") || "";
+ if (link)
+ link += ", ";
+ return this.set("Link", link + Object.keys(links).map(function(rel) {
+ return "<" + links[rel] + '>; rel="' + rel + '"';
+ }).join(", "));
+ };
+ res.send = /* @__PURE__ */ __name(function send2(body) {
+ var chunk = body;
+ var encoding;
+ var req = this.req;
+ var type;
+ var app = this.app;
+ if (arguments.length === 2) {
+ if (typeof arguments[0] !== "number" && typeof arguments[1] === "number") {
+ deprecate("res.send(body, status): Use res.status(status).send(body) instead");
+ this.statusCode = arguments[1];
+ } else {
+ deprecate("res.send(status, body): Use res.status(status).send(body) instead");
+ this.statusCode = arguments[0];
+ chunk = arguments[1];
+ }
+ }
+ if (typeof chunk === "number" && arguments.length === 1) {
+ if (!this.get("Content-Type")) {
+ this.type("txt");
+ }
+ deprecate("res.send(status): Use res.sendStatus(status) instead");
+ this.statusCode = chunk;
+ chunk = statuses.message[chunk];
+ }
+ switch (typeof chunk) {
+ case "string":
+ if (!this.get("Content-Type")) {
+ this.type("html");
+ }
+ break;
+ case "boolean":
+ case "number":
+ case "object":
+ if (chunk === null) {
+ chunk = "";
+ } else if (Buffer3.isBuffer(chunk)) {
+ if (!this.get("Content-Type")) {
+ this.type("bin");
+ }
+ } else {
+ return this.json(chunk);
+ }
+ break;
+ }
+ if (typeof chunk === "string") {
+ encoding = "utf8";
+ type = this.get("Content-Type");
+ if (typeof type === "string") {
+ this.set("Content-Type", setCharset(type, "utf-8"));
+ }
+ }
+ var etagFn = app.get("etag fn");
+ var generateETag = !this.get("ETag") && typeof etagFn === "function";
+ var len;
+ if (chunk !== void 0) {
+ if (Buffer3.isBuffer(chunk)) {
+ len = chunk.length;
+ } else if (!generateETag && chunk.length < 1e3) {
+ len = Buffer3.byteLength(chunk, encoding);
+ } else {
+ chunk = Buffer3.from(chunk, encoding);
+ encoding = void 0;
+ len = chunk.length;
+ }
+ this.set("Content-Length", len);
+ }
+ var etag;
+ if (generateETag && len !== void 0) {
+ if (etag = etagFn(chunk, encoding)) {
+ this.set("ETag", etag);
+ }
+ }
+ if (req.fresh)
+ this.statusCode = 304;
+ if (204 === this.statusCode || 304 === this.statusCode) {
+ this.removeHeader("Content-Type");
+ this.removeHeader("Content-Length");
+ this.removeHeader("Transfer-Encoding");
+ chunk = "";
+ }
+ if (this.statusCode === 205) {
+ this.set("Content-Length", "0");
+ this.removeHeader("Transfer-Encoding");
+ chunk = "";
+ }
+ if (req.method === "HEAD") {
+ this.end();
+ } else {
+ this.end(chunk, encoding);
+ }
+ return this;
+ }, "send");
+ res.json = /* @__PURE__ */ __name(function json(obj) {
+ var val = obj;
+ if (arguments.length === 2) {
+ if (typeof arguments[1] === "number") {
+ deprecate("res.json(obj, status): Use res.status(status).json(obj) instead");
+ this.statusCode = arguments[1];
+ } else {
+ deprecate("res.json(status, obj): Use res.status(status).json(obj) instead");
+ this.statusCode = arguments[0];
+ val = arguments[1];
+ }
+ }
+ var app = this.app;
+ var escape2 = app.get("json escape");
+ var replacer2 = app.get("json replacer");
+ var spaces = app.get("json spaces");
+ var body = stringify(val, replacer2, spaces, escape2);
+ if (!this.get("Content-Type")) {
+ this.set("Content-Type", "application/json");
+ }
+ return this.send(body);
+ }, "json");
+ res.jsonp = /* @__PURE__ */ __name(function jsonp(obj) {
+ var val = obj;
+ if (arguments.length === 2) {
+ if (typeof arguments[1] === "number") {
+ deprecate("res.jsonp(obj, status): Use res.status(status).jsonp(obj) instead");
+ this.statusCode = arguments[1];
+ } else {
+ deprecate("res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead");
+ this.statusCode = arguments[0];
+ val = arguments[1];
+ }
+ }
+ var app = this.app;
+ var escape2 = app.get("json escape");
+ var replacer2 = app.get("json replacer");
+ var spaces = app.get("json spaces");
+ var body = stringify(val, replacer2, spaces, escape2);
+ var callback = this.req.query[app.get("jsonp callback name")];
+ if (!this.get("Content-Type")) {
+ this.set("X-Content-Type-Options", "nosniff");
+ this.set("Content-Type", "application/json");
+ }
+ if (Array.isArray(callback)) {
+ callback = callback[0];
+ }
+ if (typeof callback === "string" && callback.length !== 0) {
+ this.set("X-Content-Type-Options", "nosniff");
+ this.set("Content-Type", "text/javascript");
+ callback = callback.replace(/[^\[\]\w$.]/g, "");
+ if (body === void 0) {
+ body = "";
+ } else if (typeof body === "string") {
+ body = body.replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
+ }
+ body = "/**/ typeof " + callback + " === 'function' && " + callback + "(" + body + ");";
+ }
+ return this.send(body);
+ }, "jsonp");
+ res.sendStatus = /* @__PURE__ */ __name(function sendStatus(statusCode) {
+ var body = statuses.message[statusCode] || String(statusCode);
+ this.statusCode = statusCode;
+ this.type("txt");
+ return this.send(body);
+ }, "sendStatus");
+ res.sendFile = /* @__PURE__ */ __name(function sendFile(path46, options14, callback) {
+ var done = callback;
+ var req = this.req;
+ var res2 = this;
+ var next = req.next;
+ var opts = options14 || {};
+ if (!path46) {
+ throw new TypeError("path argument is required to res.sendFile");
+ }
+ if (typeof path46 !== "string") {
+ throw new TypeError("path must be a string to res.sendFile");
+ }
+ if (typeof options14 === "function") {
+ done = options14;
+ opts = {};
+ }
+ if (!opts.root && !isAbsolute(path46)) {
+ throw new TypeError("path must be absolute or specify root to res.sendFile");
+ }
+ var pathname = encodeURI(path46);
+ var file = send(req, pathname, opts);
+ sendfile(res2, file, opts, function(err) {
+ if (done)
+ return done(err);
+ if (err && err.code === "EISDIR")
+ return next();
+ if (err && err.code !== "ECONNABORTED" && err.syscall !== "write") {
+ next(err);
+ }
+ });
+ }, "sendFile");
+ res.sendfile = function(path46, options14, callback) {
+ var done = callback;
+ var req = this.req;
+ var res2 = this;
+ var next = req.next;
+ var opts = options14 || {};
+ if (typeof options14 === "function") {
+ done = options14;
+ opts = {};
+ }
+ var file = send(req, path46, opts);
+ sendfile(res2, file, opts, function(err) {
+ if (done)
+ return done(err);
+ if (err && err.code === "EISDIR")
+ return next();
+ if (err && err.code !== "ECONNABORTED" && err.syscall !== "write") {
+ next(err);
+ }
+ });
+ };
+ res.sendfile = deprecate.function(
+ res.sendfile,
+ "res.sendfile: Use res.sendFile instead"
+ );
+ res.download = /* @__PURE__ */ __name(function download(path46, filename, options14, callback) {
+ var done = callback;
+ var name = filename;
+ var opts = options14 || null;
+ if (typeof filename === "function") {
+ done = filename;
+ name = null;
+ opts = null;
+ } else if (typeof options14 === "function") {
+ done = options14;
+ opts = null;
+ }
+ if (typeof filename === "object" && (typeof options14 === "function" || options14 === void 0)) {
+ name = null;
+ opts = filename;
+ }
+ var headers = {
+ "Content-Disposition": contentDisposition(name || path46)
+ };
+ if (opts && opts.headers) {
+ var keys = Object.keys(opts.headers);
+ for (var i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ if (key.toLowerCase() !== "content-disposition") {
+ headers[key] = opts.headers[key];
+ }
+ }
+ }
+ opts = Object.create(opts);
+ opts.headers = headers;
+ var fullPath = !opts.root ? resolve18(path46) : path46;
+ return this.sendFile(fullPath, opts, done);
+ }, "download");
+ res.contentType = res.type = /* @__PURE__ */ __name(function contentType(type) {
+ var ct = type.indexOf("/") === -1 ? mime.lookup(type) : type;
+ return this.set("Content-Type", ct);
+ }, "contentType");
+ res.format = function(obj) {
+ var req = this.req;
+ var next = req.next;
+ var keys = Object.keys(obj).filter(function(v) {
+ return v !== "default";
+ });
+ var key = keys.length > 0 ? req.accepts(keys) : false;
+ this.vary("Accept");
+ if (key) {
+ this.set("Content-Type", normalizeType(key).value);
+ obj[key](req, this, next);
+ } else if (obj.default) {
+ obj.default(req, this, next);
+ } else {
+ next(createError(406, {
+ types: normalizeTypes(keys).map(function(o) {
+ return o.value;
+ })
+ }));
+ }
+ return this;
+ };
+ res.attachment = /* @__PURE__ */ __name(function attachment(filename) {
+ if (filename) {
+ this.type(extname4(filename));
+ }
+ this.set("Content-Disposition", contentDisposition(filename));
+ return this;
+ }, "attachment");
+ res.append = /* @__PURE__ */ __name(function append(field, val) {
+ var prev = this.get(field);
+ var value = val;
+ if (prev) {
+ value = Array.isArray(prev) ? prev.concat(val) : Array.isArray(val) ? [prev].concat(val) : [prev, val];
+ }
+ return this.set(field, value);
+ }, "append");
+ res.set = res.header = /* @__PURE__ */ __name(function header(field, val) {
+ if (arguments.length === 2) {
+ var value = Array.isArray(val) ? val.map(String) : String(val);
+ if (field.toLowerCase() === "content-type") {
+ if (Array.isArray(value)) {
+ throw new TypeError("Content-Type cannot be set to an Array");
+ }
+ if (!charsetRegExp.test(value)) {
+ var charset = mime.charsets.lookup(value.split(";")[0]);
+ if (charset)
+ value += "; charset=" + charset.toLowerCase();
+ }
+ }
+ this.setHeader(field, value);
+ } else {
+ for (var key in field) {
+ this.set(key, field[key]);
+ }
+ }
+ return this;
+ }, "header");
+ res.get = function(field) {
+ return this.getHeader(field);
+ };
+ res.clearCookie = /* @__PURE__ */ __name(function clearCookie(name, options14) {
+ var opts = merge({ expires: /* @__PURE__ */ new Date(1), path: "/" }, options14);
+ return this.cookie(name, "", opts);
+ }, "clearCookie");
+ res.cookie = function(name, value, options14) {
+ var opts = merge({}, options14);
+ var secret2 = this.req.secret;
+ var signed = opts.signed;
+ if (signed && !secret2) {
+ throw new Error('cookieParser("secret") required for signed cookies');
+ }
+ var val = typeof value === "object" ? "j:" + JSON.stringify(value) : String(value);
+ if (signed) {
+ val = "s:" + sign(val, secret2);
+ }
+ if (opts.maxAge != null) {
+ var maxAge = opts.maxAge - 0;
+ if (!isNaN(maxAge)) {
+ opts.expires = new Date(Date.now() + maxAge);
+ opts.maxAge = Math.floor(maxAge / 1e3);
+ }
+ }
+ if (opts.path == null) {
+ opts.path = "/";
+ }
+ this.append("Set-Cookie", cookie.serialize(name, String(val), opts));
+ return this;
+ };
+ res.location = /* @__PURE__ */ __name(function location(url3) {
+ var loc = url3;
+ if (url3 === "back") {
+ loc = this.req.get("Referrer") || "/";
+ }
+ return this.set("Location", encodeUrl(loc));
+ }, "location");
+ res.redirect = /* @__PURE__ */ __name(function redirect(url3) {
+ var address = url3;
+ var body;
+ var status = 302;
+ if (arguments.length === 2) {
+ if (typeof arguments[0] === "number") {
+ status = arguments[0];
+ address = arguments[1];
+ } else {
+ deprecate("res.redirect(url, status): Use res.redirect(status, url) instead");
+ status = arguments[1];
+ }
+ }
+ address = this.location(address).get("Location");
+ this.format({
+ text: function() {
+ body = statuses.message[status] + ". Redirecting to " + address;
+ },
+ html: function() {
+ var u = escapeHtml(address);
+ body = "" + statuses.message[status] + '. Redirecting to ' + u + "
";
+ },
+ default: function() {
+ body = "";
+ }
+ });
+ this.statusCode = status;
+ this.set("Content-Length", Buffer3.byteLength(body));
+ if (this.req.method === "HEAD") {
+ this.end();
+ } else {
+ this.end(body);
+ }
+ }, "redirect");
+ res.vary = function(field) {
+ if (!field || Array.isArray(field) && !field.length) {
+ deprecate("res.vary(): Provide a field name");
+ return this;
+ }
+ vary(this, field);
+ return this;
+ };
+ res.render = /* @__PURE__ */ __name(function render7(view, options14, callback) {
+ var app = this.req.app;
+ var done = callback;
+ var opts = options14 || {};
+ var req = this.req;
+ var self2 = this;
+ if (typeof options14 === "function") {
+ done = options14;
+ opts = {};
+ }
+ opts._locals = self2.locals;
+ done = done || function(err, str) {
+ if (err)
+ return req.next(err);
+ self2.send(str);
+ };
+ app.render(view, opts, done);
+ }, "render");
+ function sendfile(res2, file, options14, callback) {
+ var done = false;
+ var streaming;
+ function onaborted() {
+ if (done)
+ return;
+ done = true;
+ var err = new Error("Request aborted");
+ err.code = "ECONNABORTED";
+ callback(err);
+ }
+ __name(onaborted, "onaborted");
+ function ondirectory() {
+ if (done)
+ return;
+ done = true;
+ var err = new Error("EISDIR, read");
+ err.code = "EISDIR";
+ callback(err);
+ }
+ __name(ondirectory, "ondirectory");
+ function onerror(err) {
+ if (done)
+ return;
+ done = true;
+ callback(err);
+ }
+ __name(onerror, "onerror");
+ function onend() {
+ if (done)
+ return;
+ done = true;
+ callback();
+ }
+ __name(onend, "onend");
+ function onfile() {
+ streaming = false;
+ }
+ __name(onfile, "onfile");
+ function onfinish(err) {
+ if (err && err.code === "ECONNRESET")
+ return onaborted();
+ if (err)
+ return onerror(err);
+ if (done)
+ return;
+ setImmediate(function() {
+ if (streaming !== false && !done) {
+ onaborted();
+ return;
+ }
+ if (done)
+ return;
+ done = true;
+ callback();
+ });
+ }
+ __name(onfinish, "onfinish");
+ function onstream() {
+ streaming = true;
+ }
+ __name(onstream, "onstream");
+ file.on("directory", ondirectory);
+ file.on("end", onend);
+ file.on("error", onerror);
+ file.on("file", onfile);
+ file.on("stream", onstream);
+ onFinished(res2, onfinish);
+ if (options14.headers) {
+ file.on("headers", /* @__PURE__ */ __name(function headers(res3) {
+ var obj = options14.headers;
+ var keys = Object.keys(obj);
+ for (var i = 0; i < keys.length; i++) {
+ var k = keys[i];
+ res3.setHeader(k, obj[k]);
+ }
+ }, "headers"));
+ }
+ file.pipe(res2);
+ }
+ __name(sendfile, "sendfile");
+ function stringify(value, replacer2, spaces, escape2) {
+ var json = replacer2 || spaces ? JSON.stringify(value, replacer2, spaces) : JSON.stringify(value);
+ if (escape2 && typeof json === "string") {
+ json = json.replace(/[<>&]/g, function(c) {
+ switch (c.charCodeAt(0)) {
+ case 60:
+ return "\\u003c";
+ case 62:
+ return "\\u003e";
+ case 38:
+ return "\\u0026";
+ default:
+ return c;
+ }
+ });
+ }
+ return json;
+ }
+ __name(stringify, "stringify");
+ }
+});
+
+// ../../node_modules/.pnpm/serve-static@1.15.0_supports-color@9.2.2/node_modules/serve-static/index.js
+var require_serve_static = __commonJS({
+ "../../node_modules/.pnpm/serve-static@1.15.0_supports-color@9.2.2/node_modules/serve-static/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var encodeUrl = require_encodeurl();
+ var escapeHtml = require_escape_html();
+ var parseUrl = require_parseurl();
+ var resolve18 = require("path").resolve;
+ var send = require_send();
+ var url3 = require("url");
+ module2.exports = serveStatic2;
+ module2.exports.mime = send.mime;
+ function serveStatic2(root, options14) {
+ if (!root) {
+ throw new TypeError("root path required");
+ }
+ if (typeof root !== "string") {
+ throw new TypeError("root path must be a string");
+ }
+ var opts = Object.create(options14 || null);
+ var fallthrough = opts.fallthrough !== false;
+ var redirect = opts.redirect !== false;
+ var setHeaders = opts.setHeaders;
+ if (setHeaders && typeof setHeaders !== "function") {
+ throw new TypeError("option setHeaders must be function");
+ }
+ opts.maxage = opts.maxage || opts.maxAge || 0;
+ opts.root = resolve18(root);
+ var onDirectory = redirect ? createRedirectDirectoryListener() : createNotFoundDirectoryListener();
+ return /* @__PURE__ */ __name(function serveStatic3(req, res, next) {
+ if (req.method !== "GET" && req.method !== "HEAD") {
+ if (fallthrough) {
+ return next();
+ }
+ res.statusCode = 405;
+ res.setHeader("Allow", "GET, HEAD");
+ res.setHeader("Content-Length", "0");
+ res.end();
+ return;
+ }
+ var forwardError = !fallthrough;
+ var originalUrl = parseUrl.original(req);
+ var path45 = parseUrl(req).pathname;
+ if (path45 === "/" && originalUrl.pathname.substr(-1) !== "/") {
+ path45 = "";
+ }
+ var stream2 = send(req, path45, opts);
+ stream2.on("directory", onDirectory);
+ if (setHeaders) {
+ stream2.on("headers", setHeaders);
+ }
+ if (fallthrough) {
+ stream2.on("file", /* @__PURE__ */ __name(function onFile() {
+ forwardError = true;
+ }, "onFile"));
+ }
+ stream2.on("error", /* @__PURE__ */ __name(function error(err) {
+ if (forwardError || !(err.statusCode < 500)) {
+ next(err);
+ return;
+ }
+ next();
+ }, "error"));
+ stream2.pipe(res);
+ }, "serveStatic");
+ }
+ __name(serveStatic2, "serveStatic");
+ function collapseLeadingSlashes(str) {
+ for (var i = 0; i < str.length; i++) {
+ if (str.charCodeAt(i) !== 47) {
+ break;
+ }
+ }
+ return i > 1 ? "/" + str.substr(i) : str;
+ }
+ __name(collapseLeadingSlashes, "collapseLeadingSlashes");
+ function createHtmlDocument(title, body) {
+ return '\n\n\n\n' + title + "\n\n\n" + body + "
\n\n\n";
+ }
+ __name(createHtmlDocument, "createHtmlDocument");
+ function createNotFoundDirectoryListener() {
+ return /* @__PURE__ */ __name(function notFound() {
+ this.error(404);
+ }, "notFound");
+ }
+ __name(createNotFoundDirectoryListener, "createNotFoundDirectoryListener");
+ function createRedirectDirectoryListener() {
+ return /* @__PURE__ */ __name(function redirect(res) {
+ if (this.hasTrailingSlash()) {
+ this.error(404);
+ return;
+ }
+ var originalUrl = parseUrl.original(this.req);
+ originalUrl.path = null;
+ originalUrl.pathname = collapseLeadingSlashes(originalUrl.pathname + "/");
+ var loc = encodeUrl(url3.format(originalUrl));
+ var doc = createHtmlDocument("Redirecting", 'Redirecting to ' + escapeHtml(loc) + "");
+ res.statusCode = 301;
+ res.setHeader("Content-Type", "text/html; charset=UTF-8");
+ res.setHeader("Content-Length", Buffer.byteLength(doc));
+ res.setHeader("Content-Security-Policy", "default-src 'none'");
+ res.setHeader("X-Content-Type-Options", "nosniff");
+ res.setHeader("Location", loc);
+ res.end(doc);
+ }, "redirect");
+ }
+ __name(createRedirectDirectoryListener, "createRedirectDirectoryListener");
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/express.js
+var require_express = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/lib/express.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var bodyParser2 = require_body_parser();
+ var EventEmitter3 = require("events").EventEmitter;
+ var mixin3 = require_merge_descriptors();
+ var proto = require_application();
+ var Route = require_route3();
+ var Router = require_router();
+ var req = require_request3();
+ var res = require_response2();
+ exports2 = module2.exports = createApplication;
+ function createApplication() {
+ var app = /* @__PURE__ */ __name(function(req2, res2, next) {
+ app.handle(req2, res2, next);
+ }, "app");
+ mixin3(app, EventEmitter3.prototype, false);
+ mixin3(app, proto, false);
+ app.request = Object.create(req, {
+ app: { configurable: true, enumerable: true, writable: true, value: app }
+ });
+ app.response = Object.create(res, {
+ app: { configurable: true, enumerable: true, writable: true, value: app }
+ });
+ app.init();
+ return app;
+ }
+ __name(createApplication, "createApplication");
+ exports2.application = proto;
+ exports2.request = req;
+ exports2.response = res;
+ exports2.Route = Route;
+ exports2.Router = Router;
+ exports2.json = bodyParser2.json;
+ exports2.query = require_query();
+ exports2.raw = bodyParser2.raw;
+ exports2.static = require_serve_static();
+ exports2.text = bodyParser2.text;
+ exports2.urlencoded = bodyParser2.urlencoded;
+ var removedMiddlewares = [
+ "bodyParser",
+ "compress",
+ "cookieSession",
+ "session",
+ "logger",
+ "cookieParser",
+ "favicon",
+ "responseTime",
+ "errorHandler",
+ "timeout",
+ "methodOverride",
+ "vhost",
+ "csrf",
+ "directory",
+ "limit",
+ "multipart",
+ "staticCache"
+ ];
+ removedMiddlewares.forEach(function(name) {
+ Object.defineProperty(exports2, name, {
+ get: function() {
+ throw new Error("Most middleware (like " + name + ") is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.");
+ },
+ configurable: true
+ });
+ });
+ }
+});
+
+// ../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/index.js
+var require_express2 = __commonJS({
+ "../../node_modules/.pnpm/express@4.18.1_supports-color@9.2.2/node_modules/express/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = require_express();
+ }
+});
+
+// ../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js
+var require_p_finally = __commonJS({
+ "../../node_modules/.pnpm/p-finally@1.0.0/node_modules/p-finally/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = (promise, onFinally) => {
+ onFinally = onFinally || (() => {
+ });
+ return promise.then(
+ (val) => new Promise((resolve18) => {
+ resolve18(onFinally());
+ }).then(() => val),
+ (err) => new Promise((resolve18) => {
+ resolve18(onFinally());
+ }).then(() => {
+ throw err;
+ })
+ );
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js
+var require_p_timeout = __commonJS({
+ "../../node_modules/.pnpm/p-timeout@3.2.0/node_modules/p-timeout/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var pFinally = require_p_finally();
+ var TimeoutError2 = class extends Error {
+ constructor(message) {
+ super(message);
+ this.name = "TimeoutError";
+ }
+ };
+ __name(TimeoutError2, "TimeoutError");
+ var pTimeout2 = /* @__PURE__ */ __name((promise, milliseconds, fallback) => new Promise((resolve18, reject) => {
+ if (typeof milliseconds !== "number" || milliseconds < 0) {
+ throw new TypeError("Expected `milliseconds` to be a positive number");
+ }
+ if (milliseconds === Infinity) {
+ resolve18(promise);
+ return;
+ }
+ const timer = setTimeout(() => {
+ if (typeof fallback === "function") {
+ try {
+ resolve18(fallback());
+ } catch (error) {
+ reject(error);
+ }
+ return;
+ }
+ const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`;
+ const timeoutError2 = fallback instanceof Error ? fallback : new TimeoutError2(message);
+ if (typeof promise.cancel === "function") {
+ promise.cancel();
+ }
+ reject(timeoutError2);
+ }, milliseconds);
+ pFinally(
+ // eslint-disable-next-line promise/prefer-await-to-then
+ promise.then(resolve18, reject),
+ () => {
+ clearTimeout(timer);
+ }
+ );
+ }), "pTimeout");
+ module2.exports = pTimeout2;
+ module2.exports.default = pTimeout2;
+ module2.exports.TimeoutError = TimeoutError2;
+ }
+});
+
+// ../../node_modules/.pnpm/p-wait-for@3.2.0/node_modules/p-wait-for/index.js
+var require_p_wait_for = __commonJS({
+ "../../node_modules/.pnpm/p-wait-for@3.2.0/node_modules/p-wait-for/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var pTimeout2 = require_p_timeout();
+ var pWaitFor = /* @__PURE__ */ __name(async (condition, options14) => {
+ options14 = {
+ interval: 20,
+ timeout: Infinity,
+ leadingCheck: true,
+ ...options14
+ };
+ let retryTimeout;
+ const promise = new Promise((resolve18, reject) => {
+ const check = /* @__PURE__ */ __name(async () => {
+ try {
+ const value = await condition();
+ if (typeof value !== "boolean") {
+ throw new TypeError("Expected condition to return a boolean");
+ }
+ if (value === true) {
+ resolve18();
+ } else {
+ retryTimeout = setTimeout(check, options14.interval);
+ }
+ } catch (error) {
+ reject(error);
+ }
+ }, "check");
+ if (options14.leadingCheck) {
+ check();
+ } else {
+ retryTimeout = setTimeout(check, options14.interval);
+ }
+ });
+ if (options14.timeout !== Infinity) {
+ try {
+ return await pTimeout2(promise, options14.timeout);
+ } catch (error) {
+ if (retryTimeout) {
+ clearTimeout(retryTimeout);
+ }
+ throw error;
+ }
+ }
+ return promise;
+ }, "pWaitFor");
+ module2.exports = pWaitFor;
+ module2.exports.default = pWaitFor;
+ }
+});
+
+// ../../node_modules/.pnpm/boolean@3.2.0/node_modules/boolean/build/lib/boolean.js
+var require_boolean = __commonJS({
+ "../../node_modules/.pnpm/boolean@3.2.0/node_modules/boolean/build/lib/boolean.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.boolean = void 0;
+ var boolean = /* @__PURE__ */ __name(function(value) {
+ switch (Object.prototype.toString.call(value)) {
+ case "[object String]":
+ return ["true", "t", "yes", "y", "on", "1"].includes(value.trim().toLowerCase());
+ case "[object Number]":
+ return value.valueOf() === 1;
+ case "[object Boolean]":
+ return value.valueOf();
+ default:
+ return false;
+ }
+ }, "boolean");
+ exports2.boolean = boolean;
+ }
+});
+
+// ../../node_modules/.pnpm/boolean@3.2.0/node_modules/boolean/build/lib/isBooleanable.js
+var require_isBooleanable = __commonJS({
+ "../../node_modules/.pnpm/boolean@3.2.0/node_modules/boolean/build/lib/isBooleanable.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.isBooleanable = void 0;
+ var isBooleanable = /* @__PURE__ */ __name(function(value) {
+ switch (Object.prototype.toString.call(value)) {
+ case "[object String]":
+ return [
+ "true",
+ "t",
+ "yes",
+ "y",
+ "on",
+ "1",
+ "false",
+ "f",
+ "no",
+ "n",
+ "off",
+ "0"
+ ].includes(value.trim().toLowerCase());
+ case "[object Number]":
+ return [0, 1].includes(value.valueOf());
+ case "[object Boolean]":
+ return true;
+ default:
+ return false;
+ }
+ }, "isBooleanable");
+ exports2.isBooleanable = isBooleanable;
+ }
+});
+
+// ../../node_modules/.pnpm/boolean@3.2.0/node_modules/boolean/build/lib/index.js
+var require_lib5 = __commonJS({
+ "../../node_modules/.pnpm/boolean@3.2.0/node_modules/boolean/build/lib/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.isBooleanable = exports2.boolean = void 0;
+ var boolean_1 = require_boolean();
+ Object.defineProperty(exports2, "boolean", { enumerable: true, get: function() {
+ return boolean_1.boolean;
+ } });
+ var isBooleanable_1 = require_isBooleanable();
+ Object.defineProperty(exports2, "isBooleanable", { enumerable: true, get: function() {
+ return isBooleanable_1.isBooleanable;
+ } });
+ }
+});
+
+// ../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/dist/es5/uri.all.js
+var require_uri_all = __commonJS({
+ "../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/dist/es5/uri.all.js"(exports2, module2) {
+ init_import_meta_url();
+ (function(global2, factory) {
+ typeof exports2 === "object" && typeof module2 !== "undefined" ? factory(exports2) : typeof define === "function" && define.amd ? define(["exports"], factory) : factory(global2.URI = global2.URI || {});
+ })(exports2, function(exports3) {
+ "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) {
+ 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("");
+ } else {
+ return sets[0];
+ }
+ }
+ __name(merge, "merge");
+ function subexp(str) {
+ return "(?:" + str + ")";
+ }
+ __name(subexp, "subexp");
+ function typeOf(o) {
+ return o === void 0 ? "undefined" : o === null ? "null" : Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();
+ }
+ __name(typeOf, "typeOf");
+ function toUpperCase(str) {
+ return str.toUpperCase();
+ }
+ __name(toUpperCase, "toUpperCase");
+ function toArray(obj) {
+ return obj !== void 0 && obj !== null ? obj instanceof Array ? obj : typeof obj.length !== "number" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj) : [];
+ }
+ __name(toArray, "toArray");
+ function assign(target, source) {
+ var obj = target;
+ if (source) {
+ for (var key in source) {
+ obj[key] = source[key];
+ }
+ }
+ return obj;
+ }
+ __name(assign, "assign");
+ function buildExps(isIRI2) {
+ var ALPHA$$ = "[A-Za-z]", CR$ = "[\\x0D]", DIGIT$$ = "[0-9]", DQUOTE$$ = "[\\x22]", HEXDIG$$2 = merge(DIGIT$$, "[A-Fa-f]"), LF$$ = "[\\x0A]", SP$$ = "[\\x20]", PCT_ENCODED$2 = subexp(subexp("%[EFef]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%[89A-Fa-f]" + HEXDIG$$2 + "%" + HEXDIG$$2 + HEXDIG$$2) + "|" + subexp("%" + HEXDIG$$2 + HEXDIG$$2)), GEN_DELIMS$$ = "[\\:\\/\\?\\#\\[\\]\\@]", SUB_DELIMS$$ = "[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]", RESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$), UCSCHAR$$ = isIRI2 ? "[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]" : "[]", IPRIVATE$$ = isIRI2 ? "[\\uE000-\\uF8FF]" : "[]", UNRESERVED$$2 = merge(ALPHA$$, DIGIT$$, "[\\-\\.\\_\\~]", UCSCHAR$$), SCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, "[\\+\\-\\.]") + "*"), USERINFO$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]")) + "*"), DEC_OCTET$ = subexp(subexp("25[0-5]") + "|" + subexp("2[0-4]" + DIGIT$$) + "|" + subexp("1" + DIGIT$$ + DIGIT$$) + "|" + subexp("[1-9]" + DIGIT$$) + "|" + DIGIT$$), DEC_OCTET_RELAXED$ = 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$$2 + "{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$$2 + "|" + PCT_ENCODED$2) + "+"), IPV6ADDRZ$ = subexp(IPV6ADDRESS$ + "\\%25" + ZONEID$), IPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + ZONEID$), IPVFUTURE$ = subexp("[vV]" + HEXDIG$$2 + "+\\." + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:]") + "+"), IP_LITERAL$ = subexp("\\[" + subexp(IPV6ADDRZ_RELAXED$ + "|" + IPV6ADDRESS$ + "|" + IPVFUTURE$) + "\\]"), REG_NAME$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, 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$2 + "|" + merge(UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@]")), SEGMENT$ = subexp(PCHAR$ + "*"), SEGMENT_NZ$ = subexp(PCHAR$ + "+"), SEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$2 + "|" + merge(UNRESERVED$$2, 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$ + ")", PATH$ = subexp(PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$), QUERY$ = 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$) + "?"), URI_REFERENCE$ = subexp(URI$ + "|" + RELATIVE$), ABSOLUTE_URI$ = subexp(SCHEME$ + "\\:" + HIER_PART$ + subexp("\\?" + QUERY$) + "?"), GENERIC_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", RELATIVE_REF$ = "^(){0}" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_NOSCHEME$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", ABSOLUTE_REF$ = "^(" + SCHEME$ + ")\\:" + subexp(subexp("\\/\\/(" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?)") + "?(" + PATH_ABEMPTY$ + "|" + PATH_ABSOLUTE$ + "|" + PATH_ROOTLESS$ + "|" + PATH_EMPTY$ + ")") + subexp("\\?(" + QUERY$ + ")") + "?$", SAMEDOC_REF$ = "^" + subexp("\\#(" + FRAGMENT$ + ")") + "?$", AUTHORITY_REF$ = "^" + subexp("(" + USERINFO$ + ")@") + "?(" + HOST$ + ")" + subexp("\\:(" + PORT$ + ")") + "?$";
+ return {
+ NOT_SCHEME: new RegExp(merge("[^]", ALPHA$$, DIGIT$$, "[\\+\\-\\.]"), "g"),
+ NOT_USERINFO: new RegExp(merge("[^\\%\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
+ NOT_HOST: new RegExp(merge("[^\\%\\[\\]\\:]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
+ NOT_PATH: new RegExp(merge("[^\\%\\/\\:\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
+ NOT_PATH_NOSCHEME: new RegExp(merge("[^\\%\\/\\@]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
+ NOT_QUERY: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]", IPRIVATE$$), "g"),
+ NOT_FRAGMENT: new RegExp(merge("[^\\%]", UNRESERVED$$2, SUB_DELIMS$$, "[\\:\\@\\/\\?]"), "g"),
+ ESCAPE: new RegExp(merge("[^]", UNRESERVED$$2, SUB_DELIMS$$), "g"),
+ UNRESERVED: new RegExp(UNRESERVED$$2, "g"),
+ OTHER_CHARS: new RegExp(merge("[^\\%]", UNRESERVED$$2, RESERVED$$), "g"),
+ PCT_ENCODED: new RegExp(PCT_ENCODED$2, "g"),
+ IPV4ADDRESS: new RegExp("^(" + IPV4ADDRESS$ + ")$"),
+ IPV6ADDRESS: new RegExp("^\\[?(" + IPV6ADDRESS$ + ")" + subexp(subexp("\\%25|\\%(?!" + HEXDIG$$2 + "{2})") + "(" + ZONEID$ + ")") + "?\\]?$")
+ //RFC 6874, with relaxed parsing rules
+ };
+ }
+ __name(buildExps, "buildExps");
+ 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;
+ }
+ __name(sliceIterator, "sliceIterator");
+ return function(arr, i) {
+ if (Array.isArray(arr)) {
+ return arr;
+ } else if (Symbol.iterator in Object(arr)) {
+ return sliceIterator(arr, i);
+ } else {
+ throw new TypeError("Invalid attempt to destructure non-iterable instance");
+ }
+ };
+ }();
+ var toConsumableArray = /* @__PURE__ */ __name(function(arr) {
+ if (Array.isArray(arr)) {
+ for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++)
+ arr2[i] = arr[i];
+ return arr2;
+ } else {
+ return Array.from(arr);
+ }
+ }, "toConsumableArray");
+ 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]);
+ }
+ __name(error$1, "error$1");
+ function map(array, fn2) {
+ var result = [];
+ var length = array.length;
+ while (length--) {
+ result[length] = fn2(array[length]);
+ }
+ return result;
+ }
+ __name(map, "map");
+ function mapDomain(string, fn2) {
+ var parts = string.split("@");
+ var result = "";
+ if (parts.length > 1) {
+ result = parts[0] + "@";
+ string = parts[1];
+ }
+ string = string.replace(regexSeparators, ".");
+ var labels = string.split(".");
+ var encoded = map(labels, fn2).join(".");
+ return result + encoded;
+ }
+ __name(mapDomain, "mapDomain");
+ function ucs2decode(string) {
+ var output = [];
+ var counter = 0;
+ var length = string.length;
+ while (counter < length) {
+ var value = string.charCodeAt(counter++);
+ if (value >= 55296 && value <= 56319 && counter < length) {
+ var extra = string.charCodeAt(counter++);
+ if ((extra & 64512) == 56320) {
+ output.push(((value & 1023) << 10) + (extra & 1023) + 65536);
+ } else {
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
+ __name(ucs2decode, "ucs2decode");
+ var ucs2encode = /* @__PURE__ */ __name(function ucs2encode2(array) {
+ return String.fromCodePoint.apply(String, toConsumableArray(array));
+ }, "ucs2encode");
+ var basicToDigit = /* @__PURE__ */ __name(function basicToDigit2(codePoint) {
+ if (codePoint - 48 < 10) {
+ return codePoint - 22;
+ }
+ if (codePoint - 65 < 26) {
+ return codePoint - 65;
+ }
+ if (codePoint - 97 < 26) {
+ return codePoint - 97;
+ }
+ return base;
+ }, "basicToDigit");
+ var digitToBasic = /* @__PURE__ */ __name(function digitToBasic2(digit, flag) {
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+ }, "digitToBasic");
+ var adapt = /* @__PURE__ */ __name(function adapt2(delta, numPoints, firstTime) {
+ var k = 0;
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
+ delta += floor(delta / numPoints);
+ for (
+ ;
+ /* no initialization */
+ delta > baseMinusTMin * tMax >> 1;
+ k += base
+ ) {
+ delta = floor(delta / baseMinusTMin);
+ }
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+ }, "adapt");
+ var decode = /* @__PURE__ */ __name(function decode2(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) >= 128) {
+ 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;
+ ;
+ /* no condition */
+ 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 t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
+ if (digit < t2) {
+ break;
+ }
+ var baseMinusT = base - t2;
+ if (w > floor(maxInt / baseMinusT)) {
+ error$1("overflow");
+ }
+ w *= baseMinusT;
+ }
+ var out = output.length + 1;
+ bias = adapt(i - oldi, out, oldi == 0);
+ 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);
+ }, "decode");
+ var encode = /* @__PURE__ */ __name(function encode2(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 < 128) {
+ 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;
+ ;
+ /* no condition */
+ k += base
+ ) {
+ var t2 = k <= bias ? tMin : k >= bias + tMax ? tMax : k - bias;
+ if (q < t2) {
+ break;
+ }
+ var qMinusT = q - t2;
+ var baseMinusT = base - t2;
+ output.push(stringFromCharCode(digitToBasic(t2 + 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("");
+ }, "encode");
+ var toUnicode = /* @__PURE__ */ __name(function toUnicode2(input) {
+ return mapDomain(input, function(string) {
+ return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string;
+ });
+ }, "toUnicode");
+ var toASCII = /* @__PURE__ */ __name(function toASCII2(input) {
+ return mapDomain(input, function(string) {
+ return regexNonASCII.test(string) ? "xn--" + encode(string) : string;
+ });
+ }, "toASCII");
+ var punycode = {
+ /**
+ * A string representing the current Punycode.js version number.
+ * @memberOf punycode
+ * @type String
+ */
+ "version": "2.1.0",
+ /**
+ * An object of methods to convert from JavaScript's internal character
+ * representation (UCS-2) to Unicode code points, and back.
+ * @see
+ * @memberOf punycode
+ * @type Object
+ */
+ "ucs2": {
+ "decode": ucs2decode,
+ "encode": ucs2encode
+ },
+ "decode": decode,
+ "encode": encode,
+ "toASCII": toASCII,
+ "toUnicode": toUnicode
+ };
+ var SCHEMES = {};
+ function pctEncChar(chr) {
+ var c = chr.charCodeAt(0);
+ var e2 = void 0;
+ if (c < 16)
+ e2 = "%0" + c.toString(16).toUpperCase();
+ else if (c < 128)
+ e2 = "%" + c.toString(16).toUpperCase();
+ else if (c < 2048)
+ e2 = "%" + (c >> 6 | 192).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
+ else
+ e2 = "%" + (c >> 12 | 224).toString(16).toUpperCase() + "%" + (c >> 6 & 63 | 128).toString(16).toUpperCase() + "%" + (c & 63 | 128).toString(16).toUpperCase();
+ return e2;
+ }
+ __name(pctEncChar, "pctEncChar");
+ 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((c & 31) << 6 | c2 & 63);
+ } else {
+ newStr += str.substr(i, 6);
+ }
+ i += 6;
+ } else if (c >= 224) {
+ if (il - i >= 9) {
+ var _c2 = parseInt(str.substr(i + 4, 2), 16);
+ var c3 = parseInt(str.substr(i + 7, 2), 16);
+ newStr += String.fromCharCode((c & 15) << 12 | (_c2 & 63) << 6 | c3 & 63);
+ } else {
+ newStr += str.substr(i, 9);
+ }
+ i += 9;
+ } else {
+ newStr += str.substr(i, 3);
+ i += 3;
+ }
+ }
+ return newStr;
+ }
+ __name(pctDecChars, "pctDecChars");
+ function _normalizeComponentEncoding(components, protocol) {
+ function decodeUnreserved2(str) {
+ var decStr = pctDecChars(str);
+ return !decStr.match(protocol.UNRESERVED) ? str : decStr;
+ }
+ __name(decodeUnreserved2, "decodeUnreserved");
+ if (components.scheme)
+ components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_SCHEME, "");
+ if (components.userinfo !== void 0)
+ components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
+ if (components.host !== void 0)
+ components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved2).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
+ if (components.path !== void 0)
+ components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
+ if (components.query !== void 0)
+ components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
+ if (components.fragment !== void 0)
+ components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved2).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);
+ return components;
+ }
+ __name(_normalizeComponentEncoding, "_normalizeComponentEncoding");
+ function _stripLeadingZeros(str) {
+ return str.replace(/^0*(.*)/, "$1") || "0";
+ }
+ __name(_stripLeadingZeros, "_stripLeadingZeros");
+ 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(".");
+ } else {
+ return host;
+ }
+ }
+ __name(_normalizeIPv4, "_normalizeIPv4");
+ function _normalizeIPv6(host, protocol) {
+ var matches = host.match(protocol.IPV6ADDRESS) || [];
+ var _matches2 = slicedToArray(matches, 3), address = _matches2[1], zone = _matches2[2];
+ if (address) {
+ 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 || field === "0") {
+ var lastLongest = acc[acc.length - 1];
+ if (lastLongest && lastLongest.index + lastLongest.length === index) {
+ lastLongest.length++;
+ } else {
+ acc.push({ 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;
+ } else {
+ return host;
+ }
+ }
+ __name(_normalizeIPv6, "_normalizeIPv6");
+ var URI_PARSE = /^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i;
+ var NO_MATCH_IS_UNDEFINED = "".match(/(){0}/)[1] === void 0;
+ function parse4(uriString) {
+ var options14 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
+ var components = {};
+ var protocol = options14.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
+ if (options14.reference === "suffix")
+ uriString = (options14.scheme ? options14.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 = uriString.indexOf("@") !== -1 ? matches[3] : void 0;
+ components.host = uriString.indexOf("//") !== -1 ? matches[4] : void 0;
+ components.port = parseInt(matches[5], 10);
+ components.path = matches[6] || "";
+ components.query = uriString.indexOf("?") !== -1 ? matches[7] : void 0;
+ components.fragment = uriString.indexOf("#") !== -1 ? 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 (components.scheme === void 0 && components.userinfo === void 0 && components.host === void 0 && components.port === void 0 && !components.path && components.query === void 0) {
+ components.reference = "same-document";
+ } else if (components.scheme === void 0) {
+ components.reference = "relative";
+ } else if (components.fragment === void 0) {
+ components.reference = "absolute";
+ } else {
+ components.reference = "uri";
+ }
+ if (options14.reference && options14.reference !== "suffix" && options14.reference !== components.reference) {
+ components.error = components.error || "URI is not a " + options14.reference + " reference.";
+ }
+ var schemeHandler = SCHEMES[(options14.scheme || components.scheme || "").toLowerCase()];
+ if (!options14.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
+ if (components.host && (options14.domainHost || schemeHandler && schemeHandler.domainHost)) {
+ try {
+ components.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());
+ } catch (e2) {
+ components.error = components.error || "Host's domain name can not be converted to ASCII via punycode: " + e2;
+ }
+ }
+ _normalizeComponentEncoding(components, URI_PROTOCOL);
+ } else {
+ _normalizeComponentEncoding(components, protocol);
+ }
+ if (schemeHandler && schemeHandler.parse) {
+ schemeHandler.parse(components, options14);
+ }
+ } else {
+ components.error = components.error || "URI can not be parsed.";
+ }
+ return components;
+ }
+ __name(parse4, "parse");
+ function _recomposeAuthority(components, options14) {
+ var protocol = options14.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL;
+ var uriTokens = [];
+ if (components.userinfo !== void 0) {
+ uriTokens.push(components.userinfo);
+ uriTokens.push("@");
+ }
+ if (components.host !== void 0) {
+ uriTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, function(_2, $1, $2) {
+ return "[" + $1 + ($2 ? "%25" + $2 : "") + "]";
+ }));
+ }
+ if (typeof components.port === "number" || typeof components.port === "string") {
+ uriTokens.push(":");
+ uriTokens.push(String(components.port));
+ }
+ return uriTokens.length ? uriTokens.join("") : void 0;
+ }
+ __name(_recomposeAuthority, "_recomposeAuthority");
+ 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("");
+ }
+ __name(removeDotSegments, "removeDotSegments");
+ function serialize(components) {
+ var options14 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {};
+ var protocol = options14.iri ? IRI_PROTOCOL : URI_PROTOCOL;
+ var uriTokens = [];
+ var schemeHandler = SCHEMES[(options14.scheme || components.scheme || "").toLowerCase()];
+ if (schemeHandler && schemeHandler.serialize)
+ schemeHandler.serialize(components, options14);
+ if (components.host) {
+ if (protocol.IPV6ADDRESS.test(components.host)) {
+ } else if (options14.domainHost || schemeHandler && schemeHandler.domainHost) {
+ try {
+ components.host = !options14.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host);
+ } catch (e2) {
+ components.error = components.error || "Host's domain name can not be converted to " + (!options14.iri ? "ASCII" : "Unicode") + " via punycode: " + e2;
+ }
+ }
+ }
+ _normalizeComponentEncoding(components, protocol);
+ if (options14.reference !== "suffix" && components.scheme) {
+ uriTokens.push(components.scheme);
+ uriTokens.push(":");
+ }
+ var authority = _recomposeAuthority(components, options14);
+ if (authority !== void 0) {
+ if (options14.reference !== "suffix") {
+ uriTokens.push("//");
+ }
+ uriTokens.push(authority);
+ if (components.path && components.path.charAt(0) !== "/") {
+ uriTokens.push("/");
+ }
+ }
+ if (components.path !== void 0) {
+ var s = components.path;
+ if (!options14.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
+ s = removeDotSegments(s);
+ }
+ if (authority === void 0) {
+ s = s.replace(/^\/\//, "/%2F");
+ }
+ uriTokens.push(s);
+ }
+ if (components.query !== void 0) {
+ uriTokens.push("?");
+ uriTokens.push(components.query);
+ }
+ if (components.fragment !== void 0) {
+ uriTokens.push("#");
+ uriTokens.push(components.fragment);
+ }
+ return uriTokens.join("");
+ }
+ __name(serialize, "serialize");
+ function resolveComponents(base2, relative12) {
+ var options14 = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {};
+ var skipNormalization = arguments[3];
+ var target = {};
+ if (!skipNormalization) {
+ base2 = parse4(serialize(base2, options14), options14);
+ relative12 = parse4(serialize(relative12, options14), options14);
+ }
+ options14 = options14 || {};
+ if (!options14.tolerant && relative12.scheme) {
+ target.scheme = relative12.scheme;
+ target.userinfo = relative12.userinfo;
+ target.host = relative12.host;
+ target.port = relative12.port;
+ target.path = removeDotSegments(relative12.path || "");
+ target.query = relative12.query;
+ } else {
+ if (relative12.userinfo !== void 0 || relative12.host !== void 0 || relative12.port !== void 0) {
+ target.userinfo = relative12.userinfo;
+ target.host = relative12.host;
+ target.port = relative12.port;
+ target.path = removeDotSegments(relative12.path || "");
+ target.query = relative12.query;
+ } else {
+ if (!relative12.path) {
+ target.path = base2.path;
+ if (relative12.query !== void 0) {
+ target.query = relative12.query;
+ } else {
+ target.query = base2.query;
+ }
+ } else {
+ if (relative12.path.charAt(0) === "/") {
+ target.path = removeDotSegments(relative12.path);
+ } else {
+ if ((base2.userinfo !== void 0 || base2.host !== void 0 || base2.port !== void 0) && !base2.path) {
+ target.path = "/" + relative12.path;
+ } else if (!base2.path) {
+ target.path = relative12.path;
+ } else {
+ target.path = base2.path.slice(0, base2.path.lastIndexOf("/") + 1) + relative12.path;
+ }
+ target.path = removeDotSegments(target.path);
+ }
+ target.query = relative12.query;
+ }
+ target.userinfo = base2.userinfo;
+ target.host = base2.host;
+ target.port = base2.port;
+ }
+ target.scheme = base2.scheme;
+ }
+ target.fragment = relative12.fragment;
+ return target;
+ }
+ __name(resolveComponents, "resolveComponents");
+ function resolve18(baseURI, relativeURI, options14) {
+ var schemelessOptions = assign({ scheme: "null" }, options14);
+ return serialize(resolveComponents(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);
+ }
+ __name(resolve18, "resolve");
+ function normalize2(uri, options14) {
+ if (typeof uri === "string") {
+ uri = serialize(parse4(uri, options14), options14);
+ } else if (typeOf(uri) === "object") {
+ uri = parse4(serialize(uri, options14), options14);
+ }
+ return uri;
+ }
+ __name(normalize2, "normalize");
+ function equal(uriA, uriB, options14) {
+ if (typeof uriA === "string") {
+ uriA = serialize(parse4(uriA, options14), options14);
+ } else if (typeOf(uriA) === "object") {
+ uriA = serialize(uriA, options14);
+ }
+ if (typeof uriB === "string") {
+ uriB = serialize(parse4(uriB, options14), options14);
+ } else if (typeOf(uriB) === "object") {
+ uriB = serialize(uriB, options14);
+ }
+ return uriA === uriB;
+ }
+ __name(equal, "equal");
+ function escapeComponent(str, options14) {
+ return str && str.toString().replace(!options14 || !options14.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE, pctEncChar);
+ }
+ __name(escapeComponent, "escapeComponent");
+ function unescapeComponent(str, options14) {
+ return str && str.toString().replace(!options14 || !options14.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED, pctDecChars);
+ }
+ __name(unescapeComponent, "unescapeComponent");
+ var handler15 = {
+ scheme: "http",
+ domainHost: true,
+ parse: /* @__PURE__ */ __name(function parse5(components, options14) {
+ if (!components.host) {
+ components.error = components.error || "HTTP URIs must have a host.";
+ }
+ return components;
+ }, "parse"),
+ serialize: /* @__PURE__ */ __name(function serialize2(components, options14) {
+ var secure = String(components.scheme).toLowerCase() === "https";
+ if (components.port === (secure ? 443 : 80) || components.port === "") {
+ components.port = void 0;
+ }
+ if (!components.path) {
+ components.path = "/";
+ }
+ return components;
+ }, "serialize")
+ };
+ var handler$1 = {
+ scheme: "https",
+ domainHost: handler15.domainHost,
+ parse: handler15.parse,
+ serialize: handler15.serialize
+ };
+ function isSecure(wsComponents) {
+ return typeof wsComponents.secure === "boolean" ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === "wss";
+ }
+ __name(isSecure, "isSecure");
+ var handler$2 = {
+ scheme: "ws",
+ domainHost: true,
+ parse: /* @__PURE__ */ __name(function parse5(components, options14) {
+ 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;
+ }, "parse"),
+ serialize: /* @__PURE__ */ __name(function serialize2(wsComponents, options14) {
+ if (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === "") {
+ wsComponents.port = void 0;
+ }
+ if (typeof wsComponents.secure === "boolean") {
+ 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), path45 = _wsComponents$resourc2[0], query = _wsComponents$resourc2[1];
+ wsComponents.path = path45 && path45 !== "/" ? path45 : void 0;
+ wsComponents.query = query;
+ wsComponents.resourceName = void 0;
+ }
+ wsComponents.fragment = void 0;
+ return wsComponents;
+ }, "serialize")
+ };
+ 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) ? str : decStr;
+ }
+ __name(decodeUnreserved, "decodeUnreserved");
+ var handler$4 = {
+ scheme: "mailto",
+ parse: /* @__PURE__ */ __name(function parse$$1(components, options14) {
+ 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], options14);
+ break;
+ case "body":
+ mailtoComponents.body = unescapeComponent(hfield[1], options14);
+ break;
+ default:
+ unknownHeaders = true;
+ headers[unescapeComponent(hfield[0], options14)] = unescapeComponent(hfield[1], options14);
+ 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 (!options14.unicodeSupport) {
+ try {
+ addr[1] = punycode.toASCII(unescapeComponent(addr[1], options14).toLowerCase());
+ } catch (e2) {
+ mailtoComponents.error = mailtoComponents.error || "Email address's domain name can not be converted to ASCII via punycode: " + e2;
+ }
+ } else {
+ addr[1] = unescapeComponent(addr[1], options14).toLowerCase();
+ }
+ to[_x2] = addr.join("@");
+ }
+ return mailtoComponents;
+ }, "parse$$1"),
+ serialize: /* @__PURE__ */ __name(function serialize$$1(mailtoComponents, options14) {
+ 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 = !options14.iri ? punycode.toASCII(unescapeComponent(domain, options14).toLowerCase()) : punycode.toUnicode(domain);
+ } catch (e2) {
+ components.error = components.error || "Email address's domain name can not be converted to " + (!options14.iri ? "ASCII" : "Unicode") + " via punycode: " + e2;
+ }
+ 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;
+ }, "serialize$$1")
+ };
+ var URN_PARSE = /^([^\:]+)\:(.*)/;
+ var handler$5 = {
+ scheme: "urn",
+ parse: /* @__PURE__ */ __name(function parse$$1(components, options14) {
+ var matches = components.path && components.path.match(URN_PARSE);
+ var urnComponents = components;
+ if (matches) {
+ var scheme = options14.scheme || urnComponents.scheme || "urn";
+ var nid = matches[1].toLowerCase();
+ var nss = matches[2];
+ var urnScheme = scheme + ":" + (options14.nid || nid);
+ var schemeHandler = SCHEMES[urnScheme];
+ urnComponents.nid = nid;
+ urnComponents.nss = nss;
+ urnComponents.path = void 0;
+ if (schemeHandler) {
+ urnComponents = schemeHandler.parse(urnComponents, options14);
+ }
+ } else {
+ urnComponents.error = urnComponents.error || "URN can not be parsed.";
+ }
+ return urnComponents;
+ }, "parse$$1"),
+ serialize: /* @__PURE__ */ __name(function serialize$$1(urnComponents, options14) {
+ var scheme = options14.scheme || urnComponents.scheme || "urn";
+ var nid = urnComponents.nid;
+ var urnScheme = scheme + ":" + (options14.nid || nid);
+ var schemeHandler = SCHEMES[urnScheme];
+ if (schemeHandler) {
+ urnComponents = schemeHandler.serialize(urnComponents, options14);
+ }
+ var uriComponents = urnComponents;
+ var nss = urnComponents.nss;
+ uriComponents.path = (nid || options14.nid) + ":" + nss;
+ return uriComponents;
+ }, "serialize$$1")
+ };
+ 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: /* @__PURE__ */ __name(function parse5(urnComponents, options14) {
+ var uuidComponents = urnComponents;
+ uuidComponents.uuid = uuidComponents.nss;
+ uuidComponents.nss = void 0;
+ if (!options14.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {
+ uuidComponents.error = uuidComponents.error || "UUID is not valid.";
+ }
+ return uuidComponents;
+ }, "parse"),
+ serialize: /* @__PURE__ */ __name(function serialize2(uuidComponents, options14) {
+ var urnComponents = uuidComponents;
+ urnComponents.nss = (uuidComponents.uuid || "").toLowerCase();
+ return urnComponents;
+ }, "serialize")
+ };
+ SCHEMES[handler15.scheme] = handler15;
+ 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;
+ exports3.SCHEMES = SCHEMES;
+ exports3.pctEncChar = pctEncChar;
+ exports3.pctDecChars = pctDecChars;
+ exports3.parse = parse4;
+ exports3.removeDotSegments = removeDotSegments;
+ exports3.serialize = serialize;
+ exports3.resolveComponents = resolveComponents;
+ exports3.resolve = resolve18;
+ exports3.normalize = normalize2;
+ exports3.equal = equal;
+ exports3.escapeComponent = escapeComponent;
+ exports3.unescapeComponent = unescapeComponent;
+ Object.defineProperty(exports3, "__esModule", { value: true });
+ });
+ }
+});
+
+// ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
+var require_fast_deep_equal = __commonJS({
+ "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function equal(a, b) {
+ if (a === b)
+ return true;
+ if (a && b && typeof a == "object" && typeof b == "object") {
+ if (a.constructor !== b.constructor)
+ return false;
+ var length, i, keys;
+ if (Array.isArray(a)) {
+ length = a.length;
+ if (length != b.length)
+ return false;
+ for (i = length; i-- !== 0; )
+ if (!equal(a[i], b[i]))
+ return false;
+ return true;
+ }
+ if (a.constructor === RegExp)
+ return a.source === b.source && a.flags === b.flags;
+ if (a.valueOf !== Object.prototype.valueOf)
+ return a.valueOf() === b.valueOf();
+ if (a.toString !== Object.prototype.toString)
+ return a.toString() === b.toString();
+ keys = Object.keys(a);
+ length = keys.length;
+ if (length !== Object.keys(b).length)
+ return false;
+ for (i = length; i-- !== 0; )
+ if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
+ return false;
+ for (i = length; i-- !== 0; ) {
+ var key = keys[i];
+ if (!equal(a[key], b[key]))
+ return false;
+ }
+ return true;
+ }
+ return a !== a && b !== b;
+ }, "equal");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/ucs2length.js
+var require_ucs2length = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/ucs2length.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function ucs2length(str) {
+ var length = 0, len = str.length, pos = 0, value;
+ while (pos < len) {
+ length++;
+ value = str.charCodeAt(pos++);
+ if (value >= 55296 && value <= 56319 && pos < len) {
+ value = str.charCodeAt(pos);
+ if ((value & 64512) == 56320)
+ pos++;
+ }
+ }
+ return length;
+ }, "ucs2length");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js
+var require_util9 = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/util.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = {
+ copy,
+ checkDataType,
+ checkDataTypes,
+ coerceToTypes,
+ toHash,
+ getProperty,
+ escapeQuotes,
+ equal: require_fast_deep_equal(),
+ ucs2length: require_ucs2length(),
+ varOccurences,
+ varReplace,
+ schemaHasRules,
+ schemaHasRulesExcept,
+ schemaUnknownRules,
+ toQuotedString,
+ getPathExpr,
+ getPath,
+ getData,
+ unescapeFragment,
+ unescapeJsonPointer,
+ escapeFragment,
+ escapeJsonPointer
+ };
+ function copy(o, to) {
+ to = to || {};
+ for (var key in o)
+ to[key] = o[key];
+ return to;
+ }
+ __name(copy, "copy");
+ 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 + '"';
+ }
+ }
+ __name(checkDataType, "checkDataType");
+ 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 t2 in types)
+ code += (code ? " && " : "") + checkDataType(t2, data, strictNumbers, true);
+ return code;
+ }
+ }
+ __name(checkDataTypes, "checkDataTypes");
+ 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 t2 = dataTypes[i];
+ if (COERCE_TO_TYPES[t2])
+ types[types.length] = t2;
+ else if (optionCoerceTypes === "array" && t2 === "array")
+ types[types.length] = t2;
+ }
+ if (types.length)
+ return types;
+ } else if (COERCE_TO_TYPES[dataTypes]) {
+ return [dataTypes];
+ } else if (optionCoerceTypes === "array" && dataTypes === "array") {
+ return ["array"];
+ }
+ }
+ __name(coerceToTypes, "coerceToTypes");
+ function toHash(arr) {
+ var hash = {};
+ for (var i = 0; i < arr.length; i++)
+ hash[arr[i]] = true;
+ return hash;
+ }
+ __name(toHash, "toHash");
+ var IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
+ var SINGLE_QUOTE = /'|\\/g;
+ function getProperty(key) {
+ return typeof key == "number" ? "[" + key + "]" : IDENTIFIER.test(key) ? "." + key : "['" + escapeQuotes(key) + "']";
+ }
+ __name(getProperty, "getProperty");
+ function escapeQuotes(str) {
+ return str.replace(SINGLE_QUOTE, "\\$&").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\f/g, "\\f").replace(/\t/g, "\\t");
+ }
+ __name(escapeQuotes, "escapeQuotes");
+ function varOccurences(str, dataVar) {
+ dataVar += "[^0-9]";
+ var matches = str.match(new RegExp(dataVar, "g"));
+ return matches ? matches.length : 0;
+ }
+ __name(varOccurences, "varOccurences");
+ function varReplace(str, dataVar, expr) {
+ dataVar += "([^0-9])";
+ expr = expr.replace(/\$/g, "$$$$");
+ return str.replace(new RegExp(dataVar, "g"), expr + "$1");
+ }
+ __name(varReplace, "varReplace");
+ function schemaHasRules(schema, rules) {
+ if (typeof schema == "boolean")
+ return !schema;
+ for (var key in schema)
+ if (rules[key])
+ return true;
+ }
+ __name(schemaHasRules, "schemaHasRules");
+ function schemaHasRulesExcept(schema, rules, exceptKeyword) {
+ if (typeof schema == "boolean")
+ return !schema && exceptKeyword != "not";
+ for (var key in schema)
+ if (key != exceptKeyword && rules[key])
+ return true;
+ }
+ __name(schemaHasRulesExcept, "schemaHasRulesExcept");
+ function schemaUnknownRules(schema, rules) {
+ if (typeof schema == "boolean")
+ return;
+ for (var key in schema)
+ if (!rules[key])
+ return key;
+ }
+ __name(schemaUnknownRules, "schemaUnknownRules");
+ function toQuotedString(str) {
+ return "'" + escapeQuotes(str) + "'";
+ }
+ __name(toQuotedString, "toQuotedString");
+ function getPathExpr(currentPath, expr, jsonPointers, isNumber) {
+ var path45 = jsonPointers ? "'/' + " + expr + (isNumber ? "" : ".replace(/~/g, '~0').replace(/\\//g, '~1')") : isNumber ? "'[' + " + expr + " + ']'" : "'[\\'' + " + expr + " + '\\']'";
+ return joinPaths(currentPath, path45);
+ }
+ __name(getPathExpr, "getPathExpr");
+ function getPath(currentPath, prop, jsonPointers) {
+ var path45 = jsonPointers ? toQuotedString("/" + escapeJsonPointer(prop)) : toQuotedString(getProperty(prop));
+ return joinPaths(currentPath, path45);
+ }
+ __name(getPath, "getPath");
+ 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;
+ }
+ __name(getData, "getData");
+ function joinPaths(a, b) {
+ if (a == '""')
+ return b;
+ return (a + " + " + b).replace(/([^\\])' \+ '/g, "$1");
+ }
+ __name(joinPaths, "joinPaths");
+ function unescapeFragment(str) {
+ return unescapeJsonPointer(decodeURIComponent(str));
+ }
+ __name(unescapeFragment, "unescapeFragment");
+ function escapeFragment(str) {
+ return encodeURIComponent(escapeJsonPointer(str));
+ }
+ __name(escapeFragment, "escapeFragment");
+ function escapeJsonPointer(str) {
+ return str.replace(/~/g, "~0").replace(/\//g, "~1");
+ }
+ __name(escapeJsonPointer, "escapeJsonPointer");
+ function unescapeJsonPointer(str) {
+ return str.replace(/~1/g, "/").replace(/~0/g, "~");
+ }
+ __name(unescapeJsonPointer, "unescapeJsonPointer");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/schema_obj.js
+var require_schema_obj = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/schema_obj.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var util3 = require_util9();
+ module2.exports = SchemaObject;
+ function SchemaObject(obj) {
+ util3.copy(obj, this);
+ }
+ __name(SchemaObject, "SchemaObject");
+ }
+});
+
+// ../../node_modules/.pnpm/json-schema-traverse@0.4.1/node_modules/json-schema-traverse/index.js
+var require_json_schema_traverse = __commonJS({
+ "../../node_modules/.pnpm/json-schema-traverse@0.4.1/node_modules/json-schema-traverse/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var traverse = module2.exports = function(schema, opts, cb) {
+ if (typeof opts == "function") {
+ cb = opts;
+ opts = {};
+ }
+ cb = opts.cb || cb;
+ var pre = typeof cb == "function" ? cb : cb.pre || function() {
+ };
+ var post = cb.post || function() {
+ };
+ _traverse(opts, pre, post, schema, "", schema);
+ };
+ traverse.keywords = {
+ additionalItems: true,
+ items: true,
+ contains: true,
+ additionalProperties: true,
+ propertyNames: true,
+ not: true
+ };
+ 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 && typeof schema == "object" && !Array.isArray(schema)) {
+ pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
+ for (var key in schema) {
+ var sch = schema[key];
+ if (Array.isArray(sch)) {
+ if (key in traverse.arrayKeywords) {
+ for (var i = 0; i < sch.length; i++)
+ _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
+ }
+ } else if (key in traverse.propsKeywords) {
+ if (sch && typeof sch == "object") {
+ for (var prop in sch)
+ _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
+ }
+ } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
+ _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
+ }
+ }
+ post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
+ }
+ }
+ __name(_traverse, "_traverse");
+ function escapeJsonPtr(str) {
+ return str.replace(/~/g, "~0").replace(/\//g, "~1");
+ }
+ __name(escapeJsonPtr, "escapeJsonPtr");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/resolve.js
+var require_resolve = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/resolve.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var URI = require_uri_all();
+ var equal = require_fast_deep_equal();
+ var util3 = require_util9();
+ var SchemaObject = require_schema_obj();
+ var traverse = require_json_schema_traverse();
+ module2.exports = resolve18;
+ resolve18.normalizeId = normalizeId;
+ resolve18.fullPath = getFullPath;
+ resolve18.url = resolveUrl;
+ resolve18.ids = resolveIds;
+ resolve18.inlineRef = inlineRef;
+ resolve18.schema = resolveSchema;
+ function resolve18(compile, root, ref) {
+ var refVal = this._refs[ref];
+ if (typeof refVal == "string") {
+ if (this._refs[refVal])
+ refVal = this._refs[refVal];
+ else
+ return resolve18.call(this, compile, root, 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 (schema !== void 0) {
+ v = inlineRef(schema, this._opts.inlineRefs) ? schema : compile.call(this, schema, root, void 0, baseId);
+ }
+ return v;
+ }
+ __name(resolve18, "resolve");
+ function resolveSchema(root, ref) {
+ var p = URI.parse(ref), refPath = _getFullPath(p), baseId = getFullPath(this._getId(root.schema));
+ if (Object.keys(root.schema).length === 0 || refPath !== baseId) {
+ var id = normalizeId(refPath);
+ var refVal = this._refs[id];
+ if (typeof refVal == "string") {
+ return resolveRecursive.call(this, root, refVal, p);
+ } else if (refVal instanceof SchemaObject) {
+ if (!refVal.validate)
+ this._compile(refVal);
+ root = refVal;
+ } else {
+ refVal = this._schemas[id];
+ if (refVal instanceof SchemaObject) {
+ if (!refVal.validate)
+ this._compile(refVal);
+ if (id == normalizeId(ref))
+ return { schema: refVal, root, baseId };
+ root = refVal;
+ } else {
+ return;
+ }
+ }
+ if (!root.schema)
+ return;
+ baseId = getFullPath(this._getId(root.schema));
+ }
+ return getJsonPointer.call(this, p, baseId, root.schema, root);
+ }
+ __name(resolveSchema, "resolveSchema");
+ 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);
+ }
+ }
+ __name(resolveRecursive, "resolveRecursive");
+ var PREVENT_SCOPE_CHANGE = util3.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 = util3.unescapeFragment(part);
+ schema = schema[part];
+ if (schema === void 0)
+ 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 (schema !== void 0 && schema !== root.schema)
+ return { schema, root, baseId };
+ }
+ __name(getJsonPointer, "getJsonPointer");
+ var SIMPLE_INLINED = util3.toHash([
+ "type",
+ "format",
+ "pattern",
+ "maxLength",
+ "minLength",
+ "maxProperties",
+ "minProperties",
+ "maxItems",
+ "minItems",
+ "maximum",
+ "minimum",
+ "uniqueItems",
+ "multipleOf",
+ "required",
+ "enum"
+ ]);
+ function inlineRef(schema, limit) {
+ if (limit === false)
+ return false;
+ if (limit === void 0 || limit === true)
+ return checkNoRef(schema);
+ else if (limit)
+ return countKeys(schema) <= limit;
+ }
+ __name(inlineRef, "inlineRef");
+ function checkNoRef(schema) {
+ var item;
+ if (Array.isArray(schema)) {
+ for (var i = 0; i < schema.length; i++) {
+ item = schema[i];
+ if (typeof item == "object" && !checkNoRef(item))
+ return false;
+ }
+ } else {
+ for (var key in schema) {
+ if (key == "$ref")
+ return false;
+ item = schema[key];
+ if (typeof item == "object" && !checkNoRef(item))
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(checkNoRef, "checkNoRef");
+ function countKeys(schema) {
+ var count = 0, item;
+ if (Array.isArray(schema)) {
+ for (var i = 0; i < schema.length; i++) {
+ item = schema[i];
+ if (typeof item == "object")
+ count += countKeys(item);
+ if (count == Infinity)
+ return Infinity;
+ }
+ } else {
+ for (var key in schema) {
+ if (key == "$ref")
+ return Infinity;
+ if (SIMPLE_INLINED[key]) {
+ count++;
+ } else {
+ item = schema[key];
+ if (typeof item == "object")
+ count += countKeys(item) + 1;
+ if (count == Infinity)
+ return Infinity;
+ }
+ }
+ }
+ return count;
+ }
+ __name(countKeys, "countKeys");
+ function getFullPath(id, normalize2) {
+ if (normalize2 !== false)
+ id = normalizeId(id);
+ var p = URI.parse(id);
+ return _getFullPath(p);
+ }
+ __name(getFullPath, "getFullPath");
+ function _getFullPath(p) {
+ return URI.serialize(p).split("#")[0] + "#";
+ }
+ __name(_getFullPath, "_getFullPath");
+ var TRAILING_SLASH_HASH = /#\/?$/;
+ function normalizeId(id) {
+ return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
+ }
+ __name(normalizeId, "normalizeId");
+ function resolveUrl(baseId, id) {
+ id = normalizeId(id);
+ return URI.resolve(baseId, id);
+ }
+ __name(resolveUrl, "resolveUrl");
+ function resolveIds(schema) {
+ var schemaId = normalizeId(this._getId(schema));
+ var baseIds = { "": schemaId };
+ var fullPaths = { "": getFullPath(schemaId, false) };
+ var localRefs = {};
+ var self2 = this;
+ traverse(schema, { allKeys: true }, function(sch, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
+ if (jsonPtr === "")
+ return;
+ var id = self2._getId(sch);
+ var baseId = baseIds[parentJsonPtr];
+ var fullPath = fullPaths[parentJsonPtr] + "/" + parentKeyword;
+ if (keyIndex !== void 0)
+ fullPath += "/" + (typeof keyIndex == "number" ? keyIndex : util3.escapeFragment(keyIndex));
+ if (typeof id == "string") {
+ id = baseId = normalizeId(baseId ? URI.resolve(baseId, id) : id);
+ var refVal = self2._refs[id];
+ if (typeof refVal == "string")
+ refVal = self2._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 {
+ self2._refs[id] = fullPath;
+ }
+ }
+ }
+ baseIds[jsonPtr] = baseId;
+ fullPaths[jsonPtr] = fullPath;
+ });
+ return localRefs;
+ }
+ __name(resolveIds, "resolveIds");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/error_classes.js
+var require_error_classes = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/error_classes.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var resolve18 = require_resolve();
+ module2.exports = {
+ Validation: errorSubclass(ValidationError),
+ MissingRef: errorSubclass(MissingRefError)
+ };
+ function ValidationError(errors) {
+ this.message = "validation failed";
+ this.errors = errors;
+ this.ajv = this.validation = true;
+ }
+ __name(ValidationError, "ValidationError");
+ 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 = resolve18.url(baseId, ref);
+ this.missingSchema = resolve18.normalizeId(resolve18.fullPath(this.missingRef));
+ }
+ __name(MissingRefError, "MissingRefError");
+ function errorSubclass(Subclass) {
+ Subclass.prototype = Object.create(Error.prototype);
+ Subclass.prototype.constructor = Subclass;
+ return Subclass;
+ }
+ __name(errorSubclass, "errorSubclass");
+ }
+});
+
+// ../../node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js
+var require_fast_json_stable_stringify = __commonJS({
+ "../../node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = function(data, opts) {
+ if (!opts)
+ opts = {};
+ if (typeof opts === "function")
+ opts = { cmp: opts };
+ var cycles = typeof opts.cycles === "boolean" ? 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 (/* @__PURE__ */ __name(function stringify(node) {
+ if (node && node.toJSON && typeof node.toJSON === "function") {
+ node = node.toJSON();
+ }
+ if (node === void 0)
+ return;
+ if (typeof node == "number")
+ return isFinite(node) ? "" + node : "null";
+ if (typeof node !== "object")
+ 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 (node === null)
+ return "null";
+ if (seen.indexOf(node) !== -1) {
+ 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)
+ continue;
+ if (out)
+ out += ",";
+ out += JSON.stringify(key) + ":" + value;
+ }
+ seen.splice(seenIndex, 1);
+ return "{" + out + "}";
+ }, "stringify"))(data);
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/validate.js
+var require_validate = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/validate.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_validate(it2, $keyword, $ruleType) {
+ var out = "";
+ var $async = it2.schema.$async === true, $refKeywords = it2.util.schemaHasRulesExcept(it2.schema, it2.RULES.all, "$ref"), $id = it2.self._getId(it2.schema);
+ if (it2.opts.strictKeywords) {
+ var $unknownKwd = it2.util.schemaUnknownRules(it2.schema, it2.RULES.keywords);
+ if ($unknownKwd) {
+ var $keywordsMsg = "unknown keyword: " + $unknownKwd;
+ if (it2.opts.strictKeywords === "log")
+ it2.logger.warn($keywordsMsg);
+ else
+ throw new Error($keywordsMsg);
+ }
+ }
+ if (it2.isTop) {
+ out += " var validate = ";
+ if ($async) {
+ it2.async = true;
+ out += "async ";
+ }
+ out += "function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ";
+ if ($id && (it2.opts.sourceCode || it2.opts.processCode)) {
+ out += " " + ("/*# sourceURL=" + $id + " */") + " ";
+ }
+ }
+ if (typeof it2.schema == "boolean" || !($refKeywords || it2.schema.$ref)) {
+ var $keyword = "false schema";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $errorKeyword;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ if (it2.schema === false) {
+ if (it2.isTop) {
+ $breakOnError = true;
+ } else {
+ out += " var " + $valid + " = false; ";
+ }
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "false schema") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'boolean schema is false' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: false , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.isTop) {
+ if ($async) {
+ out += " return data; ";
+ } else {
+ out += " validate.errors = null; return true; ";
+ }
+ } else {
+ out += " var " + $valid + " = true; ";
+ }
+ }
+ if (it2.isTop) {
+ out += " }; return validate; ";
+ }
+ return out;
+ }
+ if (it2.isTop) {
+ var $top = it2.isTop, $lvl = it2.level = 0, $dataLvl = it2.dataLevel = 0, $data = "data";
+ it2.rootId = it2.resolve.fullPath(it2.self._getId(it2.root.schema));
+ it2.baseId = it2.baseId || it2.rootId;
+ delete it2.isTop;
+ it2.dataPathArr = [""];
+ if (it2.schema.default !== void 0 && it2.opts.useDefaults && it2.opts.strictDefaults) {
+ var $defaultMsg = "default is ignored in the schema root";
+ if (it2.opts.strictDefaults === "log")
+ it2.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 = it2.level, $dataLvl = it2.dataLevel, $data = "data" + ($dataLvl || "");
+ if ($id)
+ it2.baseId = it2.resolve.url(it2.baseId, $id);
+ if ($async && !it2.async)
+ throw new Error("async schema in sync schema");
+ out += " var errs_" + $lvl + " = errors;";
+ }
+ var $valid = "valid" + $lvl, $breakOnError = !it2.opts.allErrors, $closingBraces1 = "", $closingBraces2 = "";
+ var $errorKeyword;
+ var $typeSchema = it2.schema.type, $typeIsArray = Array.isArray($typeSchema);
+ if ($typeSchema && it2.opts.nullable && it2.schema.nullable === true) {
+ if ($typeIsArray) {
+ if ($typeSchema.indexOf("null") == -1)
+ $typeSchema = $typeSchema.concat("null");
+ } else if ($typeSchema != "null") {
+ $typeSchema = [$typeSchema, "null"];
+ $typeIsArray = true;
+ }
+ }
+ if ($typeIsArray && $typeSchema.length == 1) {
+ $typeSchema = $typeSchema[0];
+ $typeIsArray = false;
+ }
+ if (it2.schema.$ref && $refKeywords) {
+ if (it2.opts.extendRefs == "fail") {
+ throw new Error('$ref: validation keywords used in schema at path "' + it2.errSchemaPath + '" (see option extendRefs)');
+ } else if (it2.opts.extendRefs !== true) {
+ $refKeywords = false;
+ it2.logger.warn('$ref: keywords ignored in schema at path "' + it2.errSchemaPath + '"');
+ }
+ }
+ if (it2.schema.$comment && it2.opts.$comment) {
+ out += " " + it2.RULES.all.$comment.code(it2, "$comment");
+ }
+ if ($typeSchema) {
+ if (it2.opts.coerceTypes) {
+ var $coerceToTypes = it2.util.coerceToTypes(it2.opts.coerceTypes, $typeSchema);
+ }
+ var $rulesGroup = it2.RULES.types[$typeSchema];
+ if ($coerceToTypes || $typeIsArray || $rulesGroup === true || $rulesGroup && !$shouldUseGroup($rulesGroup)) {
+ var $schemaPath = it2.schemaPath + ".type", $errSchemaPath = it2.errSchemaPath + "/type";
+ var $schemaPath = it2.schemaPath + ".type", $errSchemaPath = it2.errSchemaPath + "/type", $method = $typeIsArray ? "checkDataTypes" : "checkDataType";
+ out += " if (" + it2.util[$method]($typeSchema, $data, it2.opts.strictNumbers, true) + ") { ";
+ if ($coerceToTypes) {
+ var $dataType = "dataType" + $lvl, $coerced = "coerced" + $lvl;
+ out += " var " + $dataType + " = typeof " + $data + "; var " + $coerced + " = undefined; ";
+ if (it2.opts.coerceTypes == "array") {
+ out += " if (" + $dataType + " == 'object' && Array.isArray(" + $data + ") && " + $data + ".length == 1) { " + $data + " = " + $data + "[0]; " + $dataType + " = typeof " + $data + "; if (" + it2.util.checkDataType(it2.schema.type, $data, it2.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 ($type == "string") {
+ out += " else if (" + $dataType + " == 'number' || " + $dataType + " == 'boolean') " + $coerced + " = '' + " + $data + "; else if (" + $data + " === null) " + $coerced + " = ''; ";
+ } else if ($type == "number" || $type == "integer") {
+ out += " else if (" + $dataType + " == 'boolean' || " + $data + " === null || (" + $dataType + " == 'string' && " + $data + " && " + $data + " == +" + $data + " ";
+ if ($type == "integer") {
+ out += " && !(" + $data + " % 1)";
+ }
+ out += ")) " + $coerced + " = +" + $data + "; ";
+ } else if ($type == "boolean") {
+ out += " else if (" + $data + " === 'false' || " + $data + " === 0 || " + $data + " === null) " + $coerced + " = false; else if (" + $data + " === 'true' || " + $data + " === 1) " + $coerced + " = true; ";
+ } else if ($type == "null") {
+ out += " else if (" + $data + " === '' || " + $data + " === 0 || " + $data + " === false) " + $coerced + " = null; ";
+ } else if (it2.opts.coerceTypes == "array" && $type == "array") {
+ out += " else if (" + $dataType + " == 'string' || " + $dataType + " == 'number' || " + $dataType + " == 'boolean' || " + $data + " == null) " + $coerced + " = [" + $data + "]; ";
+ }
+ }
+ }
+ out += " else { ";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { type: '";
+ if ($typeIsArray) {
+ out += "" + $typeSchema.join(",");
+ } else {
+ out += "" + $typeSchema;
+ }
+ out += "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be ";
+ if ($typeIsArray) {
+ out += "" + $typeSchema.join(",");
+ } else {
+ out += "" + $typeSchema;
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 ? it2.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 (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { type: '";
+ if ($typeIsArray) {
+ out += "" + $typeSchema.join(",");
+ } else {
+ out += "" + $typeSchema;
+ }
+ out += "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be ";
+ if ($typeIsArray) {
+ out += "" + $typeSchema.join(",");
+ } else {
+ out += "" + $typeSchema;
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.schema.$ref && !$refKeywords) {
+ out += " " + it2.RULES.all.$ref.code(it2, "$ref") + " ";
+ if ($breakOnError) {
+ out += " } if (errors === ";
+ if ($top) {
+ out += "0";
+ } else {
+ out += "errs_" + $lvl;
+ }
+ out += ") { ";
+ $closingBraces2 += "}";
+ }
+ } else {
+ var arr2 = it2.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 (" + it2.util.checkDataType($rulesGroup.type, $data, it2.opts.strictNumbers) + ") { ";
+ }
+ if (it2.opts.useDefaults) {
+ if ($rulesGroup.type == "object" && it2.schema.properties) {
+ var $schema = it2.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 ($sch.default !== void 0) {
+ var $passData = $data + it2.util.getProperty($propertyKey);
+ if (it2.compositeRule) {
+ if (it2.opts.strictDefaults) {
+ var $defaultMsg = "default is ignored for: " + $passData;
+ if (it2.opts.strictDefaults === "log")
+ it2.logger.warn($defaultMsg);
+ else
+ throw new Error($defaultMsg);
+ }
+ } else {
+ out += " if (" + $passData + " === undefined ";
+ if (it2.opts.useDefaults == "empty") {
+ out += " || " + $passData + " === null || " + $passData + " === '' ";
+ }
+ out += " ) " + $passData + " = ";
+ if (it2.opts.useDefaults == "shared") {
+ out += " " + it2.useDefault($sch.default) + " ";
+ } else {
+ out += " " + JSON.stringify($sch.default) + " ";
+ }
+ out += "; ";
+ }
+ }
+ }
+ }
+ } else if ($rulesGroup.type == "array" && Array.isArray(it2.schema.items)) {
+ var arr4 = it2.schema.items;
+ if (arr4) {
+ var $sch, $i = -1, l4 = arr4.length - 1;
+ while ($i < l4) {
+ $sch = arr4[$i += 1];
+ if ($sch.default !== void 0) {
+ var $passData = $data + "[" + $i + "]";
+ if (it2.compositeRule) {
+ if (it2.opts.strictDefaults) {
+ var $defaultMsg = "default is ignored for: " + $passData;
+ if (it2.opts.strictDefaults === "log")
+ it2.logger.warn($defaultMsg);
+ else
+ throw new Error($defaultMsg);
+ }
+ } else {
+ out += " if (" + $passData + " === undefined ";
+ if (it2.opts.useDefaults == "empty") {
+ out += " || " + $passData + " === null || " + $passData + " === '' ";
+ }
+ out += " ) " + $passData + " = ";
+ if (it2.opts.useDefaults == "shared") {
+ out += " " + it2.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(it2, $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 = it2.schemaPath + ".type", $errSchemaPath = it2.errSchemaPath + "/type";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "type") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { type: '";
+ if ($typeIsArray) {
+ out += "" + $typeSchema.join(",");
+ } else {
+ out += "" + $typeSchema;
+ }
+ out += "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be ";
+ if ($typeIsArray) {
+ out += "" + $typeSchema.join(",");
+ } else {
+ out += "" + $typeSchema;
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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($rulesGroup2) {
+ var rules = $rulesGroup2.rules;
+ for (var i = 0; i < rules.length; i++)
+ if ($shouldUseRule(rules[i]))
+ return true;
+ }
+ __name($shouldUseGroup, "$shouldUseGroup");
+ function $shouldUseRule($rule2) {
+ return it2.schema[$rule2.keyword] !== void 0 || $rule2.implements && $ruleImplementsSomeKeyword($rule2);
+ }
+ __name($shouldUseRule, "$shouldUseRule");
+ function $ruleImplementsSomeKeyword($rule2) {
+ var impl = $rule2.implements;
+ for (var i = 0; i < impl.length; i++)
+ if (it2.schema[impl[i]] !== void 0)
+ return true;
+ }
+ __name($ruleImplementsSomeKeyword, "$ruleImplementsSomeKeyword");
+ return out;
+ }, "generate_validate");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/index.js
+var require_compile = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var resolve18 = require_resolve();
+ var util3 = require_util9();
+ var errorClasses = require_error_classes();
+ var stableStringify = require_fast_json_stable_stringify();
+ var validateGenerator = require_validate();
+ var ucs2length = util3.ucs2length;
+ var equal = require_fast_deep_equal();
+ var ValidationError = errorClasses.Validation;
+ module2.exports = compile;
+ function compile(schema, root, localRefs, baseId) {
+ var self2 = this, opts = this._opts, refVal = [void 0], refs = {}, patterns = [], patternsHash = {}, defaults = [], defaultsHash = {}, customRules = [];
+ root = root || { schema, refVal, 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 validate2 = compilation.validate;
+ var result = validate2.apply(this, arguments);
+ callValidate.errors = validate2.errors;
+ return result;
+ }
+ __name(callValidate, "callValidate");
+ function localCompile(_schema, _root, localRefs2, baseId2) {
+ var isRoot = !_root || _root && _root.schema == _schema;
+ if (_root.schema != root.schema)
+ return compile.call(self2, _schema, _root, localRefs2, baseId2);
+ var $async = _schema.$async === true;
+ var sourceCode = validateGenerator({
+ isTop: true,
+ schema: _schema,
+ isRoot,
+ baseId: baseId2,
+ root: _root,
+ schemaPath: "",
+ errSchemaPath: "#",
+ errorPath: '""',
+ MissingRefError: errorClasses.MissingRef,
+ RULES,
+ validate: validateGenerator,
+ util: util3,
+ resolve: resolve18,
+ resolveRef,
+ usePattern,
+ useDefault,
+ useCustomRule,
+ opts,
+ formats,
+ logger: self2.logger,
+ self: self2
+ });
+ sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode) + vars(defaults, defaultCode) + vars(customRules, customRuleCode) + sourceCode;
+ if (opts.processCode)
+ sourceCode = opts.processCode(sourceCode, _schema);
+ var validate2;
+ try {
+ var makeValidate = new Function(
+ "self",
+ "RULES",
+ "formats",
+ "root",
+ "refVal",
+ "defaults",
+ "customRules",
+ "equal",
+ "ucs2length",
+ "ValidationError",
+ sourceCode
+ );
+ validate2 = makeValidate(
+ self2,
+ RULES,
+ formats,
+ root,
+ refVal,
+ defaults,
+ customRules,
+ equal,
+ ucs2length,
+ ValidationError
+ );
+ refVal[0] = validate2;
+ } catch (e2) {
+ self2.logger.error("Error compiling schema, function code:", sourceCode);
+ throw e2;
+ }
+ validate2.schema = _schema;
+ validate2.errors = null;
+ validate2.refs = refs;
+ validate2.refVal = refVal;
+ validate2.root = isRoot ? validate2 : _root;
+ if ($async)
+ validate2.$async = true;
+ if (opts.sourceCode === true) {
+ validate2.source = {
+ code: sourceCode,
+ patterns,
+ defaults
+ };
+ }
+ return validate2;
+ }
+ __name(localCompile, "localCompile");
+ function resolveRef(baseId2, ref, isRoot) {
+ ref = resolve18.url(baseId2, ref);
+ var refIndex = refs[ref];
+ var _refVal, refCode;
+ if (refIndex !== void 0) {
+ _refVal = refVal[refIndex];
+ refCode = "refVal[" + refIndex + "]";
+ return resolvedRef(_refVal, refCode);
+ }
+ if (!isRoot && root.refs) {
+ var rootRefId = root.refs[ref];
+ if (rootRefId !== void 0) {
+ _refVal = root.refVal[rootRefId];
+ refCode = addLocalRef(ref, _refVal);
+ return resolvedRef(_refVal, refCode);
+ }
+ }
+ refCode = addLocalRef(ref);
+ var v2 = resolve18.call(self2, localCompile, root, ref);
+ if (v2 === void 0) {
+ var localSchema = localRefs && localRefs[ref];
+ if (localSchema) {
+ v2 = resolve18.inlineRef(localSchema, opts.inlineRefs) ? localSchema : compile.call(self2, localSchema, root, localRefs, baseId2);
+ }
+ }
+ if (v2 === void 0) {
+ removeLocalRef(ref);
+ } else {
+ replaceLocalRef(ref, v2);
+ return resolvedRef(v2, refCode);
+ }
+ }
+ __name(resolveRef, "resolveRef");
+ function addLocalRef(ref, v2) {
+ var refId = refVal.length;
+ refVal[refId] = v2;
+ refs[ref] = refId;
+ return "refVal" + refId;
+ }
+ __name(addLocalRef, "addLocalRef");
+ function removeLocalRef(ref) {
+ delete refs[ref];
+ }
+ __name(removeLocalRef, "removeLocalRef");
+ function replaceLocalRef(ref, v2) {
+ var refId = refs[ref];
+ refVal[refId] = v2;
+ }
+ __name(replaceLocalRef, "replaceLocalRef");
+ function resolvedRef(refVal2, code) {
+ return typeof refVal2 == "object" || typeof refVal2 == "boolean" ? { code, schema: refVal2, inline: true } : { code, $async: refVal2 && !!refVal2.$async };
+ }
+ __name(resolvedRef, "resolvedRef");
+ function usePattern(regexStr) {
+ var index = patternsHash[regexStr];
+ if (index === void 0) {
+ index = patternsHash[regexStr] = patterns.length;
+ patterns[index] = regexStr;
+ }
+ return "pattern" + index;
+ }
+ __name(usePattern, "usePattern");
+ function useDefault(value) {
+ switch (typeof value) {
+ case "boolean":
+ case "number":
+ return "" + value;
+ case "string":
+ return util3.toQuotedString(value);
+ case "object":
+ if (value === null)
+ return "null";
+ var valueStr = stableStringify(value);
+ var index = defaultsHash[valueStr];
+ if (index === void 0) {
+ index = defaultsHash[valueStr] = defaults.length;
+ defaults[index] = value;
+ }
+ return "default" + index;
+ }
+ }
+ __name(useDefault, "useDefault");
+ function useCustomRule(rule, schema2, parentSchema, it2) {
+ if (self2._opts.validateSchema !== false) {
+ 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(schema2);
+ if (!valid) {
+ var message = "keyword schema is invalid: " + self2.errorsText(validateSchema.errors);
+ if (self2._opts.validateSchema == "log")
+ self2.logger.error(message);
+ else
+ throw new Error(message);
+ }
+ }
+ }
+ var compile2 = rule.definition.compile, inline = rule.definition.inline, macro = rule.definition.macro;
+ var validate2;
+ if (compile2) {
+ validate2 = compile2.call(self2, schema2, parentSchema, it2);
+ } else if (macro) {
+ validate2 = macro.call(self2, schema2, parentSchema, it2);
+ if (opts.validateSchema !== false)
+ self2.validateSchema(validate2, true);
+ } else if (inline) {
+ validate2 = inline.call(self2, it2, rule.keyword, schema2, parentSchema);
+ } else {
+ validate2 = rule.definition.validate;
+ if (!validate2)
+ return;
+ }
+ if (validate2 === void 0)
+ throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
+ var index = customRules.length;
+ customRules[index] = validate2;
+ return {
+ code: "customRule" + index,
+ validate: validate2
+ };
+ }
+ __name(useCustomRule, "useCustomRule");
+ }
+ __name(compile, "compile");
+ function checkCompiling(schema, root, baseId) {
+ var index = compIndex.call(this, schema, root, baseId);
+ if (index >= 0)
+ return { index, compiling: true };
+ index = this._compilations.length;
+ this._compilations[index] = {
+ schema,
+ root,
+ baseId
+ };
+ return { index, compiling: false };
+ }
+ __name(checkCompiling, "checkCompiling");
+ function endCompiling(schema, root, baseId) {
+ var i = compIndex.call(this, schema, root, baseId);
+ if (i >= 0)
+ this._compilations.splice(i, 1);
+ }
+ __name(endCompiling, "endCompiling");
+ 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;
+ }
+ __name(compIndex, "compIndex");
+ function patternCode(i, patterns) {
+ return "var pattern" + i + " = new RegExp(" + util3.toQuotedString(patterns[i]) + ");";
+ }
+ __name(patternCode, "patternCode");
+ function defaultCode(i) {
+ return "var default" + i + " = defaults[" + i + "];";
+ }
+ __name(defaultCode, "defaultCode");
+ function refValCode(i, refVal) {
+ return refVal[i] === void 0 ? "" : "var refVal" + i + " = refVal[" + i + "];";
+ }
+ __name(refValCode, "refValCode");
+ function customRuleCode(i) {
+ return "var customRule" + i + " = customRules[" + i + "];";
+ }
+ __name(customRuleCode, "customRuleCode");
+ function vars(arr, statement) {
+ if (!arr.length)
+ return "";
+ var code = "";
+ for (var i = 0; i < arr.length; i++)
+ code += statement(i, arr);
+ return code;
+ }
+ __name(vars, "vars");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/cache.js
+var require_cache = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/cache.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var Cache2 = module2.exports = /* @__PURE__ */ __name(function Cache3() {
+ this._cache = {};
+ }, "Cache");
+ Cache2.prototype.put = /* @__PURE__ */ __name(function Cache_put(key, value) {
+ this._cache[key] = value;
+ }, "Cache_put");
+ Cache2.prototype.get = /* @__PURE__ */ __name(function Cache_get(key) {
+ return this._cache[key];
+ }, "Cache_get");
+ Cache2.prototype.del = /* @__PURE__ */ __name(function Cache_del(key) {
+ delete this._cache[key];
+ }, "Cache_del");
+ Cache2.prototype.clear = /* @__PURE__ */ __name(function Cache_clear() {
+ this._cache = {};
+ }, "Cache_clear");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/formats.js
+var require_formats2 = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/formats.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var util3 = require_util9();
+ 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 URL4 = /^(?:(?: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)*)*)$/;
+ module2.exports = formats;
+ function formats(mode) {
+ mode = mode == "full" ? "full" : "fast";
+ return util3.copy(formats[mode]);
+ }
+ __name(formats, "formats");
+ formats.fast = {
+ // date: http://tools.ietf.org/html/rfc3339#section-5.6
+ date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
+ // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
+ 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: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
+ uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
+ "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
+ "uri-template": URITEMPLATE,
+ url: URL4,
+ // email (sources from jsen validator):
+ // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
+ // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
+ 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,
+ // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
+ ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
+ // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
+ 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,
+ // uuid: http://tools.ietf.org/html/rfc4122
+ uuid: UUID,
+ // JSON-pointer: https://tools.ietf.org/html/rfc6901
+ // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
+ "json-pointer": JSON_POINTER,
+ "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
+ // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
+ "relative-json-pointer": RELATIVE_JSON_POINTER
+ };
+ formats.full = {
+ date,
+ time,
+ "date-time": date_time,
+ uri,
+ "uri-reference": URIREF,
+ "uri-template": URITEMPLATE,
+ url: URL4,
+ 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,
+ uuid: UUID,
+ "json-pointer": JSON_POINTER,
+ "json-pointer-uri-fragment": JSON_POINTER_URI_FRAGMENT,
+ "relative-json-pointer": RELATIVE_JSON_POINTER
+ };
+ function isLeapYear(year2) {
+ return year2 % 4 === 0 && (year2 % 100 !== 0 || year2 % 400 === 0);
+ }
+ __name(isLeapYear, "isLeapYear");
+ function date(str) {
+ var matches = str.match(DATE);
+ if (!matches)
+ return false;
+ var year2 = +matches[1];
+ var month2 = +matches[2];
+ var day2 = +matches[3];
+ return month2 >= 1 && month2 <= 12 && day2 >= 1 && day2 <= (month2 == 2 && isLeapYear(year2) ? 29 : DAYS[month2]);
+ }
+ __name(date, "date");
+ function time(str, full) {
+ var matches = str.match(TIME);
+ if (!matches)
+ return false;
+ var hour2 = matches[1];
+ var minute2 = matches[2];
+ var second = matches[3];
+ var timeZone = matches[5];
+ return (hour2 <= 23 && minute2 <= 59 && second <= 59 || hour2 == 23 && minute2 == 59 && second == 60) && (!full || timeZone);
+ }
+ __name(time, "time");
+ var DATE_TIME_SEPARATOR = /t|\s/i;
+ function date_time(str) {
+ var dateTime = str.split(DATE_TIME_SEPARATOR);
+ return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
+ }
+ __name(date_time, "date_time");
+ var NOT_URI_FRAGMENT = /\/|:/;
+ function uri(str) {
+ return NOT_URI_FRAGMENT.test(str) && URI.test(str);
+ }
+ __name(uri, "uri");
+ var Z_ANCHOR = /[^\\]\\Z/;
+ function regex(str) {
+ if (Z_ANCHOR.test(str))
+ return false;
+ try {
+ new RegExp(str);
+ return true;
+ } catch (e2) {
+ return false;
+ }
+ }
+ __name(regex, "regex");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/ref.js
+var require_ref = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/ref.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_ref(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $async, $refCode;
+ if ($schema == "#" || $schema == "#/") {
+ if (it2.isRoot) {
+ $async = it2.async;
+ $refCode = "validate";
+ } else {
+ $async = it2.root.schema.$async === true;
+ $refCode = "root.refVal[0]";
+ }
+ } else {
+ var $refVal = it2.resolveRef(it2.baseId, $schema, it2.isRoot);
+ if ($refVal === void 0) {
+ var $message = it2.MissingRefError.message(it2.baseId, $schema);
+ if (it2.opts.missingRefs == "fail") {
+ it2.logger.error($message);
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: '$ref' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { ref: '" + it2.util.escapeQuotes($schema) + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'can\\'t resolve reference " + it2.util.escapeQuotes($schema) + "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: " + it2.util.toQuotedString($schema) + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts.missingRefs == "ignore") {
+ it2.logger.warn($message);
+ if ($breakOnError) {
+ out += " if (true) { ";
+ }
+ } else {
+ throw new it2.MissingRefError(it2.baseId, $schema, $message);
+ }
+ } else if ($refVal.inline) {
+ var $it = it2.util.copy(it2);
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ $it.schema = $refVal.schema;
+ $it.schemaPath = "";
+ $it.errSchemaPath = $schema;
+ var $code = it2.validate($it).replace(/validate\.schema/g, $refVal.code);
+ out += " " + $code + " ";
+ if ($breakOnError) {
+ out += " if (" + $nextValid + ") { ";
+ }
+ } else {
+ $async = $refVal.$async === true || it2.async && $refVal.$async !== false;
+ $refCode = $refVal.code;
+ }
+ }
+ if ($refCode) {
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.opts.passContext) {
+ out += " " + $refCode + ".call(this, ";
+ } else {
+ out += " " + $refCode + "( ";
+ }
+ out += " " + $data + ", (dataPath || '')";
+ if (it2.errorPath != '""') {
+ out += " + " + it2.errorPath;
+ }
+ var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it2.dataPathArr[$dataLvl] : "parentDataProperty";
+ out += " , " + $parentData + " , " + $parentDataProperty + ", rootData) ";
+ var __callValidate = out;
+ out = $$outStack.pop();
+ if ($async) {
+ if (!it2.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;
+ }, "generate_ref");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/allOf.js
+var require_allOf = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/allOf.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_allOf(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $it = it2.util.copy(it2);
+ 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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
+ $allSchemasEmpty = false;
+ $it.schema = $sch;
+ $it.schemaPath = $schemaPath + "[" + $i + "]";
+ $it.errSchemaPath = $errSchemaPath + "/" + $i;
+ out += " " + it2.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;
+ }, "generate_allOf");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/anyOf.js
+var require_anyOf = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/anyOf.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_anyOf(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ var $noEmptySchema = $schema.every(function($sch2) {
+ return it2.opts.strictKeywords ? typeof $sch2 == "object" && Object.keys($sch2).length > 0 || $sch2 === false : it2.util.schemaHasRules($sch2, it2.RULES.all);
+ });
+ if ($noEmptySchema) {
+ var $currentBaseId = $it.baseId;
+ out += " var " + $errs + " = errors; var " + $valid + " = false; ";
+ var $wasComposite = it2.compositeRule;
+ it2.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 += " " + it2.validate($it) + " ";
+ $it.baseId = $currentBaseId;
+ out += " " + $valid + " = " + $valid + " || " + $nextValid + "; if (!" + $valid + ") { ";
+ $closingBraces += "}";
+ }
+ }
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ out += " " + $closingBraces + " if (!" + $valid + ") { var err = ";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'anyOf' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should match some schema in anyOf' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts.allErrors) {
+ out += " } ";
+ }
+ } else {
+ if ($breakOnError) {
+ out += " if (true) { ";
+ }
+ }
+ return out;
+ }, "generate_anyOf");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/comment.js
+var require_comment = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/comment.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_comment(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $schema = it2.schema[$keyword];
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $comment = it2.util.toQuotedString($schema);
+ if (it2.opts.$comment === true) {
+ out += " console.log(" + $comment + ");";
+ } else if (typeof it2.opts.$comment == "function") {
+ out += " self._opts.$comment(" + $comment + ", " + it2.util.toQuotedString($errSchemaPath) + ", validate.root.schema);";
+ }
+ return out;
+ }, "generate_comment");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/const.js
+var require_const = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/const.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_const(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ 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 (it2.createErrors !== false) {
+ out += " { keyword: 'const' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { allowedValue: schema" + $lvl + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be equal to constant' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_const");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/contains.js
+var require_contains = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/contains.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_contains(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it2.baseId, $nonEmptySchema = it2.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it2.util.schemaHasRules($schema, it2.RULES.all);
+ out += "var " + $errs + " = errors;var " + $valid + ";";
+ if ($nonEmptySchema) {
+ var $wasComposite = it2.compositeRule;
+ it2.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 = it2.util.getPathExpr(it2.errorPath, $idx, it2.opts.jsonPointers, true);
+ var $passData = $data + "[" + $idx + "]";
+ $it.dataPathArr[$dataNxt] = $idx;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
+ } else {
+ out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
+ }
+ out += " if (" + $nextValid + ") break; } ";
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ out += " " + $closingBraces + " if (!" + $nextValid + ") {";
+ } else {
+ out += " if (" + $data + ".length == 0) {";
+ }
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'contains' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should contain a valid item' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts.allErrors) {
+ out += " } ";
+ }
+ return out;
+ }, "generate_contains");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/dependencies.js
+var require_dependencies = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/dependencies.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_dependencies(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ var $schemaDeps = {}, $propertyDeps = {}, $ownProperties = it2.opts.ownProperties;
+ for ($property in $schema) {
+ if ($property == "__proto__")
+ continue;
+ var $sch = $schema[$property];
+ var $deps = Array.isArray($sch) ? $propertyDeps : $schemaDeps;
+ $deps[$property] = $sch;
+ }
+ out += "var " + $errs + " = errors;";
+ var $currentErrorPath = it2.errorPath;
+ out += "var missing" + $lvl + ";";
+ for (var $property in $propertyDeps) {
+ $deps = $propertyDeps[$property];
+ if ($deps.length) {
+ out += " if ( " + $data + it2.util.getProperty($property) + " !== undefined ";
+ if ($ownProperties) {
+ out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.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 = it2.util.getProperty($propertyKey), $useData = $data + $prop;
+ out += " ( ( " + $useData + " === undefined ";
+ if ($ownProperties) {
+ out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
+ }
+ out += ") && (missing" + $lvl + " = " + it2.util.toQuotedString(it2.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
+ }
+ }
+ out += ")) { ";
+ var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
+ if (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.opts.jsonPointers ? it2.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
+ }
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it2.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it2.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should have ";
+ if ($deps.length == 1) {
+ out += "property " + it2.util.escapeQuotes($deps[0]);
+ } else {
+ out += "properties " + it2.util.escapeQuotes($deps.join(", "));
+ }
+ out += " when property " + it2.util.escapeQuotes($property) + " is present' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 = it2.util.getProperty($propertyKey), $missingProperty = it2.util.escapeQuotes($propertyKey), $useData = $data + $prop;
+ if (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.util.getPath($currentErrorPath, $propertyKey, it2.opts.jsonPointers);
+ }
+ out += " if ( " + $useData + " === undefined ";
+ if ($ownProperties) {
+ out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
+ }
+ out += ") { var err = ";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'dependencies' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { property: '" + it2.util.escapeQuotes($property) + "', missingProperty: '" + $missingProperty + "', depsCount: " + $deps.length + ", deps: '" + it2.util.escapeQuotes($deps.length == 1 ? $deps[0] : $deps.join(", ")) + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should have ";
+ if ($deps.length == 1) {
+ out += "property " + it2.util.escapeQuotes($deps[0]);
+ } else {
+ out += "properties " + it2.util.escapeQuotes($deps.join(", "));
+ }
+ out += " when property " + it2.util.escapeQuotes($property) + " is present' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
+ }
+ }
+ }
+ out += " } ";
+ if ($breakOnError) {
+ $closingBraces += "}";
+ out += " else { ";
+ }
+ }
+ }
+ it2.errorPath = $currentErrorPath;
+ var $currentBaseId = $it.baseId;
+ for (var $property in $schemaDeps) {
+ var $sch = $schemaDeps[$property];
+ if (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
+ out += " " + $nextValid + " = true; if ( " + $data + it2.util.getProperty($property) + " !== undefined ";
+ if ($ownProperties) {
+ out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($property) + "') ";
+ }
+ out += ") { ";
+ $it.schema = $sch;
+ $it.schemaPath = $schemaPath + it2.util.getProperty($property);
+ $it.errSchemaPath = $errSchemaPath + "/" + it2.util.escapeFragment($property);
+ out += " " + it2.validate($it) + " ";
+ $it.baseId = $currentBaseId;
+ out += " } ";
+ if ($breakOnError) {
+ out += " if (" + $nextValid + ") { ";
+ $closingBraces += "}";
+ }
+ }
+ }
+ if ($breakOnError) {
+ out += " " + $closingBraces + " if (" + $errs + " == errors) {";
+ }
+ return out;
+ }, "generate_dependencies");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/enum.js
+var require_enum = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/enum.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_enum(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ 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 (it2.createErrors !== false) {
+ out += " { keyword: 'enum' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { allowedValues: schema" + $lvl + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be equal to one of the allowed values' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_enum");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/format.js
+var require_format = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/format.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_format(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ if (it2.opts.format === false) {
+ if ($breakOnError) {
+ out += " if (true) { ";
+ }
+ return out;
+ }
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ var $unknownFormats = it2.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 (it2.async) {
+ out += " var async" + $lvl + " = " + $format + ".async; ";
+ }
+ out += " " + $format + " = " + $format + ".validate; } if ( ";
+ if ($isData) {
+ out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
+ }
+ out += " (";
+ if ($unknownFormats != "ignore") {
+ out += " (" + $schemaValue + " && !" + $format + " ";
+ if ($allowUnknown) {
+ out += " && self._opts.unknownFormats.indexOf(" + $schemaValue + ") == -1 ";
+ }
+ out += ") || ";
+ }
+ out += " (" + $format + " && " + $formatType + " == '" + $ruleType + "' && !(typeof " + $format + " == 'function' ? ";
+ if (it2.async) {
+ out += " (async" + $lvl + " ? await " + $format + "(" + $data + ") : " + $format + "(" + $data + ")) ";
+ } else {
+ out += " " + $format + "(" + $data + ") ";
+ }
+ out += " : " + $format + ".test(" + $data + "))))) {";
+ } else {
+ var $format = it2.formats[$schema];
+ if (!$format) {
+ if ($unknownFormats == "ignore") {
+ it2.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it2.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 "' + it2.errSchemaPath + '"');
+ }
+ }
+ var $isObject = typeof $format == "object" && !($format instanceof RegExp) && $format.validate;
+ var $formatType = $isObject && $format.type || "string";
+ if ($isObject) {
+ var $async = $format.async === true;
+ $format = $format.validate;
+ }
+ if ($formatType != $ruleType) {
+ if ($breakOnError) {
+ out += " if (true) { ";
+ }
+ return out;
+ }
+ if ($async) {
+ if (!it2.async)
+ throw new Error("async format in sync schema");
+ var $formatRef = "formats" + it2.util.getProperty($schema) + ".validate";
+ out += " if (!(await " + $formatRef + "(" + $data + "))) { ";
+ } else {
+ out += " if (! ";
+ var $formatRef = "formats" + it2.util.getProperty($schema);
+ if ($isObject)
+ $formatRef += ".validate";
+ if (typeof $format == "function") {
+ out += " " + $formatRef + "(" + $data + ") ";
+ } else {
+ out += " " + $formatRef + ".test(" + $data + ") ";
+ }
+ out += ") { ";
+ }
+ }
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'format' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { format: ";
+ if ($isData) {
+ out += "" + $schemaValue;
+ } else {
+ out += "" + it2.util.toQuotedString($schema);
+ }
+ out += " } ";
+ if (it2.opts.messages !== false) {
+ out += ` , message: 'should match format "`;
+ if ($isData) {
+ out += "' + " + $schemaValue + " + '";
+ } else {
+ out += "" + it2.util.escapeQuotes($schema);
+ }
+ out += `"' `;
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + it2.util.toQuotedString($schema);
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_format");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/if.js
+var require_if = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/if.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_if(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ var $thenSch = it2.schema["then"], $elseSch = it2.schema["else"], $thenPresent = $thenSch !== void 0 && (it2.opts.strictKeywords ? typeof $thenSch == "object" && Object.keys($thenSch).length > 0 || $thenSch === false : it2.util.schemaHasRules($thenSch, it2.RULES.all)), $elsePresent = $elseSch !== void 0 && (it2.opts.strictKeywords ? typeof $elseSch == "object" && Object.keys($elseSch).length > 0 || $elseSch === false : it2.util.schemaHasRules($elseSch, it2.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 = it2.compositeRule;
+ it2.compositeRule = $it.compositeRule = true;
+ out += " " + it2.validate($it) + " ";
+ $it.baseId = $currentBaseId;
+ $it.createErrors = true;
+ out += " errors = " + $errs + "; if (vErrors !== null) { if (" + $errs + ") vErrors.length = " + $errs + "; else vErrors = null; } ";
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ if ($thenPresent) {
+ out += " if (" + $nextValid + ") { ";
+ $it.schema = it2.schema["then"];
+ $it.schemaPath = it2.schemaPath + ".then";
+ $it.errSchemaPath = it2.errSchemaPath + "/then";
+ out += " " + it2.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 = it2.schema["else"];
+ $it.schemaPath = it2.schemaPath + ".else";
+ $it.errSchemaPath = it2.errSchemaPath + "/else";
+ out += " " + it2.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 (it2.createErrors !== false) {
+ out += " { keyword: 'if' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { failingKeyword: " + $ifClause + " } ";
+ if (it2.opts.messages !== false) {
+ out += ` , message: 'should match "' + ` + $ifClause + ` + '" schema' `;
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_if");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/items.js
+var require_items = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/items.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_items(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ var $idx = "i" + $lvl, $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $currentBaseId = it2.baseId;
+ out += "var " + $errs + " = errors;var " + $valid + ";";
+ if (Array.isArray($schema)) {
+ var $additionalItems = it2.schema.additionalItems;
+ if ($additionalItems === false) {
+ out += " " + $valid + " = " + $data + ".length <= " + $schema.length + "; ";
+ var $currErrSchemaPath = $errSchemaPath;
+ $errSchemaPath = it2.errSchemaPath + "/additionalItems";
+ out += " if (!" + $valid + ") { ";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'additionalItems' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schema.length + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT have more than " + $schema.length + " items' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: false , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.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 = it2.util.getPathExpr(it2.errorPath, $i, it2.opts.jsonPointers, true);
+ $it.dataPathArr[$dataNxt] = $i;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
+ } else {
+ out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
+ }
+ out += " } ";
+ if ($breakOnError) {
+ out += " if (" + $nextValid + ") { ";
+ $closingBraces += "}";
+ }
+ }
+ }
+ }
+ if (typeof $additionalItems == "object" && (it2.opts.strictKeywords ? typeof $additionalItems == "object" && Object.keys($additionalItems).length > 0 || $additionalItems === false : it2.util.schemaHasRules($additionalItems, it2.RULES.all))) {
+ $it.schema = $additionalItems;
+ $it.schemaPath = it2.schemaPath + ".additionalItems";
+ $it.errSchemaPath = it2.errSchemaPath + "/additionalItems";
+ out += " " + $nextValid + " = true; if (" + $data + ".length > " + $schema.length + ") { for (var " + $idx + " = " + $schema.length + "; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
+ $it.errorPath = it2.util.getPathExpr(it2.errorPath, $idx, it2.opts.jsonPointers, true);
+ var $passData = $data + "[" + $idx + "]";
+ $it.dataPathArr[$dataNxt] = $idx;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.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 (it2.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it2.util.schemaHasRules($schema, it2.RULES.all)) {
+ $it.schema = $schema;
+ $it.schemaPath = $schemaPath;
+ $it.errSchemaPath = $errSchemaPath;
+ out += " for (var " + $idx + " = 0; " + $idx + " < " + $data + ".length; " + $idx + "++) { ";
+ $it.errorPath = it2.util.getPathExpr(it2.errorPath, $idx, it2.opts.jsonPointers, true);
+ var $passData = $data + "[" + $idx + "]";
+ $it.dataPathArr[$dataNxt] = $idx;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.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;
+ }, "generate_items");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limit.js
+var require_limit = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limit.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate__limit(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $errorKeyword;
+ var $data = "data" + ($dataLvl || "");
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ var $isMax = $keyword == "maximum", $exclusiveKeyword = $isMax ? "exclusiveMaximum" : "exclusiveMinimum", $schemaExcl = it2.schema[$exclusiveKeyword], $isDataExcl = it2.opts.$data && $schemaExcl && $schemaExcl.$data, $op = $isMax ? "<" : ">", $notOp = $isMax ? ">" : "<", $errorKeyword = void 0;
+ if (!($isData || typeof $schema == "number" || $schema === void 0)) {
+ throw new Error($keyword + " must be number");
+ }
+ if (!($isDataExcl || $schemaExcl === void 0 || typeof $schemaExcl == "number" || typeof $schemaExcl == "boolean")) {
+ throw new Error($exclusiveKeyword + " must be number or boolean");
+ }
+ if ($isDataExcl) {
+ var $schemaValueExcl = it2.util.getData($schemaExcl.$data, $dataLvl, it2.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 (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "_exclusiveLimit") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '" + $exclusiveKeyword + " should be boolean' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 ($schema === void 0) {
+ $errorKeyword = $exclusiveKeyword;
+ $errSchemaPath = it2.errSchemaPath + "/" + $exclusiveKeyword;
+ $schemaValue = $schemaValueExcl;
+ $isData = $isDataExcl;
+ }
+ } else {
+ var $exclIsNumber = typeof $schemaExcl == "number", $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 && $schema === void 0) {
+ $exclusive = true;
+ $errorKeyword = $exclusiveKeyword;
+ $errSchemaPath = it2.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 = it2.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 (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "_limit") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { comparison: " + $opExpr + ", limit: " + $schemaValue + ", exclusive: " + $exclusive + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be " + $opStr + " ";
+ if ($isData) {
+ out += "' + " + $schemaValue;
+ } else {
+ out += "" + $schemaValue + "'";
+ }
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + $schema;
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate__limit");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitItems.js
+var require_limitItems = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitItems.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate__limitItems(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $errorKeyword;
+ var $data = "data" + ($dataLvl || "");
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ if (!($isData || typeof $schema == "number")) {
+ throw new Error($keyword + " must be number");
+ }
+ var $op = $keyword == "maxItems" ? ">" : "<";
+ 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 (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "_limitItems") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT have ";
+ if ($keyword == "maxItems") {
+ out += "more";
+ } else {
+ out += "fewer";
+ }
+ out += " than ";
+ if ($isData) {
+ out += "' + " + $schemaValue + " + '";
+ } else {
+ out += "" + $schema;
+ }
+ out += " items' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + $schema;
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate__limitItems");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitLength.js
+var require_limitLength = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitLength.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate__limitLength(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $errorKeyword;
+ var $data = "data" + ($dataLvl || "");
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ if (!($isData || typeof $schema == "number")) {
+ throw new Error($keyword + " must be number");
+ }
+ var $op = $keyword == "maxLength" ? ">" : "<";
+ out += "if ( ";
+ if ($isData) {
+ out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'number') || ";
+ }
+ if (it2.opts.unicode === false) {
+ out += " " + $data + ".length ";
+ } else {
+ out += " ucs2length(" + $data + ") ";
+ }
+ out += " " + $op + " " + $schemaValue + ") { ";
+ var $errorKeyword = $keyword;
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "_limitLength") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT be ";
+ if ($keyword == "maxLength") {
+ out += "longer";
+ } else {
+ out += "shorter";
+ }
+ out += " than ";
+ if ($isData) {
+ out += "' + " + $schemaValue + " + '";
+ } else {
+ out += "" + $schema;
+ }
+ out += " characters' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + $schema;
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate__limitLength");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitProperties.js
+var require_limitProperties = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/_limitProperties.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate__limitProperties(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $errorKeyword;
+ var $data = "data" + ($dataLvl || "");
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ if (!($isData || typeof $schema == "number")) {
+ throw new Error($keyword + " must be number");
+ }
+ var $op = $keyword == "maxProperties" ? ">" : "<";
+ 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 (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "_limitProperties") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { limit: " + $schemaValue + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT have ";
+ if ($keyword == "maxProperties") {
+ out += "more";
+ } else {
+ out += "fewer";
+ }
+ out += " than ";
+ if ($isData) {
+ out += "' + " + $schemaValue + " + '";
+ } else {
+ out += "" + $schema;
+ }
+ out += " properties' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + $schema;
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate__limitProperties");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/multipleOf.js
+var require_multipleOf = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/multipleOf.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_multipleOf(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ if (!($isData || typeof $schema == "number")) {
+ 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 (it2.opts.multipleOfPrecision) {
+ out += " Math.abs(Math.round(division" + $lvl + ") - division" + $lvl + ") > 1e-" + it2.opts.multipleOfPrecision + " ";
+ } else {
+ out += " division" + $lvl + " !== parseInt(division" + $lvl + ") ";
+ }
+ out += " ) ";
+ if ($isData) {
+ out += " ) ";
+ }
+ out += " ) { ";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'multipleOf' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { multipleOf: " + $schemaValue + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should be multiple of ";
+ if ($isData) {
+ out += "' + " + $schemaValue;
+ } else {
+ out += "" + $schemaValue + "'";
+ }
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + $schema;
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_multipleOf");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/not.js
+var require_not = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/not.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_not(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ if (it2.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it2.util.schemaHasRules($schema, it2.RULES.all)) {
+ $it.schema = $schema;
+ $it.schemaPath = $schemaPath;
+ $it.errSchemaPath = $errSchemaPath;
+ out += " var " + $errs + " = errors; ";
+ var $wasComposite = it2.compositeRule;
+ it2.compositeRule = $it.compositeRule = true;
+ $it.createErrors = false;
+ var $allErrorsOption;
+ if ($it.opts.allErrors) {
+ $allErrorsOption = $it.opts.allErrors;
+ $it.opts.allErrors = false;
+ }
+ out += " " + it2.validate($it) + " ";
+ $it.createErrors = true;
+ if ($allErrorsOption)
+ $it.opts.allErrors = $allErrorsOption;
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ out += " if (" + $nextValid + ") { ";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT be valid' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts.allErrors) {
+ out += " } ";
+ }
+ } else {
+ out += " var err = ";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'not' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: {} ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT be valid' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
+ if ($breakOnError) {
+ out += " if (false) { ";
+ }
+ }
+ return out;
+ }, "generate_not");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/oneOf.js
+var require_oneOf = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/oneOf.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_oneOf(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ 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 = it2.compositeRule;
+ it2.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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
+ $it.schema = $sch;
+ $it.schemaPath = $schemaPath + "[" + $i + "]";
+ $it.errSchemaPath = $errSchemaPath + "/" + $i;
+ out += " " + it2.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 + "; }";
+ }
+ }
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ out += "" + $closingBraces + "if (!" + $valid + ") { var err = ";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'oneOf' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { passingSchemas: " + $passingSchemas + " } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should match exactly one schema in oneOf' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts.allErrors) {
+ out += " } ";
+ }
+ return out;
+ }, "generate_oneOf");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/pattern.js
+var require_pattern = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/pattern.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_pattern(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ var $regexp = $isData ? "(new RegExp(" + $schemaValue + "))" : it2.usePattern($schema);
+ out += "if ( ";
+ if ($isData) {
+ out += " (" + $schemaValue + " !== undefined && typeof " + $schemaValue + " != 'string') || ";
+ }
+ out += " !" + $regexp + ".test(" + $data + ") ) { ";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'pattern' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { pattern: ";
+ if ($isData) {
+ out += "" + $schemaValue;
+ } else {
+ out += "" + it2.util.toQuotedString($schema);
+ }
+ out += " } ";
+ if (it2.opts.messages !== false) {
+ out += ` , message: 'should match pattern "`;
+ if ($isData) {
+ out += "' + " + $schemaValue + " + '";
+ } else {
+ out += "" + it2.util.escapeQuotes($schema);
+ }
+ out += `"' `;
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + it2.util.toQuotedString($schema);
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_pattern");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/properties.js
+var require_properties = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/properties.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_properties(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ var $key = "key" + $lvl, $idx = "idx" + $lvl, $dataNxt = $it.dataLevel = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl;
+ var $schemaKeys = Object.keys($schema || {}).filter(notProto), $pProperties = it2.schema.patternProperties || {}, $pPropertyKeys = Object.keys($pProperties).filter(notProto), $aProperties = it2.schema.additionalProperties, $someProperties = $schemaKeys.length || $pPropertyKeys.length, $noAdditional = $aProperties === false, $additionalIsSchema = typeof $aProperties == "object" && Object.keys($aProperties).length, $removeAdditional = it2.opts.removeAdditional, $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional, $ownProperties = it2.opts.ownProperties, $currentBaseId = it2.baseId;
+ var $required = it2.schema.required;
+ if ($required && !(it2.opts.$data && $required.$data) && $required.length < it2.opts.loopRequired) {
+ var $requiredHash = it2.util.toHash($required);
+ }
+ function notProto(p) {
+ return p !== "__proto__";
+ }
+ __name(notProto, "notProto");
+ 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 + " == " + it2.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 += " || " + it2.usePattern($pProperty) + ".test(" + $key + ") ";
+ }
+ }
+ }
+ out += " ); if (isAdditional" + $lvl + ") { ";
+ }
+ if ($removeAdditional == "all") {
+ out += " delete " + $data + "[" + $key + "]; ";
+ } else {
+ var $currentErrorPath = it2.errorPath;
+ var $additionalProperty = "' + " + $key + " + '";
+ if (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
+ }
+ if ($noAdditional) {
+ if ($removeAdditional) {
+ out += " delete " + $data + "[" + $key + "]; ";
+ } else {
+ out += " " + $nextValid + " = false; ";
+ var $currErrSchemaPath = $errSchemaPath;
+ $errSchemaPath = it2.errSchemaPath + "/additionalProperties";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'additionalProperties' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { additionalProperty: '" + $additionalProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is an invalid additional property";
+ } else {
+ out += "should NOT have additional properties";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: false , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 ($removeAdditional == "failing") {
+ out += " var " + $errs + " = errors; ";
+ var $wasComposite = it2.compositeRule;
+ it2.compositeRule = $it.compositeRule = true;
+ $it.schema = $aProperties;
+ $it.schemaPath = it2.schemaPath + ".additionalProperties";
+ $it.errSchemaPath = it2.errSchemaPath + "/additionalProperties";
+ $it.errorPath = it2.opts._errorDataPathProperty ? it2.errorPath : it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
+ var $passData = $data + "[" + $key + "]";
+ $it.dataPathArr[$dataNxt] = $key;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.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 + "]; } ";
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ } else {
+ $it.schema = $aProperties;
+ $it.schemaPath = it2.schemaPath + ".additionalProperties";
+ $it.errSchemaPath = it2.errSchemaPath + "/additionalProperties";
+ $it.errorPath = it2.opts._errorDataPathProperty ? it2.errorPath : it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
+ var $passData = $data + "[" + $key + "]";
+ $it.dataPathArr[$dataNxt] = $key;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
+ } else {
+ out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
+ }
+ if ($breakOnError) {
+ out += " if (!" + $nextValid + ") break; ";
+ }
+ }
+ }
+ it2.errorPath = $currentErrorPath;
+ }
+ if ($someProperties) {
+ out += " } ";
+ }
+ out += " } ";
+ if ($breakOnError) {
+ out += " if (" + $nextValid + ") { ";
+ $closingBraces += "}";
+ }
+ }
+ var $useDefaults = it2.opts.useDefaults && !it2.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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
+ var $prop = it2.util.getProperty($propertyKey), $passData = $data + $prop, $hasDefault = $useDefaults && $sch.default !== void 0;
+ $it.schema = $sch;
+ $it.schemaPath = $schemaPath + $prop;
+ $it.errSchemaPath = $errSchemaPath + "/" + it2.util.escapeFragment($propertyKey);
+ $it.errorPath = it2.util.getPath(it2.errorPath, $propertyKey, it2.opts.jsonPointers);
+ $it.dataPathArr[$dataNxt] = it2.util.toQuotedString($propertyKey);
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ $code = it2.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 + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
+ }
+ out += ") { " + $nextValid + " = false; ";
+ var $currentErrorPath = it2.errorPath, $currErrSchemaPath = $errSchemaPath, $missingProperty = it2.util.escapeQuotes($propertyKey);
+ if (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.util.getPath($currentErrorPath, $propertyKey, it2.opts.jsonPointers);
+ }
+ $errSchemaPath = it2.errSchemaPath + "/required";
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is a required property";
+ } else {
+ out += "should have required property \\'" + $missingProperty + "\\'";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ it2.errorPath = $currentErrorPath;
+ out += " } else { ";
+ } else {
+ if ($breakOnError) {
+ out += " if ( " + $useData + " === undefined ";
+ if ($ownProperties) {
+ out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
+ }
+ out += ") { " + $nextValid + " = true; } else { ";
+ } else {
+ out += " if (" + $useData + " !== undefined ";
+ if ($ownProperties) {
+ out += " && Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.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 (it2.opts.strictKeywords ? typeof $sch == "object" && Object.keys($sch).length > 0 || $sch === false : it2.util.schemaHasRules($sch, it2.RULES.all)) {
+ $it.schema = $sch;
+ $it.schemaPath = it2.schemaPath + ".patternProperties" + it2.util.getProperty($pProperty);
+ $it.errSchemaPath = it2.errSchemaPath + "/patternProperties/" + it2.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 (" + it2.usePattern($pProperty) + ".test(" + $key + ")) { ";
+ $it.errorPath = it2.util.getPathExpr(it2.errorPath, $key, it2.opts.jsonPointers);
+ var $passData = $data + "[" + $key + "]";
+ $it.dataPathArr[$dataNxt] = $key;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.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;
+ }, "generate_properties");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/propertyNames.js
+var require_propertyNames = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/propertyNames.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_propertyNames(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $errs = "errs__" + $lvl;
+ var $it = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ out += "var " + $errs + " = errors;";
+ if (it2.opts.strictKeywords ? typeof $schema == "object" && Object.keys($schema).length > 0 || $schema === false : it2.util.schemaHasRules($schema, it2.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 = it2.dataLevel + 1, $nextData = "data" + $dataNxt, $dataProperties = "dataProperties" + $lvl, $ownProperties = it2.opts.ownProperties, $currentBaseId = it2.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 = it2.compositeRule;
+ it2.compositeRule = $it.compositeRule = true;
+ var $code = it2.validate($it);
+ $it.baseId = $currentBaseId;
+ if (it2.util.varOccurences($code, $nextData) < 2) {
+ out += " " + it2.util.varReplace($code, $nextData, $passData) + " ";
+ } else {
+ out += " var " + $nextData + " = " + $passData + "; " + $code + " ";
+ }
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ out += " if (!" + $nextValid + ") { for (var " + $i + "=startErrs" + $lvl + "; " + $i + " 0 || $propertySch === false : it2.util.schemaHasRules($propertySch, it2.RULES.all)))) {
+ $required[$required.length] = $property;
+ }
+ }
+ }
+ } else {
+ var $required = $schema;
+ }
+ }
+ if ($isData || $required.length) {
+ var $currentErrorPath = it2.errorPath, $loopRequired = $isData || $required.length >= it2.opts.loopRequired, $ownProperties = it2.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 (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.util.getPathExpr($currentErrorPath, $propertyPath, it2.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 (it2.createErrors !== false) {
+ out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is a required property";
+ } else {
+ out += "should have required property \\'" + $missingProperty + "\\'";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 = it2.util.getProperty($propertyKey), $useData = $data + $prop;
+ out += " ( ( " + $useData + " === undefined ";
+ if ($ownProperties) {
+ out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
+ }
+ out += ") && (missing" + $lvl + " = " + it2.util.toQuotedString(it2.opts.jsonPointers ? $propertyKey : $prop) + ") ) ";
+ }
+ }
+ out += ") { ";
+ var $propertyPath = "missing" + $lvl, $missingProperty = "' + " + $propertyPath + " + '";
+ if (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.opts.jsonPointers ? it2.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + " + " + $propertyPath;
+ }
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is a required property";
+ } else {
+ out += "should have required property \\'" + $missingProperty + "\\'";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.util.getPathExpr($currentErrorPath, $propertyPath, it2.opts.jsonPointers);
+ }
+ if ($isData) {
+ out += " if (" + $vSchema + " && !Array.isArray(" + $vSchema + ")) { var err = ";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is a required property";
+ } else {
+ out += "should have required property \\'" + $missingProperty + "\\'";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.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 (it2.createErrors !== false) {
+ out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is a required property";
+ } else {
+ out += "should have required property \\'" + $missingProperty + "\\'";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.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 = it2.util.getProperty($propertyKey), $missingProperty = it2.util.escapeQuotes($propertyKey), $useData = $data + $prop;
+ if (it2.opts._errorDataPathProperty) {
+ it2.errorPath = it2.util.getPath($currentErrorPath, $propertyKey, it2.opts.jsonPointers);
+ }
+ out += " if ( " + $useData + " === undefined ";
+ if ($ownProperties) {
+ out += " || ! Object.prototype.hasOwnProperty.call(" + $data + ", '" + it2.util.escapeQuotes($propertyKey) + "') ";
+ }
+ out += ") { var err = ";
+ if (it2.createErrors !== false) {
+ out += " { keyword: 'required' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { missingProperty: '" + $missingProperty + "' } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: '";
+ if (it2.opts._errorDataPathProperty) {
+ out += "is a required property";
+ } else {
+ out += "should have required property \\'" + $missingProperty + "\\'";
+ }
+ out += "' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ out += "; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ";
+ }
+ }
+ }
+ }
+ it2.errorPath = $currentErrorPath;
+ } else if ($breakOnError) {
+ out += " if (true) {";
+ }
+ return out;
+ }, "generate_required");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/uniqueItems.js
+var require_uniqueItems = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/uniqueItems.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_uniqueItems(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.dataPathArr) + "; ";
+ $schemaValue = "schema" + $lvl;
+ } else {
+ $schemaValue = $schema;
+ }
+ if (($schema || $isData) && it2.opts.uniqueItems !== false) {
+ 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 = it2.schema.items && it2.schema.items.type, $typeIsArray = Array.isArray($itemType);
+ if (!$itemType || $itemType == "object" || $itemType == "array" || $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 (" + it2.util[$method]($itemType, "item", it2.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 (it2.createErrors !== false) {
+ out += " { keyword: 'uniqueItems' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { i: i, j: j } ";
+ if (it2.opts.messages !== false) {
+ out += " , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' ";
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: ";
+ if ($isData) {
+ out += "validate.schema" + $schemaPath;
+ } else {
+ out += "" + $schema;
+ }
+ out += " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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;
+ }, "generate_uniqueItems");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/index.js
+var require_dotjs = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = {
+ "$ref": require_ref(),
+ allOf: require_allOf(),
+ anyOf: require_anyOf(),
+ "$comment": require_comment(),
+ const: require_const(),
+ contains: require_contains(),
+ dependencies: require_dependencies(),
+ "enum": require_enum(),
+ format: require_format(),
+ "if": require_if(),
+ items: require_items(),
+ maximum: require_limit(),
+ minimum: require_limit(),
+ maxItems: require_limitItems(),
+ minItems: require_limitItems(),
+ maxLength: require_limitLength(),
+ minLength: require_limitLength(),
+ maxProperties: require_limitProperties(),
+ minProperties: require_limitProperties(),
+ multipleOf: require_multipleOf(),
+ not: require_not(),
+ oneOf: require_oneOf(),
+ pattern: require_pattern(),
+ properties: require_properties(),
+ propertyNames: require_propertyNames(),
+ required: require_required(),
+ uniqueItems: require_uniqueItems(),
+ validate: require_validate()
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/rules.js
+var require_rules = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/rules.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var ruleModules = require_dotjs();
+ var toHash = require_util9().toHash;
+ module2.exports = /* @__PURE__ */ __name(function rules() {
+ 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 (typeof keyword == "object") {
+ 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,
+ 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;
+ }, "rules");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/data.js
+var require_data = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/data.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var KEYWORDS = [
+ "multipleOf",
+ "maximum",
+ "exclusiveMaximum",
+ "minimum",
+ "exclusiveMinimum",
+ "maxLength",
+ "minLength",
+ "pattern",
+ "additionalItems",
+ "maxItems",
+ "minItems",
+ "uniqueItems",
+ "maxProperties",
+ "minProperties",
+ "required",
+ "additionalProperties",
+ "enum",
+ "format",
+ "const"
+ ];
+ module2.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/compile/async.js
+var require_async = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/compile/async.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var MissingRefError = require_error_classes().MissingRef;
+ module2.exports = compileAsync;
+ function compileAsync(schema, meta, callback) {
+ var self2 = this;
+ if (typeof this._opts.loadSchema != "function")
+ throw new Error("options.loadSchema should be a function");
+ if (typeof meta == "function") {
+ callback = meta;
+ meta = void 0;
+ }
+ var p = loadMetaSchemaOf(schema).then(function() {
+ var schemaObj = self2._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 && !self2.getSchema($schema) ? compileAsync.call(self2, { $ref: $schema }, true) : Promise.resolve();
+ }
+ __name(loadMetaSchemaOf, "loadMetaSchemaOf");
+ function _compileAsync(schemaObj) {
+ try {
+ return self2._compile(schemaObj);
+ } catch (e2) {
+ if (e2 instanceof MissingRefError)
+ return loadMissingSchema(e2);
+ throw e2;
+ }
+ function loadMissingSchema(e2) {
+ var ref = e2.missingSchema;
+ if (added(ref))
+ throw new Error("Schema " + ref + " is loaded but " + e2.missingRef + " cannot be resolved");
+ var schemaPromise = self2._loadingSchemas[ref];
+ if (!schemaPromise) {
+ schemaPromise = self2._loadingSchemas[ref] = self2._opts.loadSchema(ref);
+ schemaPromise.then(removePromise, removePromise);
+ }
+ return schemaPromise.then(function(sch) {
+ if (!added(ref)) {
+ return loadMetaSchemaOf(sch).then(function() {
+ if (!added(ref))
+ self2.addSchema(sch, ref, void 0, meta);
+ });
+ }
+ }).then(function() {
+ return _compileAsync(schemaObj);
+ });
+ function removePromise() {
+ delete self2._loadingSchemas[ref];
+ }
+ __name(removePromise, "removePromise");
+ function added(ref2) {
+ return self2._refs[ref2] || self2._schemas[ref2];
+ }
+ __name(added, "added");
+ }
+ __name(loadMissingSchema, "loadMissingSchema");
+ }
+ __name(_compileAsync, "_compileAsync");
+ }
+ __name(compileAsync, "compileAsync");
+ }
+});
+
+// ../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/custom.js
+var require_custom = __commonJS({
+ "../../node_modules/.pnpm/ajv@6.12.6/node_modules/ajv/lib/dotjs/custom.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function generate_custom(it2, $keyword, $ruleType) {
+ var out = " ";
+ var $lvl = it2.level;
+ var $dataLvl = it2.dataLevel;
+ var $schema = it2.schema[$keyword];
+ var $schemaPath = it2.schemaPath + it2.util.getProperty($keyword);
+ var $errSchemaPath = it2.errSchemaPath + "/" + $keyword;
+ var $breakOnError = !it2.opts.allErrors;
+ var $errorKeyword;
+ var $data = "data" + ($dataLvl || "");
+ var $valid = "valid" + $lvl;
+ var $errs = "errs__" + $lvl;
+ var $isData = it2.opts.$data && $schema && $schema.$data, $schemaValue;
+ if ($isData) {
+ out += " var schema" + $lvl + " = " + it2.util.getData($schema.$data, $dataLvl, it2.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 = it2.useCustomRule($rule, $schema, it2.schema, it2);
+ 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 && !it2.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 = it2.util.copy(it2);
+ var $closingBraces = "";
+ $it.level++;
+ var $nextValid = "valid" + $it.level;
+ $it.schema = $ruleValidate.validate;
+ $it.schemaPath = "";
+ var $wasComposite = it2.compositeRule;
+ it2.compositeRule = $it.compositeRule = true;
+ var $code = it2.validate($it).replace(/validate\.schema/g, $validateCode);
+ it2.compositeRule = $it.compositeRule = $wasComposite;
+ out += " " + $code;
+ } else {
+ var $$outStack = $$outStack || [];
+ $$outStack.push(out);
+ out = "";
+ out += " " + $validateCode + ".call( ";
+ if (it2.opts.passContext) {
+ out += "this";
+ } else {
+ out += "self";
+ }
+ if ($compile || $rDef.schema === false) {
+ out += " , " + $data + " ";
+ } else {
+ out += " , " + $schemaValue + " , " + $data + " , validate.schema" + it2.schemaPath + " ";
+ }
+ out += " , (dataPath || '')";
+ if (it2.errorPath != '""') {
+ out += " + " + it2.errorPath;
+ }
+ var $parentData = $dataLvl ? "data" + ($dataLvl - 1 || "") : "parentData", $parentDataProperty = $dataLvl ? it2.dataPathArr[$dataLvl] : "parentDataProperty";
+ out += " , " + $parentData + " , " + $parentDataProperty + " , rootData ) ";
+ var def_callRuleValidate = out;
+ out = $$outStack.pop();
+ if ($rDef.errors === false) {
+ 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 ($rDef.valid === void 0) {
+ 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 (it2.createErrors !== false) {
+ out += " { keyword: '" + ($errorKeyword || "custom") + "' , dataPath: (dataPath || '') + " + it2.errorPath + " , schemaPath: " + it2.util.toQuotedString($errSchemaPath) + " , params: { keyword: '" + $rule.keyword + "' } ";
+ if (it2.opts.messages !== false) {
+ out += ` , message: 'should pass "` + $rule.keyword + `" keyword validation' `;
+ }
+ if (it2.opts.verbose) {
+ out += " , schema: validate.schema" + $schemaPath + " , parentSchema: validate.schema" + it2.schemaPath + " , data: " + $data + " ";
+ }
+ out += " } ";
+ } else {
+ out += " {} ";
+ }
+ var __err = out;
+ out = $$outStack.pop();
+ if (!it2.compositeRule && $breakOnError) {
+ if (it2.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 ($rDef.errors != "full") {
+ out += " for (var " + $i + "=" + $errs + "; " + $i + "=",
+ limit: 0,
+ exclusive: false
+ },
+ message: "should be >= 0"
+ }];
+ return false;
+ }
+ }
+ var valid2 = errors === errs_2;
+ var valid1 = errors === errs_1;
+ validate3.errors = vErrors;
+ return errors === 0;
+ }, "validate");
+ }();
+ refVal2.schema = {
+ "allOf": [{
+ "$ref": "#/definitions/nonNegativeInteger"
+ }, {
+ "default": 0
+ }]
+ };
+ refVal2.errors = null;
+ refVal[2] = refVal2;
+ var refVal3 = function() {
+ return /* @__PURE__ */ __name(function validate3(data, dataPath, parentData, parentDataProperty, rootData) {
+ "use strict";
+ var vErrors = null;
+ var errors = 0;
+ if (rootData === void 0)
+ rootData = data;
+ if (Array.isArray(data)) {
+ if (data.length < 1) {
+ validate3.errors = [{
+ keyword: "minItems",
+ dataPath: (dataPath || "") + "",
+ schemaPath: "#/minItems",
+ params: {
+ limit: 1
+ },
+ message: "should NOT have fewer than 1 items"
+ }];
+ return false;
+ } else {
+ var errs__0 = errors;
+ var valid0;
+ for (var i0 = 0; i0 < data.length; i0++) {
+ var errs_1 = errors;
+ if (!nop(data[i0], (dataPath || "") + "[" + i0 + "]", data, i0, rootData)) {
+ if (vErrors === null)
+ vErrors = nop.errors;
+ else
+ vErrors = vErrors.concat(nop.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ if (!valid1)
+ break;
+ }
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + "",
+ schemaPath: "#/type",
+ params: {
+ type: "array"
+ },
+ message: "should be array"
+ }];
+ return false;
+ }
+ validate3.errors = vErrors;
+ return errors === 0;
+ }, "validate");
+ }();
+ refVal3.schema = {
+ "type": "array",
+ "minItems": 1,
+ "items": {
+ "$ref": "#"
+ }
+ };
+ refVal3.errors = null;
+ refVal[3] = refVal3;
+ var refVal4 = {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "uniqueItems": true,
+ "default": []
+ };
+ refVal[4] = refVal4;
+ var refVal5 = {
+ "enum": ["array", "boolean", "integer", "null", "number", "object", "string"]
+ };
+ refVal[5] = refVal5;
+ return /* @__PURE__ */ __name(function validate3(data, dataPath, parentData, parentDataProperty, rootData) {
+ "use strict";
+ var vErrors = null;
+ var errors = 0;
+ if (rootData === void 0)
+ rootData = data;
+ if ((!data || typeof data !== "object" || Array.isArray(data)) && typeof data !== "boolean") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + "",
+ schemaPath: "#/type",
+ params: {
+ type: "object,boolean"
+ },
+ message: "should be object,boolean"
+ }];
+ return false;
+ }
+ if (data && typeof data === "object" && !Array.isArray(data)) {
+ var errs__0 = errors;
+ var valid1 = true;
+ var data1 = data.$id;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (errors === errs_1) {
+ if (typeof data1 === "string") {
+ if (!formats["uri-reference"].test(data1)) {
+ validate3.errors = [{
+ keyword: "format",
+ dataPath: (dataPath || "") + ".$id",
+ schemaPath: "#/properties/%24id/format",
+ params: {
+ format: "uri-reference"
+ },
+ message: 'should match format "uri-reference"'
+ }];
+ return false;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".$id",
+ schemaPath: "#/properties/%24id/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.$schema;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (errors === errs_1) {
+ if (typeof data1 === "string") {
+ if (!formats.uri.test(data1)) {
+ validate3.errors = [{
+ keyword: "format",
+ dataPath: (dataPath || "") + ".$schema",
+ schemaPath: "#/properties/%24schema/format",
+ params: {
+ format: "uri"
+ },
+ message: 'should match format "uri"'
+ }];
+ return false;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".$schema",
+ schemaPath: "#/properties/%24schema/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.$ref;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (errors === errs_1) {
+ if (typeof data1 === "string") {
+ if (!formats["uri-reference"].test(data1)) {
+ validate3.errors = [{
+ keyword: "format",
+ dataPath: (dataPath || "") + ".$ref",
+ schemaPath: "#/properties/%24ref/format",
+ params: {
+ format: "uri-reference"
+ },
+ message: 'should match format "uri-reference"'
+ }];
+ return false;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".$ref",
+ schemaPath: "#/properties/%24ref/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.$comment === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.$comment !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".$comment",
+ schemaPath: "#/properties/%24comment/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.title === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.title !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".title",
+ schemaPath: "#/properties/title/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.description === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.description !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".description",
+ schemaPath: "#/properties/description/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (valid1) {
+ if (data.readOnly === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.readOnly !== "boolean") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".readOnly",
+ schemaPath: "#/properties/readOnly/type",
+ params: {
+ type: "boolean"
+ },
+ message: "should be boolean"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.examples === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (Array.isArray(data.examples)) {
+ var errs__1 = errors;
+ var valid1;
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".examples",
+ schemaPath: "#/properties/examples/type",
+ params: {
+ type: "array"
+ },
+ message: "should be array"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.multipleOf;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data1 === "number") {
+ if (data1 <= 0 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "exclusiveMinimum",
+ dataPath: (dataPath || "") + ".multipleOf",
+ schemaPath: "#/properties/multipleOf/exclusiveMinimum",
+ params: {
+ comparison: ">",
+ limit: 0,
+ exclusive: true
+ },
+ message: "should be > 0"
+ }];
+ return false;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".multipleOf",
+ schemaPath: "#/properties/multipleOf/type",
+ params: {
+ type: "number"
+ },
+ message: "should be number"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.maximum === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.maximum !== "number") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".maximum",
+ schemaPath: "#/properties/maximum/type",
+ params: {
+ type: "number"
+ },
+ message: "should be number"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.exclusiveMaximum === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.exclusiveMaximum !== "number") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".exclusiveMaximum",
+ schemaPath: "#/properties/exclusiveMaximum/type",
+ params: {
+ type: "number"
+ },
+ message: "should be number"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.minimum === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.minimum !== "number") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".minimum",
+ schemaPath: "#/properties/minimum/type",
+ params: {
+ type: "number"
+ },
+ message: "should be number"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.exclusiveMinimum === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.exclusiveMinimum !== "number") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".exclusiveMinimum",
+ schemaPath: "#/properties/exclusiveMinimum/type",
+ params: {
+ type: "number"
+ },
+ message: "should be number"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.maxLength;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ var errs_2 = errors;
+ if (typeof data1 !== "number" || data1 % 1 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".maxLength",
+ schemaPath: "#/definitions/nonNegativeInteger/type",
+ params: {
+ type: "integer"
+ },
+ message: "should be integer"
+ }];
+ return false;
+ }
+ if (typeof data1 === "number") {
+ if (data1 < 0 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "minimum",
+ dataPath: (dataPath || "") + ".maxLength",
+ schemaPath: "#/definitions/nonNegativeInteger/minimum",
+ params: {
+ comparison: ">=",
+ limit: 0,
+ exclusive: false
+ },
+ message: "should be >= 0"
+ }];
+ return false;
+ }
+ }
+ var valid2 = errors === errs_2;
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.minLength === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!refVal2(data.minLength, (dataPath || "") + ".minLength", data, "minLength", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal2.errors;
+ else
+ vErrors = vErrors.concat(refVal2.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.pattern;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (errors === errs_1) {
+ if (typeof data1 === "string") {
+ if (!formats.regex(data1)) {
+ validate3.errors = [{
+ keyword: "format",
+ dataPath: (dataPath || "") + ".pattern",
+ schemaPath: "#/properties/pattern/format",
+ params: {
+ format: "regex"
+ },
+ message: 'should match format "regex"'
+ }];
+ return false;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".pattern",
+ schemaPath: "#/properties/pattern/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.additionalItems === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.additionalItems, (dataPath || "") + ".additionalItems", data, "additionalItems", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.items;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ var errs__1 = errors;
+ var valid1 = false;
+ var errs_2 = errors;
+ if (!validate3(data1, (dataPath || "") + ".items", data, "items", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid2 = errors === errs_2;
+ valid1 = valid1 || valid2;
+ if (!valid1) {
+ var errs_2 = errors;
+ if (!refVal3(data1, (dataPath || "") + ".items", data, "items", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal3.errors;
+ else
+ vErrors = vErrors.concat(refVal3.errors);
+ errors = vErrors.length;
+ }
+ var valid2 = errors === errs_2;
+ valid1 = valid1 || valid2;
+ }
+ if (!valid1) {
+ var err = {
+ keyword: "anyOf",
+ dataPath: (dataPath || "") + ".items",
+ schemaPath: "#/properties/items/anyOf",
+ params: {},
+ message: "should match some schema in anyOf"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ validate3.errors = vErrors;
+ return false;
+ } else {
+ errors = errs__1;
+ if (vErrors !== null) {
+ if (errs__1)
+ vErrors.length = errs__1;
+ else
+ vErrors = null;
+ }
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.maxItems;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ var errs_2 = errors;
+ if (typeof data1 !== "number" || data1 % 1 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".maxItems",
+ schemaPath: "#/definitions/nonNegativeInteger/type",
+ params: {
+ type: "integer"
+ },
+ message: "should be integer"
+ }];
+ return false;
+ }
+ if (typeof data1 === "number") {
+ if (data1 < 0 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "minimum",
+ dataPath: (dataPath || "") + ".maxItems",
+ schemaPath: "#/definitions/nonNegativeInteger/minimum",
+ params: {
+ comparison: ">=",
+ limit: 0,
+ exclusive: false
+ },
+ message: "should be >= 0"
+ }];
+ return false;
+ }
+ }
+ var valid2 = errors === errs_2;
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.minItems === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!refVal[2](data.minItems, (dataPath || "") + ".minItems", data, "minItems", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal[2].errors;
+ else
+ vErrors = vErrors.concat(refVal[2].errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.uniqueItems === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.uniqueItems !== "boolean") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".uniqueItems",
+ schemaPath: "#/properties/uniqueItems/type",
+ params: {
+ type: "boolean"
+ },
+ message: "should be boolean"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.contains === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.contains, (dataPath || "") + ".contains", data, "contains", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.maxProperties;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ var errs_2 = errors;
+ if (typeof data1 !== "number" || data1 % 1 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".maxProperties",
+ schemaPath: "#/definitions/nonNegativeInteger/type",
+ params: {
+ type: "integer"
+ },
+ message: "should be integer"
+ }];
+ return false;
+ }
+ if (typeof data1 === "number") {
+ if (data1 < 0 || data1 !== data1) {
+ validate3.errors = [{
+ keyword: "minimum",
+ dataPath: (dataPath || "") + ".maxProperties",
+ schemaPath: "#/definitions/nonNegativeInteger/minimum",
+ params: {
+ comparison: ">=",
+ limit: 0,
+ exclusive: false
+ },
+ message: "should be >= 0"
+ }];
+ return false;
+ }
+ }
+ var valid2 = errors === errs_2;
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.minProperties === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!refVal[2](data.minProperties, (dataPath || "") + ".minProperties", data, "minProperties", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal[2].errors;
+ else
+ vErrors = vErrors.concat(refVal[2].errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.required;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ var errs_2 = errors;
+ if (Array.isArray(data1)) {
+ var errs__2 = errors;
+ var valid2;
+ for (var i2 = 0; i2 < data1.length; i2++) {
+ var errs_3 = errors;
+ if (typeof data1[i2] !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".required[" + i2 + "]",
+ schemaPath: "#/definitions/stringArray/items/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid3 = errors === errs_3;
+ if (!valid3)
+ break;
+ }
+ if (errs__2 == errors) {
+ var i = data1.length, valid2 = true, j;
+ if (i > 1) {
+ var itemIndices = {}, item;
+ for (; i--; ) {
+ var item = data1[i];
+ if (typeof item !== "string")
+ continue;
+ if (typeof itemIndices[item] == "number") {
+ valid2 = false;
+ j = itemIndices[item];
+ break;
+ }
+ itemIndices[item] = i;
+ }
+ }
+ if (!valid2) {
+ validate3.errors = [{
+ keyword: "uniqueItems",
+ dataPath: (dataPath || "") + ".required",
+ schemaPath: "#/definitions/stringArray/uniqueItems",
+ params: {
+ i,
+ j
+ },
+ message: "should NOT have duplicate items (items ## " + j + " and " + i + " are identical)"
+ }];
+ return false;
+ }
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".required",
+ schemaPath: "#/definitions/stringArray/type",
+ params: {
+ type: "array"
+ },
+ message: "should be array"
+ }];
+ return false;
+ }
+ var valid2 = errors === errs_2;
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.additionalProperties === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.additionalProperties, (dataPath || "") + ".additionalProperties", data, "additionalProperties", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.definitions;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (data1 && typeof data1 === "object" && !Array.isArray(data1)) {
+ var errs__1 = errors;
+ var valid2 = true;
+ for (var key1 in data1) {
+ var errs_2 = errors;
+ if (!validate3(data1[key1], (dataPath || "") + ".definitions['" + key1 + "']", data1, key1, rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid2 = errors === errs_2;
+ if (!valid2)
+ break;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".definitions",
+ schemaPath: "#/properties/definitions/type",
+ params: {
+ type: "object"
+ },
+ message: "should be object"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.properties;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (data1 && typeof data1 === "object" && !Array.isArray(data1)) {
+ var errs__1 = errors;
+ var valid2 = true;
+ for (var key1 in data1) {
+ var errs_2 = errors;
+ if (!validate3(data1[key1], (dataPath || "") + ".properties['" + key1 + "']", data1, key1, rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid2 = errors === errs_2;
+ if (!valid2)
+ break;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".properties",
+ schemaPath: "#/properties/properties/type",
+ params: {
+ type: "object"
+ },
+ message: "should be object"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.patternProperties;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (data1 && typeof data1 === "object" && !Array.isArray(data1)) {
+ var errs__1 = errors;
+ for (var key1 in data1) {
+ var startErrs1 = errors;
+ var data2 = key1;
+ var errs_2 = errors;
+ if (errors === errs_2) {
+ if (typeof data2 === "string") {
+ if (!formats.regex(data2)) {
+ var err = {
+ keyword: "format",
+ dataPath: (dataPath || "") + ".patternProperties",
+ schemaPath: "#/properties/patternProperties/propertyNames/format",
+ params: {
+ format: "regex"
+ },
+ message: 'should match format "regex"'
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ }
+ }
+ var valid2 = errors === errs_2;
+ if (!valid2) {
+ for (var i1 = startErrs1; i1 < errors; i1++) {
+ vErrors[i1].propertyName = key1;
+ }
+ var err = {
+ keyword: "propertyNames",
+ dataPath: (dataPath || "") + ".patternProperties",
+ schemaPath: "#/properties/patternProperties/propertyNames",
+ params: {
+ propertyName: "" + key1
+ },
+ message: "property name '" + key1 + "' is invalid"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ validate3.errors = vErrors;
+ return false;
+ break;
+ }
+ }
+ if (errs__1 == errors) {
+ var errs__1 = errors;
+ var valid2 = true;
+ for (var key1 in data1) {
+ var errs_2 = errors;
+ if (!validate3(data1[key1], (dataPath || "") + ".patternProperties['" + key1 + "']", data1, key1, rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid2 = errors === errs_2;
+ if (!valid2)
+ break;
+ }
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".patternProperties",
+ schemaPath: "#/properties/patternProperties/type",
+ params: {
+ type: "object"
+ },
+ message: "should be object"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.dependencies;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (data1 && typeof data1 === "object" && !Array.isArray(data1)) {
+ var errs__1 = errors;
+ var valid2 = true;
+ for (var key1 in data1) {
+ var data2 = data1[key1];
+ var errs_2 = errors;
+ var errs__2 = errors;
+ var valid2 = false;
+ var errs_3 = errors;
+ if (!validate3(data2, (dataPath || "") + ".dependencies['" + key1 + "']", data1, key1, rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid3 = errors === errs_3;
+ valid2 = valid2 || valid3;
+ if (!valid2) {
+ var errs_3 = errors;
+ var errs_4 = errors;
+ if (Array.isArray(data2)) {
+ var errs__4 = errors;
+ var valid4;
+ for (var i4 = 0; i4 < data2.length; i4++) {
+ var errs_5 = errors;
+ if (typeof data2[i4] !== "string") {
+ var err = {
+ keyword: "type",
+ dataPath: (dataPath || "") + ".dependencies['" + key1 + "'][" + i4 + "]",
+ schemaPath: "#/definitions/stringArray/items/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ var valid5 = errors === errs_5;
+ if (!valid5)
+ break;
+ }
+ if (errs__4 == errors) {
+ var i = data2.length, valid4 = true, j;
+ if (i > 1) {
+ var itemIndices = {}, item;
+ for (; i--; ) {
+ var item = data2[i];
+ if (typeof item !== "string")
+ continue;
+ if (typeof itemIndices[item] == "number") {
+ valid4 = false;
+ j = itemIndices[item];
+ break;
+ }
+ itemIndices[item] = i;
+ }
+ }
+ if (!valid4) {
+ var err = {
+ keyword: "uniqueItems",
+ dataPath: (dataPath || "") + ".dependencies['" + key1 + "']",
+ schemaPath: "#/definitions/stringArray/uniqueItems",
+ params: {
+ i,
+ j
+ },
+ message: "should NOT have duplicate items (items ## " + j + " and " + i + " are identical)"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ }
+ } else {
+ var err = {
+ keyword: "type",
+ dataPath: (dataPath || "") + ".dependencies['" + key1 + "']",
+ schemaPath: "#/definitions/stringArray/type",
+ params: {
+ type: "array"
+ },
+ message: "should be array"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ var valid4 = errors === errs_4;
+ var valid3 = errors === errs_3;
+ valid2 = valid2 || valid3;
+ }
+ if (!valid2) {
+ var err = {
+ keyword: "anyOf",
+ dataPath: (dataPath || "") + ".dependencies['" + key1 + "']",
+ schemaPath: "#/properties/dependencies/additionalProperties/anyOf",
+ params: {},
+ message: "should match some schema in anyOf"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ validate3.errors = vErrors;
+ return false;
+ } else {
+ errors = errs__2;
+ if (vErrors !== null) {
+ if (errs__2)
+ vErrors.length = errs__2;
+ else
+ vErrors = null;
+ }
+ }
+ var valid2 = errors === errs_2;
+ if (!valid2)
+ break;
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".dependencies",
+ schemaPath: "#/properties/dependencies/type",
+ params: {
+ type: "object"
+ },
+ message: "should be object"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.propertyNames === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.propertyNames, (dataPath || "") + ".propertyNames", data, "propertyNames", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (valid1) {
+ var data1 = data.enum;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (Array.isArray(data1)) {
+ if (data1.length < 1) {
+ validate3.errors = [{
+ keyword: "minItems",
+ dataPath: (dataPath || "") + ".enum",
+ schemaPath: "#/properties/enum/minItems",
+ params: {
+ limit: 1
+ },
+ message: "should NOT have fewer than 1 items"
+ }];
+ return false;
+ } else {
+ var errs__1 = errors;
+ var valid1;
+ if (errs__1 == errors) {
+ var i = data1.length, valid1 = true, j;
+ if (i > 1) {
+ outer:
+ for (; i--; ) {
+ for (j = i; j--; ) {
+ if (equal(data1[i], data1[j])) {
+ valid1 = false;
+ break outer;
+ }
+ }
+ }
+ }
+ if (!valid1) {
+ validate3.errors = [{
+ keyword: "uniqueItems",
+ dataPath: (dataPath || "") + ".enum",
+ schemaPath: "#/properties/enum/uniqueItems",
+ params: {
+ i,
+ j
+ },
+ message: "should NOT have duplicate items (items ## " + j + " and " + i + " are identical)"
+ }];
+ return false;
+ }
+ }
+ }
+ } else {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".enum",
+ schemaPath: "#/properties/enum/type",
+ params: {
+ type: "array"
+ },
+ message: "should be array"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ var data1 = data.type;
+ if (data1 === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ var errs__1 = errors;
+ var valid1 = false;
+ var errs_2 = errors;
+ var errs_3 = errors;
+ var schema3 = refVal5.enum;
+ var valid3;
+ valid3 = false;
+ for (var i3 = 0; i3 < schema3.length; i3++)
+ if (equal(data1, schema3[i3])) {
+ valid3 = true;
+ break;
+ }
+ if (!valid3) {
+ var err = {
+ keyword: "enum",
+ dataPath: (dataPath || "") + ".type",
+ schemaPath: "#/definitions/simpleTypes/enum",
+ params: {
+ allowedValues: schema3
+ },
+ message: "should be equal to one of the allowed values"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ var valid3 = errors === errs_3;
+ var valid2 = errors === errs_2;
+ valid1 = valid1 || valid2;
+ if (!valid1) {
+ var errs_2 = errors;
+ if (Array.isArray(data1)) {
+ if (data1.length < 1) {
+ var err = {
+ keyword: "minItems",
+ dataPath: (dataPath || "") + ".type",
+ schemaPath: "#/properties/type/anyOf/1/minItems",
+ params: {
+ limit: 1
+ },
+ message: "should NOT have fewer than 1 items"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ } else {
+ var errs__2 = errors;
+ var valid2;
+ for (var i2 = 0; i2 < data1.length; i2++) {
+ var errs_3 = errors;
+ var errs_4 = errors;
+ var schema4 = refVal[5].enum;
+ var valid4;
+ valid4 = false;
+ for (var i4 = 0; i4 < schema4.length; i4++)
+ if (equal(data1[i2], schema4[i4])) {
+ valid4 = true;
+ break;
+ }
+ if (!valid4) {
+ var err = {
+ keyword: "enum",
+ dataPath: (dataPath || "") + ".type[" + i2 + "]",
+ schemaPath: "#/definitions/simpleTypes/enum",
+ params: {
+ allowedValues: schema4
+ },
+ message: "should be equal to one of the allowed values"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ var valid4 = errors === errs_4;
+ var valid3 = errors === errs_3;
+ if (!valid3)
+ break;
+ }
+ if (errs__2 == errors) {
+ var i = data1.length, valid2 = true, j;
+ if (i > 1) {
+ outer:
+ for (; i--; ) {
+ for (j = i; j--; ) {
+ if (equal(data1[i], data1[j])) {
+ valid2 = false;
+ break outer;
+ }
+ }
+ }
+ }
+ if (!valid2) {
+ var err = {
+ keyword: "uniqueItems",
+ dataPath: (dataPath || "") + ".type",
+ schemaPath: "#/properties/type/anyOf/1/uniqueItems",
+ params: {
+ i,
+ j
+ },
+ message: "should NOT have duplicate items (items ## " + j + " and " + i + " are identical)"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ }
+ }
+ } else {
+ var err = {
+ keyword: "type",
+ dataPath: (dataPath || "") + ".type",
+ schemaPath: "#/properties/type/anyOf/1/type",
+ params: {
+ type: "array"
+ },
+ message: "should be array"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ }
+ var valid2 = errors === errs_2;
+ valid1 = valid1 || valid2;
+ }
+ if (!valid1) {
+ var err = {
+ keyword: "anyOf",
+ dataPath: (dataPath || "") + ".type",
+ schemaPath: "#/properties/type/anyOf",
+ params: {},
+ message: "should match some schema in anyOf"
+ };
+ if (vErrors === null)
+ vErrors = [err];
+ else
+ vErrors.push(err);
+ errors++;
+ validate3.errors = vErrors;
+ return false;
+ } else {
+ errors = errs__1;
+ if (vErrors !== null) {
+ if (errs__1)
+ vErrors.length = errs__1;
+ else
+ vErrors = null;
+ }
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.format === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.format !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".format",
+ schemaPath: "#/properties/format/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.contentMediaType === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.contentMediaType !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".contentMediaType",
+ schemaPath: "#/properties/contentMediaType/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.contentEncoding === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (typeof data.contentEncoding !== "string") {
+ validate3.errors = [{
+ keyword: "type",
+ dataPath: (dataPath || "") + ".contentEncoding",
+ schemaPath: "#/properties/contentEncoding/type",
+ params: {
+ type: "string"
+ },
+ message: "should be string"
+ }];
+ return false;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.if === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.if, (dataPath || "") + ".if", data, "if", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.then === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.then, (dataPath || "") + ".then", data, "then", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.else === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.else, (dataPath || "") + ".else", data, "else", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.allOf === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!refVal[3](data.allOf, (dataPath || "") + ".allOf", data, "allOf", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal[3].errors;
+ else
+ vErrors = vErrors.concat(refVal[3].errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.anyOf === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!refVal[3](data.anyOf, (dataPath || "") + ".anyOf", data, "anyOf", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal[3].errors;
+ else
+ vErrors = vErrors.concat(refVal[3].errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.oneOf === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!refVal[3](data.oneOf, (dataPath || "") + ".oneOf", data, "oneOf", rootData)) {
+ if (vErrors === null)
+ vErrors = refVal[3].errors;
+ else
+ vErrors = vErrors.concat(refVal[3].errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ if (valid1) {
+ if (data.not === void 0) {
+ valid1 = true;
+ } else {
+ var errs_1 = errors;
+ if (!validate3(data.not, (dataPath || "") + ".not", data, "not", rootData)) {
+ if (vErrors === null)
+ vErrors = validate3.errors;
+ else
+ vErrors = vErrors.concat(validate3.errors);
+ errors = vErrors.length;
+ }
+ var valid1 = errors === errs_1;
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ validate3.errors = vErrors;
+ return errors === 0;
+ }, "validate");
+ }();
+ validate2.schema = {
+ "$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
+ };
+ validate2.errors = null;
+ module2.exports = validate2;
+ }
+});
+
+// ../../node_modules/.pnpm/string-similarity@4.0.4/node_modules/string-similarity/src/index.js
+var require_src4 = __commonJS({
+ "../../node_modules/.pnpm/string-similarity@4.0.4/node_modules/string-similarity/src/index.js"(exports2, module2) {
+ init_import_meta_url();
+ module2.exports = {
+ compareTwoStrings,
+ findBestMatch
+ };
+ function compareTwoStrings(first, second) {
+ first = first.replace(/\s+/g, "");
+ second = second.replace(/\s+/g, "");
+ if (first === second)
+ return 1;
+ if (first.length < 2 || second.length < 2)
+ return 0;
+ let firstBigrams = /* @__PURE__ */ new Map();
+ for (let i = 0; i < first.length - 1; i++) {
+ const bigram = first.substring(i, i + 2);
+ const count = firstBigrams.has(bigram) ? firstBigrams.get(bigram) + 1 : 1;
+ firstBigrams.set(bigram, count);
+ }
+ ;
+ let intersectionSize = 0;
+ for (let i = 0; i < second.length - 1; i++) {
+ const bigram = second.substring(i, i + 2);
+ const count = firstBigrams.has(bigram) ? firstBigrams.get(bigram) : 0;
+ if (count > 0) {
+ firstBigrams.set(bigram, count - 1);
+ intersectionSize++;
+ }
+ }
+ return 2 * intersectionSize / (first.length + second.length - 2);
+ }
+ __name(compareTwoStrings, "compareTwoStrings");
+ function findBestMatch(mainString, targetStrings) {
+ if (!areArgsValid(mainString, targetStrings))
+ throw new Error("Bad arguments: First argument should be a string, second should be an array of strings");
+ const ratings = [];
+ let bestMatchIndex = 0;
+ for (let i = 0; i < targetStrings.length; i++) {
+ const currentTargetString = targetStrings[i];
+ const currentRating = compareTwoStrings(mainString, currentTargetString);
+ ratings.push({ target: currentTargetString, rating: currentRating });
+ if (currentRating > ratings[bestMatchIndex].rating) {
+ bestMatchIndex = i;
+ }
+ }
+ const bestMatch = ratings[bestMatchIndex];
+ return { ratings, bestMatch, bestMatchIndex };
+ }
+ __name(findBestMatch, "findBestMatch");
+ function areArgsValid(mainString, targetStrings) {
+ if (typeof mainString !== "string")
+ return false;
+ if (!Array.isArray(targetStrings))
+ return false;
+ if (!targetStrings.length)
+ return false;
+ if (targetStrings.find(function(s) {
+ return typeof s !== "string";
+ }))
+ return false;
+ return true;
+ }
+ __name(areArgsValid, "areArgsValid");
+ }
+});
+
+// ../../node_modules/.pnpm/fast-json-stringify@2.7.13/node_modules/fast-json-stringify/index.js
+var require_fast_json_stringify = __commonJS({
+ "../../node_modules/.pnpm/fast-json-stringify@2.7.13/node_modules/fast-json-stringify/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var Ajv = require_ajv();
+ var merge = require_cjs();
+ var clone = require_rfdc()({ proto: true });
+ var fjsCloned = Symbol("fast-json-stringify.cloned");
+ var validate2 = require_schema_validator();
+ var stringSimilarity = null;
+ var isLong;
+ try {
+ isLong = require("long").isLong;
+ } catch (e2) {
+ isLong = null;
+ }
+ var addComma = `
+ if (addComma) {
+ json += ','
+ } else {
+ addComma = true
+ }
+`;
+ function isValidSchema(schema, name) {
+ if (!validate2(schema)) {
+ if (name) {
+ name = `"${name}" `;
+ } else {
+ name = "";
+ }
+ const first = validate2.errors[0];
+ const err = new Error(`${name}schema is invalid: data${first.dataPath} ${first.message}`);
+ err.errors = isValidSchema.errors;
+ throw err;
+ }
+ }
+ __name(isValidSchema, "isValidSchema");
+ function mergeLocation(source, dest) {
+ return {
+ schema: dest.schema || source.schema,
+ root: dest.root || source.root,
+ externalSchema: dest.externalSchema || source.externalSchema
+ };
+ }
+ __name(mergeLocation, "mergeLocation");
+ var arrayItemsReferenceSerializersMap = /* @__PURE__ */ new Map();
+ var objectReferenceSerializersMap = /* @__PURE__ */ new Map();
+ function build5(schema, options14) {
+ arrayItemsReferenceSerializersMap.clear();
+ objectReferenceSerializersMap.clear();
+ options14 = options14 || {};
+ isValidSchema(schema);
+ if (options14.schema) {
+ for (var key of Object.keys(options14.schema)) {
+ isValidSchema(options14.schema[key], key);
+ }
+ }
+ let intParseFunctionName = "trunc";
+ if (options14.rounding) {
+ if (["floor", "ceil", "round"].includes(options14.rounding)) {
+ intParseFunctionName = options14.rounding;
+ } else {
+ throw new Error(`Unsupported integer rounding method ${options14.rounding}`);
+ }
+ }
+ let code = `
+ 'use strict'
+ `;
+ code += `
+ ${asFunctions}
+
+ var isLong = ${isLong ? isLong.toString() : false}
+
+ function parseInteger(int) { return Math.${intParseFunctionName}(int) }
+ `;
+ let location = {
+ schema,
+ root: schema,
+ externalSchema: options14.schema
+ };
+ if (schema.$ref) {
+ location = refFinder(schema.$ref, location);
+ schema = location.schema;
+ }
+ if (schema.type === void 0) {
+ schema.type = inferTypeByKeyword(schema);
+ }
+ let main2;
+ switch (schema.type) {
+ case "object":
+ main2 = "$main";
+ code = buildObject(location, code, main2);
+ break;
+ case "string":
+ main2 = schema.nullable ? "$asStringNullable" : getStringSerializer(schema.format);
+ break;
+ case "integer":
+ main2 = schema.nullable ? "$asIntegerNullable" : "$asInteger";
+ break;
+ case "number":
+ main2 = schema.nullable ? "$asNumberNullable" : "$asNumber";
+ break;
+ case "boolean":
+ main2 = schema.nullable ? "$asBooleanNullable" : "$asBoolean";
+ break;
+ case "null":
+ main2 = "$asNull";
+ break;
+ case "array":
+ main2 = "$main";
+ code = buildArray(location, code, main2);
+ schema = location.schema;
+ break;
+ case void 0:
+ main2 = "$asAny";
+ break;
+ default:
+ throw new Error(`${schema.type} unsupported`);
+ }
+ code += `
+ ;
+ return ${main2}
+ `;
+ const dependencies = [new Ajv(options14.ajv)];
+ const dependenciesName = ["ajv"];
+ dependenciesName.push(code);
+ if (options14.debugMode) {
+ dependenciesName.toString = function() {
+ return dependenciesName.join("\n");
+ };
+ return dependenciesName;
+ }
+ arrayItemsReferenceSerializersMap.clear();
+ objectReferenceSerializersMap.clear();
+ return Function.apply(null, dependenciesName).apply(null, dependencies);
+ }
+ __name(build5, "build");
+ var objectKeywords = [
+ "maxProperties",
+ "minProperties",
+ "required",
+ "properties",
+ "patternProperties",
+ "additionalProperties",
+ "dependencies"
+ ];
+ var arrayKeywords = [
+ "items",
+ "additionalItems",
+ "maxItems",
+ "minItems",
+ "uniqueItems",
+ "contains"
+ ];
+ var stringKeywords = [
+ "maxLength",
+ "minLength",
+ "pattern"
+ ];
+ var numberKeywords = [
+ "multipleOf",
+ "maximum",
+ "exclusiveMaximum",
+ "minimum",
+ "exclusiveMinimum"
+ ];
+ function inferTypeByKeyword(schema) {
+ for (var keyword of objectKeywords) {
+ if (keyword in schema)
+ return "object";
+ }
+ for (var keyword of arrayKeywords) {
+ if (keyword in schema)
+ return "array";
+ }
+ for (var keyword of stringKeywords) {
+ if (keyword in schema)
+ return "string";
+ }
+ for (var keyword of numberKeywords) {
+ if (keyword in schema)
+ return "number";
+ }
+ return schema.type;
+ }
+ __name(inferTypeByKeyword, "inferTypeByKeyword");
+ var stringSerializerMap = {
+ "date-time": "$asDatetime",
+ date: "$asDate",
+ time: "$asTime"
+ };
+ function getStringSerializer(format8) {
+ return stringSerializerMap[format8] || "$asString";
+ }
+ __name(getStringSerializer, "getStringSerializer");
+ function getTestSerializer(format8) {
+ return stringSerializerMap[format8];
+ }
+ __name(getTestSerializer, "getTestSerializer");
+ var asFunctions = `
+function $pad2Zeros (num) {
+ const s = '00' + num
+ return s[s.length - 2] + s[s.length - 1]
+}
+
+function $asAny (i) {
+ return JSON.stringify(i)
+}
+
+function $asNull () {
+ return 'null'
+}
+
+function $asInteger (i) {
+ if (isLong && isLong(i)) {
+ return i.toString()
+ } else if (typeof i === 'bigint') {
+ return i.toString()
+ } else if (Number.isInteger(i)) {
+ return $asNumber(i)
+ } else {
+ /* eslint no-undef: "off" */
+ return $asNumber(parseInteger(i))
+ }
+}
+
+function $asIntegerNullable (i) {
+ return i === null ? null : $asInteger(i)
+}
+
+function $asNumber (i) {
+ const num = Number(i)
+ if (isNaN(num)) {
+ return 'null'
+ } else {
+ return '' + num
+ }
+}
+
+function $asNumberNullable (i) {
+ return i === null ? null : $asNumber(i)
+}
+
+function $asBoolean (bool) {
+ return bool && 'true' || 'false' // eslint-disable-line
+}
+
+function $asBooleanNullable (bool) {
+ return bool === null ? null : $asBoolean(bool)
+}
+
+function $asDatetime (date, skipQuotes) {
+ const quotes = skipQuotes === true ? '' : '"'
+ if (date instanceof Date) {
+ return quotes + date.toISOString() + quotes
+ } else if (date && typeof date.toISOString === 'function') {
+ return quotes + date.toISOString() + quotes
+ } else {
+ return $asString(date, skipQuotes)
+ }
+}
+
+function $asDate (date, skipQuotes) {
+ const quotes = skipQuotes === true ? '' : '"'
+ if (date instanceof Date) {
+ return quotes + new Date(date.getTime() - (date.getTimezoneOffset() * 60000 )).toISOString().slice(0, 10) + quotes
+ } else if (date && typeof date.format === 'function') {
+ return quotes + date.format('YYYY-MM-DD') + quotes
+ } else {
+ return $asString(date, skipQuotes)
+ }
+}
+
+function $asTime (date, skipQuotes) {
+ const quotes = skipQuotes === true ? '' : '"'
+ if (date instanceof Date) {
+ const hour = new Intl.DateTimeFormat('en', { hour: 'numeric', hour12: false }).format(date)
+ const minute = new Intl.DateTimeFormat('en', { minute: 'numeric' }).format(date)
+ const second = new Intl.DateTimeFormat('en', { second: 'numeric' }).format(date)
+ return quotes + $pad2Zeros(hour) + ':' + $pad2Zeros(minute) + ':' + $pad2Zeros(second) + quotes
+ } else if (date && typeof date.format === 'function') {
+ return quotes + date.format('HH:mm:ss') + quotes
+ } else {
+ return $asString(date, skipQuotes)
+ }
+}
+
+function $asString (str, skipQuotes) {
+ const quotes = skipQuotes === true ? '' : '"'
+ if (str instanceof Date) {
+ return quotes + str.toISOString() + quotes
+ } else if (str === null) {
+ return quotes + quotes
+ } else if (str instanceof RegExp) {
+ str = str.source
+ } else if (typeof str !== 'string') {
+ str = str.toString()
+ }
+ // If we skipQuotes it means that we are using it as test
+ // no need to test the string length for the render
+ if (skipQuotes) {
+ return str
+ }
+
+ if (str.length < 42) {
+ return $asStringSmall(str)
+ } else {
+ return JSON.stringify(str)
+ }
+}
+
+function $asStringNullable (str) {
+ return str === null ? null : $asString(str)
+}
+
+// magically escape strings for json
+// relying on their charCodeAt
+// everything below 32 needs JSON.stringify()
+// every string that contain surrogate needs JSON.stringify()
+// 34 and 92 happens all the time, so we
+// have a fast case for them
+function $asStringSmall (str) {
+ const l = str.length
+ let result = ''
+ let last = 0
+ let found = false
+ let surrogateFound = false
+ let point = 255
+ // eslint-disable-next-line
+ for (var i = 0; i < l && point >= 32; i++) {
+ point = str.charCodeAt(i)
+ if (point >= 0xD800 && point <= 0xDFFF) {
+ // The current character is a surrogate.
+ surrogateFound = true
+ }
+ if (point === 34 || point === 92) {
+ result += str.slice(last, i) + '\\\\'
+ last = i
+ found = true
+ }
+ }
+
+ if (!found) {
+ result = str
+ } else {
+ result += str.slice(last)
+ }
+ return ((point < 32) || (surrogateFound === true)) ? JSON.stringify(str) : '"' + result + '"'
+}
+`;
+ function addPatternProperties(location) {
+ const schema = location.schema;
+ const pp = schema.patternProperties;
+ let code = `
+ var properties = ${JSON.stringify(schema.properties)} || {}
+ var keys = Object.keys(obj)
+ for (var i = 0; i < keys.length; i++) {
+ if (properties[keys[i]]) continue
+ `;
+ Object.keys(pp).forEach((regex, index) => {
+ let ppLocation = mergeLocation(location, { schema: pp[regex] });
+ if (pp[regex].$ref) {
+ ppLocation = refFinder(pp[regex].$ref, location);
+ pp[regex] = ppLocation.schema;
+ }
+ const type = pp[regex].type;
+ const format8 = pp[regex].format;
+ const stringSerializer = getStringSerializer(format8);
+ try {
+ RegExp(regex);
+ } catch (err) {
+ throw new Error(`${err.message}. Found at ${regex} matching ${JSON.stringify(pp[regex])}`);
+ }
+ const ifPpKeyExists = `if (/${regex.replace(/\\*\//g, "\\/")}/.test(keys[i])) {`;
+ if (type === "object") {
+ code += `${buildObject(ppLocation, "", "buildObjectPP" + index)}
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + buildObjectPP${index}(obj[keys[i]])
+ `;
+ } else if (type === "array") {
+ code += `${buildArray(ppLocation, "", "buildArrayPP" + index)}
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + buildArrayPP${index}(obj[keys[i]])
+ `;
+ } else if (type === "null") {
+ code += `
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) +':null'
+ `;
+ } else if (type === "string") {
+ code += `
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + ${stringSerializer}(obj[keys[i]])
+ `;
+ } else if (type === "integer") {
+ code += `
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asInteger(obj[keys[i]])
+ `;
+ } else if (type === "number") {
+ code += `
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asNumber(obj[keys[i]])
+ `;
+ } else if (type === "boolean") {
+ code += `
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asBoolean(obj[keys[i]])
+ `;
+ } else if (type === void 0) {
+ code += `
+ ${ifPpKeyExists}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asAny(obj[keys[i]])
+ `;
+ } else {
+ code += `
+ ${ifPpKeyExists}
+ throw new Error('Cannot coerce ' + obj[keys[i]] + ' to ' + ${JSON.stringify(type)})
+ `;
+ }
+ code += `
+ continue
+ }
+ `;
+ });
+ if (schema.additionalProperties) {
+ code += additionalProperty(location);
+ }
+ code += `
+ }
+ `;
+ return code;
+ }
+ __name(addPatternProperties, "addPatternProperties");
+ function additionalProperty(location) {
+ let ap = location.schema.additionalProperties;
+ let code = "";
+ if (ap === true) {
+ return `
+ if (obj[keys[i]] !== undefined && typeof obj[keys[i]] !== 'function' && typeof obj[keys[i]] !== 'symbol') {
+ ${addComma}
+ json += $asString(keys[i]) + ':' + JSON.stringify(obj[keys[i]])
+ }
+ `;
+ }
+ let apLocation = mergeLocation(location, { schema: ap });
+ if (ap.$ref) {
+ apLocation = refFinder(ap.$ref, location);
+ ap = apLocation.schema;
+ }
+ const type = ap.type;
+ const format8 = ap.format;
+ const stringSerializer = getStringSerializer(format8);
+ if (type === "object") {
+ code += `${buildObject(apLocation, "", "buildObjectAP")}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + buildObjectAP(obj[keys[i]])
+ `;
+ } else if (type === "array") {
+ code += `${buildArray(apLocation, "", "buildArrayAP")}
+ ${addComma}
+ json += $asString(keys[i]) + ':' + buildArrayAP(obj[keys[i]])
+ `;
+ } else if (type === "null") {
+ code += `
+ ${addComma}
+ json += $asString(keys[i]) +':null'
+ `;
+ } else if (type === "string") {
+ code += `
+ ${addComma}
+ json += $asString(keys[i]) + ':' + ${stringSerializer}(obj[keys[i]])
+ `;
+ } else if (type === "integer") {
+ code += `
+ var t = Number(obj[keys[i]])
+ `;
+ if (isLong) {
+ code += `
+ if (isLong(obj[keys[i]]) || !isNaN(t)) {
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asInteger(obj[keys[i]])
+ }
+ `;
+ } else {
+ code += `
+ if (!isNaN(t)) {
+ ${addComma}
+ json += $asString(keys[i]) + ':' + t
+ }
+ `;
+ }
+ } else if (type === "number") {
+ code += `
+ var t = Number(obj[keys[i]])
+ if (!isNaN(t)) {
+ ${addComma}
+ json += $asString(keys[i]) + ':' + t
+ }
+ `;
+ } else if (type === "boolean") {
+ code += `
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asBoolean(obj[keys[i]])
+ `;
+ } else if (type === void 0) {
+ code += `
+ ${addComma}
+ json += $asString(keys[i]) + ':' + $asAny(obj[keys[i]])
+ `;
+ } else {
+ code += `
+ throw new Error('Cannot coerce ' + obj[keys[i]] + ' to ' + ${JSON.stringify(type)})
+ `;
+ }
+ return code;
+ }
+ __name(additionalProperty, "additionalProperty");
+ function addAdditionalProperties(location) {
+ return `
+ var properties = ${JSON.stringify(location.schema.properties)} || {}
+ var keys = Object.keys(obj)
+ for (var i = 0; i < keys.length; i++) {
+ if (properties[keys[i]]) continue
+ ${additionalProperty(location)}
+ }
+ `;
+ }
+ __name(addAdditionalProperties, "addAdditionalProperties");
+ function idFinder(schema, searchedId) {
+ let objSchema;
+ const explore = /* @__PURE__ */ __name((schema2, searchedId2) => {
+ Object.keys(schema2 || {}).forEach((key, i, a) => {
+ if (key === "$id" && schema2[key] === searchedId2) {
+ objSchema = schema2;
+ } else if (objSchema === void 0 && typeof schema2[key] === "object") {
+ explore(schema2[key], searchedId2);
+ }
+ });
+ }, "explore");
+ explore(schema, searchedId);
+ return objSchema;
+ }
+ __name(idFinder, "idFinder");
+ function refFinder(ref, location) {
+ const externalSchema = location.externalSchema;
+ let root = location.root;
+ let schema = location.schema;
+ if (externalSchema && externalSchema[ref]) {
+ return {
+ schema: externalSchema[ref],
+ root: externalSchema[ref],
+ externalSchema
+ };
+ }
+ ref = ref.split("#");
+ if (ref[0]) {
+ schema = externalSchema[ref[0]];
+ root = externalSchema[ref[0]];
+ if (schema === void 0) {
+ findBadKey(externalSchema, [ref[0]]);
+ }
+ if (schema.$ref) {
+ return refFinder(schema.$ref, {
+ schema,
+ root,
+ externalSchema
+ });
+ }
+ }
+ let code = "return schema";
+ if (ref[1]) {
+ const walk = ref[1].split("/");
+ if (walk.length === 1) {
+ const targetId = `#${ref[1]}`;
+ let dereferenced = idFinder(schema, targetId);
+ if (dereferenced === void 0 && !ref[0]) {
+ for (var key of Object.keys(externalSchema)) {
+ dereferenced = idFinder(externalSchema[key], targetId);
+ if (dereferenced !== void 0) {
+ root = externalSchema[key];
+ break;
+ }
+ }
+ }
+ return {
+ schema: dereferenced,
+ root,
+ externalSchema
+ };
+ } else {
+ for (var i = 1; i < walk.length; i++) {
+ code += `[${JSON.stringify(walk[i])}]`;
+ }
+ }
+ }
+ let result;
+ try {
+ result = new Function("schema", code)(root);
+ } catch (err) {
+ }
+ if (result === void 0 && ref[1]) {
+ const walk = ref[1].split("/");
+ findBadKey(schema, walk.slice(1));
+ }
+ if (result.$ref) {
+ return refFinder(result.$ref, {
+ schema,
+ root,
+ externalSchema
+ });
+ }
+ return {
+ schema: result,
+ root,
+ externalSchema
+ };
+ function findBadKey(obj, keys) {
+ if (keys.length === 0)
+ return null;
+ const key2 = keys.shift();
+ if (obj[key2] === void 0) {
+ stringSimilarity = stringSimilarity || require_src4();
+ const { bestMatch } = stringSimilarity.findBestMatch(key2, Object.keys(obj));
+ if (bestMatch.rating >= 0.5) {
+ throw new Error(`Cannot find reference ${JSON.stringify(key2)}, did you mean ${JSON.stringify(bestMatch.target)}?`);
+ } else {
+ throw new Error(`Cannot find reference ${JSON.stringify(key2)}`);
+ }
+ }
+ return findBadKey(obj[key2], keys);
+ }
+ __name(findBadKey, "findBadKey");
+ }
+ __name(refFinder, "refFinder");
+ function buildCode(location, code, laterCode, name) {
+ if (location.schema.$ref) {
+ location = refFinder(location.schema.$ref, location);
+ }
+ const schema = location.schema;
+ let required = schema.required;
+ Object.keys(schema.properties || {}).forEach((key, i2, a) => {
+ let propertyLocation = mergeLocation(location, { schema: schema.properties[key] });
+ if (schema.properties[key].$ref) {
+ propertyLocation = refFinder(schema.properties[key].$ref, location);
+ schema.properties[key] = propertyLocation.schema;
+ }
+ const type = schema.properties[key].type;
+ const nullable = schema.properties[key].nullable;
+ const sanitized = JSON.stringify(key);
+ const asString = JSON.stringify(sanitized);
+ if (nullable) {
+ code += `
+ if (obj[${sanitized}] === null) {
+ ${addComma}
+ json += ${asString} + ':null'
+ var rendered = true
+ } else {
+ `;
+ }
+ if (type === "number") {
+ code += `
+ var t = Number(obj[${sanitized}])
+ if (!isNaN(t)) {
+ ${addComma}
+ json += ${asString} + ':' + t
+ `;
+ } else if (type === "integer") {
+ code += `
+ var rendered = false
+ `;
+ if (isLong) {
+ code += `
+ if (isLong(obj[${sanitized}])) {
+ ${addComma}
+ json += ${asString} + ':' + obj[${sanitized}].toString()
+ rendered = true
+ } else {
+ var t = Number(obj[${sanitized}])
+ if (!isNaN(t)) {
+ ${addComma}
+ json += ${asString} + ':' + t
+ rendered = true
+ }
+ }
+ `;
+ } else {
+ code += `
+ var t = $asInteger(obj[${sanitized}])
+ if (!isNaN(t)) {
+ ${addComma}
+ json += ${asString} + ':' + t
+ rendered = true
+ }
+ `;
+ }
+ code += `
+ if (rendered) {
+ `;
+ } else {
+ code += `
+ if (obj[${sanitized}] !== undefined) {
+ ${addComma}
+ json += ${asString} + ':'
+ `;
+ const result = nested(laterCode, name, key, mergeLocation(propertyLocation, { schema: schema.properties[key] }), void 0, false);
+ code += result.code;
+ laterCode = result.laterCode;
+ }
+ const defaultValue = schema.properties[key].default;
+ if (defaultValue !== void 0) {
+ required = filterRequired(required, key);
+ code += `
+ } else {
+ ${addComma}
+ json += ${asString} + ':' + ${JSON.stringify(JSON.stringify(defaultValue))}
+ `;
+ } else if (required && required.indexOf(key) !== -1) {
+ required = filterRequired(required, key);
+ code += `
+ } else {
+ throw new Error('${sanitized} is required!')
+ `;
+ }
+ code += `
+ }
+ `;
+ if (nullable) {
+ code += `
+ }
+ `;
+ }
+ });
+ if (required && required.length > 0) {
+ code += "var required = [";
+ for (var i = 0; i < required.length; i++) {
+ if (i > 0) {
+ code += ",";
+ }
+ code += `${JSON.stringify(required[i])}`;
+ }
+ code += `]
+ for (var i = 0; i < required.length; i++) {
+ if (obj[required[i]] === undefined) throw new Error('"' + required[i] + '" is required!')
+ }
+ `;
+ }
+ if (schema.allOf) {
+ const builtCode = buildCodeWithAllOfs(location, code, laterCode, name);
+ code = builtCode.code;
+ laterCode = builtCode.laterCode;
+ }
+ return { code, laterCode };
+ }
+ __name(buildCode, "buildCode");
+ function filterRequired(required, key) {
+ if (!required) {
+ return required;
+ }
+ return required.filter((k) => k !== key);
+ }
+ __name(filterRequired, "filterRequired");
+ function buildCodeWithAllOfs(location, code, laterCode, name) {
+ if (location.schema.allOf) {
+ location.schema.allOf.forEach((ss) => {
+ const builtCode = buildCodeWithAllOfs(mergeLocation(location, { schema: ss }), code, laterCode, name);
+ code = builtCode.code;
+ laterCode = builtCode.laterCode;
+ });
+ } else {
+ const builtCode = buildCode(location, code, laterCode, name);
+ code = builtCode.code;
+ laterCode = builtCode.laterCode;
+ }
+ return { code, laterCode };
+ }
+ __name(buildCodeWithAllOfs, "buildCodeWithAllOfs");
+ function buildInnerObject(location, name) {
+ const schema = location.schema;
+ const result = buildCodeWithAllOfs(location, "", "", name);
+ if (schema.patternProperties) {
+ result.code += addPatternProperties(location);
+ } else if (schema.additionalProperties && !schema.patternProperties) {
+ result.code += addAdditionalProperties(location);
+ }
+ return result;
+ }
+ __name(buildInnerObject, "buildInnerObject");
+ function addIfThenElse(location, name) {
+ let code = "";
+ let r;
+ let laterCode = "";
+ let innerR;
+ const schema = location.schema;
+ const copy = merge({}, schema);
+ const i = copy.if;
+ const then = copy.then;
+ const e2 = copy.else ? copy.else : { additionalProperties: true };
+ delete copy.if;
+ delete copy.then;
+ delete copy.else;
+ let merged = merge(copy, then);
+ let mergedLocation = mergeLocation(location, { schema: merged });
+ code += `
+ valid = ajv.validate(${JSON.stringify(i)}, obj)
+ if (valid) {
+ `;
+ if (merged.if && merged.then) {
+ innerR = addIfThenElse(mergedLocation, name + "Then");
+ code += innerR.code;
+ laterCode = innerR.laterCode;
+ }
+ r = buildInnerObject(mergedLocation, name + "Then");
+ code += r.code;
+ laterCode += r.laterCode;
+ code += `
+ }
+ `;
+ merged = merge(copy, e2);
+ mergedLocation = mergeLocation(mergedLocation, { schema: merged });
+ code += `
+ else {
+ `;
+ if (merged.if && merged.then) {
+ innerR = addIfThenElse(mergedLocation, name + "Else");
+ code += innerR.code;
+ laterCode += innerR.laterCode;
+ }
+ r = buildInnerObject(mergedLocation, name + "Else");
+ code += r.code;
+ laterCode += r.laterCode;
+ code += `
+ }
+ `;
+ return { code, laterCode };
+ }
+ __name(addIfThenElse, "addIfThenElse");
+ function toJSON(variableName) {
+ return `(${variableName} && typeof ${variableName}.toJSON === 'function')
+ ? ${variableName}.toJSON()
+ : ${variableName}
+ `;
+ }
+ __name(toJSON, "toJSON");
+ function buildObject(location, code, name) {
+ const schema = location.schema;
+ code += `
+ function ${name} (input) {
+ `;
+ if (schema.nullable) {
+ code += `
+ if(input === null) {
+ return 'null';
+ }
+ `;
+ }
+ if (objectReferenceSerializersMap.has(schema)) {
+ code += `
+ return ${objectReferenceSerializersMap.get(schema)}(input)
+ }
+ `;
+ return code;
+ }
+ objectReferenceSerializersMap.set(schema, name);
+ code += `
+ var obj = ${toJSON("input")}
+ var json = '{'
+ var addComma = false
+ `;
+ let r;
+ if (schema.if && schema.then) {
+ code += `
+ var valid
+ `;
+ r = addIfThenElse(location, name);
+ } else {
+ r = buildInnerObject(location, name);
+ }
+ code += `${r.code}
+ json += '}'
+ return json
+ }
+ ${r.laterCode}
+ `;
+ return code;
+ }
+ __name(buildObject, "buildObject");
+ function buildArray(location, code, name, key = null) {
+ let schema = location.schema;
+ code += `
+ function ${name} (obj) {
+ `;
+ if (schema.nullable) {
+ code += `
+ if(obj === null) {
+ return 'null';
+ }
+ `;
+ }
+ const laterCode = "";
+ if (!schema.items) {
+ schema.items = {};
+ }
+ if (schema.items.$ref) {
+ if (!schema[fjsCloned]) {
+ location.schema = clone(location.schema);
+ schema = location.schema;
+ schema[fjsCloned] = true;
+ }
+ location = refFinder(schema.items.$ref, location);
+ schema.items = location.schema;
+ if (arrayItemsReferenceSerializersMap.has(schema.items)) {
+ code += `
+ return ${arrayItemsReferenceSerializersMap.get(schema.items)}(obj)
+ }
+ `;
+ return code;
+ }
+ arrayItemsReferenceSerializersMap.set(schema.items, name);
+ }
+ let result = { code: "", laterCode: "" };
+ const accessor = "[i]";
+ if (Array.isArray(schema.items)) {
+ result = schema.items.reduce((res, item, i) => {
+ const tmpRes = nested(laterCode, name, accessor, mergeLocation(location, { schema: item }), i, true);
+ const condition = `i === ${i} && ${buildArrayTypeCondition(item.type, accessor)}`;
+ return {
+ code: `${res.code}
+ ${i > 0 ? "else" : ""} if (${condition}) {
+ ${tmpRes.code}
+ }`,
+ laterCode: `${res.laterCode}
+ ${tmpRes.laterCode}`
+ };
+ }, result);
+ if (schema.additionalItems) {
+ const tmpRes = nested(laterCode, name, accessor, mergeLocation(location, { schema: schema.items }), void 0, true);
+ result.code += `
+ else if (i >= ${schema.items.length}) {
+ ${tmpRes.code}
+ }
+ `;
+ }
+ result.code += `
+ else {
+ throw new Error(\`Item at \${i} does not match schema definition.\`)
+ }
+ `;
+ } else {
+ result = nested(laterCode, name, accessor, mergeLocation(location, { schema: schema.items }), void 0, true);
+ }
+ if (key) {
+ code += `
+ if(!Array.isArray(obj)) {
+ throw new TypeError(\`Property '${key}' should be of type array, received '\${obj}' instead.\`)
+ }
+ `;
+ }
+ code += `
+ var l = obj.length
+ var jsonOutput= ''
+ for (var i = 0; i < l; i++) {
+ var json = ''
+ ${result.code}
+ jsonOutput += json
+
+ if (json.length > 0 && i < l - 1) {
+ jsonOutput += ','
+ }
+ }
+ return \`[\${jsonOutput}]\`
+ }
+ ${result.laterCode}
+ `;
+ return code;
+ }
+ __name(buildArray, "buildArray");
+ function buildArrayTypeCondition(type, accessor) {
+ let condition;
+ switch (type) {
+ case "null":
+ condition = `obj${accessor} === null`;
+ break;
+ case "string":
+ condition = `typeof obj${accessor} === 'string'`;
+ break;
+ case "integer":
+ condition = `Number.isInteger(obj${accessor})`;
+ break;
+ case "number":
+ condition = `Number.isFinite(obj${accessor})`;
+ break;
+ case "boolean":
+ condition = `typeof obj${accessor} === 'boolean'`;
+ break;
+ case "object":
+ condition = `obj${accessor} && typeof obj${accessor} === 'object' && obj${accessor}.constructor === Object`;
+ break;
+ case "array":
+ condition = `Array.isArray(obj${accessor})`;
+ break;
+ default:
+ if (Array.isArray(type)) {
+ const conditions = type.map((subType) => {
+ return buildArrayTypeCondition(subType, accessor);
+ });
+ condition = `(${conditions.join(" || ")})`;
+ } else {
+ throw new Error(`${type} unsupported`);
+ }
+ }
+ return condition;
+ }
+ __name(buildArrayTypeCondition, "buildArrayTypeCondition");
+ function dereferenceOfRefs(location, type) {
+ if (!location.schema[fjsCloned]) {
+ const schemaClone = clone(location.schema);
+ schemaClone[fjsCloned] = true;
+ location.schema = schemaClone;
+ }
+ const schema = location.schema;
+ const locations = [];
+ schema[type].forEach((s, index) => {
+ let sLocation = mergeLocation(location, { schema: s });
+ while (s.$ref) {
+ sLocation = refFinder(s.$ref, sLocation);
+ schema[type][index] = sLocation.schema;
+ s = schema[type][index];
+ }
+ locations[index] = sLocation;
+ });
+ return locations;
+ }
+ __name(dereferenceOfRefs, "dereferenceOfRefs");
+ var strNameCounter = 0;
+ function asFuncName(str) {
+ let rep = str.replace(/[^a-zA-Z0-9$_]/g, "");
+ if (rep.length === 0) {
+ return "anan" + strNameCounter++;
+ } else if (rep !== str) {
+ rep += strNameCounter++;
+ }
+ return rep;
+ }
+ __name(asFuncName, "asFuncName");
+ function nested(laterCode, name, key, location, subKey, isArray) {
+ let code = "";
+ let funcName;
+ subKey = subKey || "";
+ let schema = location.schema;
+ if (schema.$ref) {
+ schema = refFinder(schema.$ref, location);
+ }
+ if (schema.type === void 0) {
+ const inferredType = inferTypeByKeyword(schema);
+ if (inferredType) {
+ schema.type = inferredType;
+ }
+ }
+ const type = schema.type;
+ const nullable = schema.nullable === true;
+ const accessor = isArray ? key : `[${JSON.stringify(key)}]`;
+ switch (type) {
+ case "null":
+ code += `
+ json += $asNull()
+ `;
+ break;
+ case "string": {
+ const stringSerializer = getStringSerializer(schema.format);
+ code += nullable ? `json += obj${accessor} === null ? null : ${stringSerializer}(obj${accessor})` : `json += ${stringSerializer}(obj${accessor})`;
+ break;
+ }
+ case "integer":
+ code += nullable ? `json += obj${accessor} === null ? null : $asInteger(obj${accessor})` : `json += $asInteger(obj${accessor})`;
+ break;
+ case "number":
+ code += nullable ? `json += obj${accessor} === null ? null : $asNumber(obj${accessor})` : `json += $asNumber(obj${accessor})`;
+ break;
+ case "boolean":
+ code += nullable ? `json += obj${accessor} === null ? null : $asBoolean(obj${accessor})` : `json += $asBoolean(obj${accessor})`;
+ break;
+ case "object":
+ funcName = asFuncName(name + key + subKey);
+ laterCode = buildObject(location, laterCode, funcName);
+ code += `
+ json += ${funcName}(obj${accessor})
+ `;
+ break;
+ case "array":
+ funcName = asFuncName("$arr" + name + key + subKey);
+ laterCode = buildArray(location, laterCode, funcName, key);
+ code += `
+ json += ${funcName}(obj${accessor})
+ `;
+ break;
+ case void 0:
+ if ("anyOf" in schema) {
+ const anyOfLocations = dereferenceOfRefs(location, "anyOf");
+ anyOfLocations.forEach((location2, index) => {
+ const nestedResult = nested(laterCode, name, key, location2, subKey !== "" ? subKey : "i" + index, isArray);
+ const testSerializer = getTestSerializer(location2.schema.format);
+ const testValue = testSerializer !== void 0 ? `${testSerializer}(obj${accessor}, true)` : `obj${accessor}`;
+ code += `
+ ${index === 0 ? "if" : "else if"}(ajv.validate(${JSON.stringify(location2.schema)}, ${testValue}))
+ ${nestedResult.code}
+ `;
+ laterCode = nestedResult.laterCode;
+ });
+ code += `
+ else json+= null
+ `;
+ } else if ("oneOf" in schema) {
+ const oneOfLocations = dereferenceOfRefs(location, "oneOf");
+ oneOfLocations.forEach((location2, index) => {
+ const nestedResult = nested(laterCode, name, key, location2, subKey !== "" ? subKey : "i" + index, isArray);
+ const testSerializer = getTestSerializer(location2.schema.format);
+ const testValue = testSerializer !== void 0 ? `${testSerializer}(obj${accessor}, true)` : `obj${accessor}`;
+ code += `
+ ${index === 0 ? "if" : "else if"}(ajv.validate(${JSON.stringify(location2.schema)}, ${testValue}))
+ ${nestedResult.code}
+ `;
+ laterCode = nestedResult.laterCode;
+ });
+ if (!isArray) {
+ code += `
+ else json+= null
+ `;
+ }
+ } else if (isEmpty(schema)) {
+ code += `
+ json += JSON.stringify(obj${accessor})
+ `;
+ } else if ("const" in schema) {
+ code += `
+ if(ajv.validate(${JSON.stringify(schema)}, obj${accessor}))
+ json += '${JSON.stringify(schema.const)}'
+ else
+ throw new Error(\`Item \${JSON.stringify(obj${accessor})} does not match schema definition.\`)
+ `;
+ } else if (schema.type === void 0) {
+ code += `
+ json += JSON.stringify(obj${accessor})
+ `;
+ } else {
+ throw new Error(`${schema.type} unsupported`);
+ }
+ break;
+ default:
+ if (Array.isArray(type)) {
+ const nullIndex = type.indexOf("null");
+ const sortedTypes = nullIndex !== -1 ? [type[nullIndex]].concat(type.slice(0, nullIndex)).concat(type.slice(nullIndex + 1)) : type;
+ sortedTypes.forEach((type2, index) => {
+ const statement = index === 0 ? "if" : "else if";
+ const tempSchema = Object.assign({}, schema, { type: type2 });
+ const nestedResult = nested(laterCode, name, key, mergeLocation(location, { schema: tempSchema }), subKey, isArray);
+ switch (type2) {
+ case "string": {
+ code += `
+ ${statement}(obj${accessor} === null || typeof obj${accessor} === "${type2}" || obj${accessor} instanceof Date || typeof obj${accessor}.toISOString === "function" || obj${accessor} instanceof RegExp || (typeof obj${accessor} === "object" && Object.hasOwnProperty.call(obj${accessor}, "toString")))
+ ${nestedResult.code}
+ `;
+ break;
+ }
+ case "null": {
+ code += `
+ ${statement}(obj${accessor} == null)
+ ${nestedResult.code}
+ `;
+ break;
+ }
+ case "array": {
+ code += `
+ ${statement}(Array.isArray(obj${accessor}))
+ ${nestedResult.code}
+ `;
+ break;
+ }
+ case "integer": {
+ code += `
+ ${statement}(Number.isInteger(obj${accessor}) || obj${accessor} === null)
+ ${nestedResult.code}
+ `;
+ break;
+ }
+ case "number": {
+ code += `
+ ${statement}(isNaN(obj${accessor}) === false)
+ ${nestedResult.code}
+ `;
+ break;
+ }
+ default: {
+ code += `
+ ${statement}(typeof obj${accessor} === "${type2}")
+ ${nestedResult.code}
+ `;
+ break;
+ }
+ }
+ laterCode = nestedResult.laterCode;
+ });
+ code += `
+ else json+= null
+ `;
+ } else {
+ throw new Error(`${type} unsupported`);
+ }
+ }
+ return {
+ code,
+ laterCode
+ };
+ }
+ __name(nested, "nested");
+ function isEmpty(schema) {
+ for (var key in schema) {
+ if (schema.hasOwnProperty(key) && schema[key] !== void 0) {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(isEmpty, "isEmpty");
+ module2.exports = build5;
+ module2.exports.restore = function(debugModeStr, options14 = {}) {
+ const dependencies = [debugModeStr];
+ const args = [];
+ if (debugModeStr.startsWith("ajv")) {
+ dependencies.unshift("ajv");
+ args.push(new Ajv(options14.ajv));
+ }
+ return Function.apply(null, ["ajv", debugModeStr]).apply(null, args);
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/fast-safe-stringify@2.1.1/node_modules/fast-safe-stringify/index.js
+var require_fast_safe_stringify = __commonJS({
+ "../../node_modules/.pnpm/fast-safe-stringify@2.1.1/node_modules/fast-safe-stringify/index.js"(exports2, module2) {
+ init_import_meta_url();
+ module2.exports = stringify;
+ stringify.default = stringify;
+ stringify.stable = deterministicStringify;
+ stringify.stableStringify = deterministicStringify;
+ var LIMIT_REPLACE_NODE = "[...]";
+ var CIRCULAR_REPLACE_NODE = "[Circular]";
+ var arr = [];
+ var replacerStack = [];
+ function defaultOptions() {
+ return {
+ depthLimit: Number.MAX_SAFE_INTEGER,
+ edgesLimit: Number.MAX_SAFE_INTEGER
+ };
+ }
+ __name(defaultOptions, "defaultOptions");
+ function stringify(obj, replacer2, spacer, options14) {
+ if (typeof options14 === "undefined") {
+ options14 = defaultOptions();
+ }
+ decirc(obj, "", 0, [], void 0, 0, options14);
+ var res;
+ try {
+ if (replacerStack.length === 0) {
+ res = JSON.stringify(obj, replacer2, spacer);
+ } else {
+ res = JSON.stringify(obj, replaceGetterValues(replacer2), spacer);
+ }
+ } catch (_2) {
+ return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]");
+ } finally {
+ while (arr.length !== 0) {
+ var part = arr.pop();
+ if (part.length === 4) {
+ Object.defineProperty(part[0], part[1], part[3]);
+ } else {
+ part[0][part[1]] = part[2];
+ }
+ }
+ }
+ return res;
+ }
+ __name(stringify, "stringify");
+ function setReplace(replace, val, k, parent) {
+ var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k);
+ if (propertyDescriptor.get !== void 0) {
+ if (propertyDescriptor.configurable) {
+ Object.defineProperty(parent, k, { value: replace });
+ arr.push([parent, k, val, propertyDescriptor]);
+ } else {
+ replacerStack.push([val, k, replace]);
+ }
+ } else {
+ parent[k] = replace;
+ arr.push([parent, k, val]);
+ }
+ }
+ __name(setReplace, "setReplace");
+ function decirc(val, k, edgeIndex, stack, parent, depth, options14) {
+ depth += 1;
+ var i;
+ if (typeof val === "object" && val !== null) {
+ for (i = 0; i < stack.length; i++) {
+ if (stack[i] === val) {
+ setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);
+ return;
+ }
+ }
+ if (typeof options14.depthLimit !== "undefined" && depth > options14.depthLimit) {
+ setReplace(LIMIT_REPLACE_NODE, val, k, parent);
+ return;
+ }
+ if (typeof options14.edgesLimit !== "undefined" && edgeIndex + 1 > options14.edgesLimit) {
+ setReplace(LIMIT_REPLACE_NODE, val, k, parent);
+ return;
+ }
+ stack.push(val);
+ if (Array.isArray(val)) {
+ for (i = 0; i < val.length; i++) {
+ decirc(val[i], i, i, stack, val, depth, options14);
+ }
+ } else {
+ var keys = Object.keys(val);
+ for (i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ decirc(val[key], key, i, stack, val, depth, options14);
+ }
+ }
+ stack.pop();
+ }
+ }
+ __name(decirc, "decirc");
+ function compareFunction(a, b) {
+ if (a < b) {
+ return -1;
+ }
+ if (a > b) {
+ return 1;
+ }
+ return 0;
+ }
+ __name(compareFunction, "compareFunction");
+ function deterministicStringify(obj, replacer2, spacer, options14) {
+ if (typeof options14 === "undefined") {
+ options14 = defaultOptions();
+ }
+ var tmp5 = deterministicDecirc(obj, "", 0, [], void 0, 0, options14) || obj;
+ var res;
+ try {
+ if (replacerStack.length === 0) {
+ res = JSON.stringify(tmp5, replacer2, spacer);
+ } else {
+ res = JSON.stringify(tmp5, replaceGetterValues(replacer2), spacer);
+ }
+ } catch (_2) {
+ return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]");
+ } finally {
+ while (arr.length !== 0) {
+ var part = arr.pop();
+ if (part.length === 4) {
+ Object.defineProperty(part[0], part[1], part[3]);
+ } else {
+ part[0][part[1]] = part[2];
+ }
+ }
+ }
+ return res;
+ }
+ __name(deterministicStringify, "deterministicStringify");
+ function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options14) {
+ depth += 1;
+ var i;
+ if (typeof val === "object" && val !== null) {
+ for (i = 0; i < stack.length; i++) {
+ if (stack[i] === val) {
+ setReplace(CIRCULAR_REPLACE_NODE, val, k, parent);
+ return;
+ }
+ }
+ try {
+ if (typeof val.toJSON === "function") {
+ return;
+ }
+ } catch (_2) {
+ return;
+ }
+ if (typeof options14.depthLimit !== "undefined" && depth > options14.depthLimit) {
+ setReplace(LIMIT_REPLACE_NODE, val, k, parent);
+ return;
+ }
+ if (typeof options14.edgesLimit !== "undefined" && edgeIndex + 1 > options14.edgesLimit) {
+ setReplace(LIMIT_REPLACE_NODE, val, k, parent);
+ return;
+ }
+ stack.push(val);
+ if (Array.isArray(val)) {
+ for (i = 0; i < val.length; i++) {
+ deterministicDecirc(val[i], i, i, stack, val, depth, options14);
+ }
+ } else {
+ var tmp5 = {};
+ var keys = Object.keys(val).sort(compareFunction);
+ for (i = 0; i < keys.length; i++) {
+ var key = keys[i];
+ deterministicDecirc(val[key], key, i, stack, val, depth, options14);
+ tmp5[key] = val[key];
+ }
+ if (typeof parent !== "undefined") {
+ arr.push([parent, k, val]);
+ parent[k] = tmp5;
+ } else {
+ return tmp5;
+ }
+ }
+ stack.pop();
+ }
+ }
+ __name(deterministicDecirc, "deterministicDecirc");
+ function replaceGetterValues(replacer2) {
+ replacer2 = typeof replacer2 !== "undefined" ? replacer2 : function(k, v) {
+ return v;
+ };
+ return function(key, val) {
+ if (replacerStack.length > 0) {
+ for (var i = 0; i < replacerStack.length; i++) {
+ var part = replacerStack[i];
+ if (part[1] === key && part[0] === val) {
+ val = part[2];
+ replacerStack.splice(i, 1);
+ break;
+ }
+ }
+ }
+ return replacer2.call(this, key, val);
+ };
+ }
+ __name(replaceGetterValues, "replaceGetterValues");
+ }
+});
+
+// ../../node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/isArguments.js
+var require_isArguments = __commonJS({
+ "../../node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/isArguments.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var toStr = Object.prototype.toString;
+ module2.exports = /* @__PURE__ */ __name(function isArguments(value) {
+ var str = toStr.call(value);
+ var isArgs = str === "[object Arguments]";
+ if (!isArgs) {
+ isArgs = str !== "[object Array]" && value !== null && typeof value === "object" && typeof value.length === "number" && value.length >= 0 && toStr.call(value.callee) === "[object Function]";
+ }
+ return isArgs;
+ }, "isArguments");
+ }
+});
+
+// ../../node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/implementation.js
+var require_implementation2 = __commonJS({
+ "../../node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/implementation.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var keysShim;
+ if (!Object.keys) {
+ has = Object.prototype.hasOwnProperty;
+ toStr = Object.prototype.toString;
+ isArgs = require_isArguments();
+ isEnumerable = Object.prototype.propertyIsEnumerable;
+ hasDontEnumBug = !isEnumerable.call({ toString: null }, "toString");
+ hasProtoEnumBug = isEnumerable.call(function() {
+ }, "prototype");
+ dontEnums = [
+ "toString",
+ "toLocaleString",
+ "valueOf",
+ "hasOwnProperty",
+ "isPrototypeOf",
+ "propertyIsEnumerable",
+ "constructor"
+ ];
+ equalsConstructorPrototype = /* @__PURE__ */ __name(function(o) {
+ var ctor = o.constructor;
+ return ctor && ctor.prototype === o;
+ }, "equalsConstructorPrototype");
+ excludedKeys = {
+ $applicationCache: true,
+ $console: true,
+ $external: true,
+ $frame: true,
+ $frameElement: true,
+ $frames: true,
+ $innerHeight: true,
+ $innerWidth: true,
+ $onmozfullscreenchange: true,
+ $onmozfullscreenerror: true,
+ $outerHeight: true,
+ $outerWidth: true,
+ $pageXOffset: true,
+ $pageYOffset: true,
+ $parent: true,
+ $scrollLeft: true,
+ $scrollTop: true,
+ $scrollX: true,
+ $scrollY: true,
+ $self: true,
+ $webkitIndexedDB: true,
+ $webkitStorageInfo: true,
+ $window: true
+ };
+ hasAutomationEqualityBug = function() {
+ if (typeof window === "undefined") {
+ return false;
+ }
+ for (var k in window) {
+ try {
+ if (!excludedKeys["$" + k] && has.call(window, k) && window[k] !== null && typeof window[k] === "object") {
+ try {
+ equalsConstructorPrototype(window[k]);
+ } catch (e2) {
+ return true;
+ }
+ }
+ } catch (e2) {
+ return true;
+ }
+ }
+ return false;
+ }();
+ equalsConstructorPrototypeIfNotBuggy = /* @__PURE__ */ __name(function(o) {
+ if (typeof window === "undefined" || !hasAutomationEqualityBug) {
+ return equalsConstructorPrototype(o);
+ }
+ try {
+ return equalsConstructorPrototype(o);
+ } catch (e2) {
+ return false;
+ }
+ }, "equalsConstructorPrototypeIfNotBuggy");
+ keysShim = /* @__PURE__ */ __name(function keys(object) {
+ var isObject2 = object !== null && typeof object === "object";
+ var isFunction2 = toStr.call(object) === "[object Function]";
+ var isArguments = isArgs(object);
+ var isString2 = isObject2 && toStr.call(object) === "[object String]";
+ var theKeys = [];
+ if (!isObject2 && !isFunction2 && !isArguments) {
+ throw new TypeError("Object.keys called on a non-object");
+ }
+ var skipProto = hasProtoEnumBug && isFunction2;
+ if (isString2 && object.length > 0 && !has.call(object, 0)) {
+ for (var i = 0; i < object.length; ++i) {
+ theKeys.push(String(i));
+ }
+ }
+ if (isArguments && object.length > 0) {
+ for (var j = 0; j < object.length; ++j) {
+ theKeys.push(String(j));
+ }
+ } else {
+ for (var name in object) {
+ if (!(skipProto && name === "prototype") && has.call(object, name)) {
+ theKeys.push(String(name));
+ }
+ }
+ }
+ if (hasDontEnumBug) {
+ var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
+ for (var k = 0; k < dontEnums.length; ++k) {
+ if (!(skipConstructor && dontEnums[k] === "constructor") && has.call(object, dontEnums[k])) {
+ theKeys.push(dontEnums[k]);
+ }
+ }
+ }
+ return theKeys;
+ }, "keys");
+ }
+ var has;
+ var toStr;
+ var isArgs;
+ var isEnumerable;
+ var hasDontEnumBug;
+ var hasProtoEnumBug;
+ var dontEnums;
+ var equalsConstructorPrototype;
+ var excludedKeys;
+ var hasAutomationEqualityBug;
+ var equalsConstructorPrototypeIfNotBuggy;
+ module2.exports = keysShim;
+ }
+});
+
+// ../../node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/index.js
+var require_object_keys = __commonJS({
+ "../../node_modules/.pnpm/object-keys@1.1.1/node_modules/object-keys/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var slice = Array.prototype.slice;
+ var isArgs = require_isArguments();
+ var origKeys = Object.keys;
+ var keysShim = origKeys ? /* @__PURE__ */ __name(function keys(o) {
+ return origKeys(o);
+ }, "keys") : require_implementation2();
+ var originalKeys = Object.keys;
+ keysShim.shim = /* @__PURE__ */ __name(function shimObjectKeys() {
+ if (Object.keys) {
+ var keysWorksWithArguments = function() {
+ var args = Object.keys(arguments);
+ return args && args.length === arguments.length;
+ }(1, 2);
+ if (!keysWorksWithArguments) {
+ Object.keys = /* @__PURE__ */ __name(function keys(object) {
+ if (isArgs(object)) {
+ return originalKeys(slice.call(object));
+ }
+ return originalKeys(object);
+ }, "keys");
+ }
+ } else {
+ Object.keys = keysShim;
+ }
+ return Object.keys || keysShim;
+ }, "shimObjectKeys");
+ module2.exports = keysShim;
+ }
+});
+
+// ../../node_modules/.pnpm/has-property-descriptors@1.0.0/node_modules/has-property-descriptors/index.js
+var require_has_property_descriptors = __commonJS({
+ "../../node_modules/.pnpm/has-property-descriptors@1.0.0/node_modules/has-property-descriptors/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var GetIntrinsic = require_get_intrinsic();
+ var $defineProperty = GetIntrinsic("%Object.defineProperty%", true);
+ var hasPropertyDescriptors = /* @__PURE__ */ __name(function hasPropertyDescriptors2() {
+ if ($defineProperty) {
+ try {
+ $defineProperty({}, "a", { value: 1 });
+ return true;
+ } catch (e2) {
+ return false;
+ }
+ }
+ return false;
+ }, "hasPropertyDescriptors");
+ hasPropertyDescriptors.hasArrayLengthDefineBug = /* @__PURE__ */ __name(function hasArrayLengthDefineBug() {
+ if (!hasPropertyDescriptors()) {
+ return null;
+ }
+ try {
+ return $defineProperty([], "length", { value: 1 }).length !== 1;
+ } catch (e2) {
+ return true;
+ }
+ }, "hasArrayLengthDefineBug");
+ module2.exports = hasPropertyDescriptors;
+ }
+});
+
+// ../../node_modules/.pnpm/define-properties@1.2.0/node_modules/define-properties/index.js
+var require_define_properties = __commonJS({
+ "../../node_modules/.pnpm/define-properties@1.2.0/node_modules/define-properties/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var keys = require_object_keys();
+ var hasSymbols = typeof Symbol === "function" && typeof Symbol("foo") === "symbol";
+ var toStr = Object.prototype.toString;
+ var concat = Array.prototype.concat;
+ var origDefineProperty = Object.defineProperty;
+ var isFunction2 = /* @__PURE__ */ __name(function(fn2) {
+ return typeof fn2 === "function" && toStr.call(fn2) === "[object Function]";
+ }, "isFunction");
+ var hasPropertyDescriptors = require_has_property_descriptors()();
+ var supportsDescriptors = origDefineProperty && hasPropertyDescriptors;
+ var defineProperty2 = /* @__PURE__ */ __name(function(object, name, value, predicate) {
+ if (name in object) {
+ if (predicate === true) {
+ if (object[name] === value) {
+ return;
+ }
+ } else if (!isFunction2(predicate) || !predicate()) {
+ return;
+ }
+ }
+ if (supportsDescriptors) {
+ origDefineProperty(object, name, {
+ configurable: true,
+ enumerable: false,
+ value,
+ writable: true
+ });
+ } else {
+ object[name] = value;
+ }
+ }, "defineProperty");
+ var defineProperties = /* @__PURE__ */ __name(function(object, map) {
+ var predicates = arguments.length > 2 ? arguments[2] : {};
+ var props = keys(map);
+ if (hasSymbols) {
+ props = concat.call(props, Object.getOwnPropertySymbols(map));
+ }
+ for (var i = 0; i < props.length; i += 1) {
+ defineProperty2(object, props[i], map[props[i]], predicates[props[i]]);
+ }
+ }, "defineProperties");
+ defineProperties.supportsDescriptors = !!supportsDescriptors;
+ module2.exports = defineProperties;
+ }
+});
+
+// ../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/implementation.js
+var require_implementation3 = __commonJS({
+ "../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/implementation.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = global;
+ }
+});
+
+// ../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/polyfill.js
+var require_polyfill = __commonJS({
+ "../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/polyfill.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var implementation = require_implementation3();
+ module2.exports = /* @__PURE__ */ __name(function getPolyfill() {
+ if (typeof global !== "object" || !global || global.Math !== Math || global.Array !== Array) {
+ return implementation;
+ }
+ return global;
+ }, "getPolyfill");
+ }
+});
+
+// ../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/shim.js
+var require_shim = __commonJS({
+ "../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/shim.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var define2 = require_define_properties();
+ var getPolyfill = require_polyfill();
+ module2.exports = /* @__PURE__ */ __name(function shimGlobal() {
+ var polyfill2 = getPolyfill();
+ if (define2.supportsDescriptors) {
+ var descriptor2 = Object.getOwnPropertyDescriptor(polyfill2, "globalThis");
+ if (!descriptor2 || descriptor2.configurable && (descriptor2.enumerable || !descriptor2.writable || globalThis !== polyfill2)) {
+ Object.defineProperty(polyfill2, "globalThis", {
+ configurable: true,
+ enumerable: false,
+ value: polyfill2,
+ writable: true
+ });
+ }
+ } else if (typeof globalThis !== "object" || globalThis !== polyfill2) {
+ polyfill2.globalThis = polyfill2;
+ }
+ return polyfill2;
+ }, "shimGlobal");
+ }
+});
+
+// ../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/index.js
+var require_globalthis = __commonJS({
+ "../../node_modules/.pnpm/globalthis@1.0.3/node_modules/globalthis/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var defineProperties = require_define_properties();
+ var implementation = require_implementation3();
+ var getPolyfill = require_polyfill();
+ var shim3 = require_shim();
+ var polyfill2 = getPolyfill();
+ var getGlobal = /* @__PURE__ */ __name(function() {
+ return polyfill2;
+ }, "getGlobal");
+ defineProperties(getGlobal, {
+ getPolyfill,
+ implementation,
+ shim: shim3
+ });
+ module2.exports = getGlobal;
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/constants.js
+var require_constants6 = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/constants.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.logLevels = void 0;
+ exports2.logLevels = {
+ debug: 20,
+ error: 50,
+ fatal: 60,
+ info: 30,
+ trace: 10,
+ warn: 40
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/fast-printf@1.6.9/node_modules/fast-printf/dist/src/tokenize.js
+var require_tokenize = __commonJS({
+ "../../node_modules/.pnpm/fast-printf@1.6.9/node_modules/fast-printf/dist/src/tokenize.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.tokenize = void 0;
+ var TokenRule = /(?:%(?([+0-]|-\+))?(?\d+)?(?\d+\$)?(?\.\d+)?(?[%BCESb-iosux]))|(\\%)/g;
+ var tokenize = /* @__PURE__ */ __name((subject) => {
+ let matchResult;
+ const tokens = [];
+ let argumentIndex = 0;
+ let lastIndex = 0;
+ let lastToken = null;
+ while ((matchResult = TokenRule.exec(subject)) !== null) {
+ if (matchResult.index > lastIndex) {
+ lastToken = {
+ literal: subject.slice(lastIndex, matchResult.index),
+ type: "literal"
+ };
+ tokens.push(lastToken);
+ }
+ const match = matchResult[0];
+ lastIndex = matchResult.index + match.length;
+ if (match === "\\%" || match === "%%") {
+ if (lastToken && lastToken.type === "literal") {
+ lastToken.literal += "%";
+ } else {
+ lastToken = {
+ literal: "%",
+ type: "literal"
+ };
+ tokens.push(lastToken);
+ }
+ } else if (matchResult.groups) {
+ lastToken = {
+ conversion: matchResult.groups.conversion,
+ flag: matchResult.groups.flag || null,
+ placeholder: match,
+ position: matchResult.groups.position ? Number.parseInt(matchResult.groups.position, 10) - 1 : argumentIndex++,
+ precision: matchResult.groups.precision ? Number.parseInt(matchResult.groups.precision.slice(1), 10) : null,
+ type: "placeholder",
+ width: matchResult.groups.width ? Number.parseInt(matchResult.groups.width, 10) : null
+ };
+ tokens.push(lastToken);
+ }
+ }
+ if (lastIndex <= subject.length - 1) {
+ if (lastToken && lastToken.type === "literal") {
+ lastToken.literal += subject.slice(lastIndex);
+ } else {
+ tokens.push({
+ literal: subject.slice(lastIndex),
+ type: "literal"
+ });
+ }
+ }
+ return tokens;
+ }, "tokenize");
+ exports2.tokenize = tokenize;
+ }
+});
+
+// ../../node_modules/.pnpm/fast-printf@1.6.9/node_modules/fast-printf/dist/src/createPrintf.js
+var require_createPrintf = __commonJS({
+ "../../node_modules/.pnpm/fast-printf@1.6.9/node_modules/fast-printf/dist/src/createPrintf.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createPrintf = void 0;
+ var boolean_1 = require_lib5();
+ var tokenize_1 = require_tokenize();
+ var formatDefaultUnboundExpression = /* @__PURE__ */ __name((subject, token) => {
+ return token.placeholder;
+ }, "formatDefaultUnboundExpression");
+ var createPrintf = /* @__PURE__ */ __name((configuration) => {
+ var _a2;
+ const padValue = /* @__PURE__ */ __name((value, width, flag) => {
+ if (flag === "-") {
+ return value.padEnd(width, " ");
+ } else if (flag === "-+") {
+ return ((Number(value) >= 0 ? "+" : "") + value).padEnd(width, " ");
+ } else if (flag === "+") {
+ return ((Number(value) >= 0 ? "+" : "") + value).padStart(width, " ");
+ } else if (flag === "0") {
+ return value.padStart(width, "0");
+ } else {
+ return value.padStart(width, " ");
+ }
+ }, "padValue");
+ const formatUnboundExpression = (_a2 = configuration === null || configuration === void 0 ? void 0 : configuration.formatUnboundExpression) !== null && _a2 !== void 0 ? _a2 : formatDefaultUnboundExpression;
+ const cache2 = {};
+ return (subject, ...boundValues) => {
+ let tokens = cache2[subject];
+ if (!tokens) {
+ tokens = cache2[subject] = tokenize_1.tokenize(subject);
+ }
+ let result = "";
+ for (const token of tokens) {
+ if (token.type === "literal") {
+ result += token.literal;
+ } else {
+ let boundValue = boundValues[token.position];
+ if (boundValue === void 0) {
+ result += formatUnboundExpression(subject, token, boundValues);
+ } else if (token.conversion === "b") {
+ result += boolean_1.boolean(boundValue) ? "true" : "false";
+ } else if (token.conversion === "B") {
+ result += boolean_1.boolean(boundValue) ? "TRUE" : "FALSE";
+ } else if (token.conversion === "c") {
+ result += boundValue;
+ } else if (token.conversion === "C") {
+ result += String(boundValue).toUpperCase();
+ } else if (token.conversion === "i" || token.conversion === "d") {
+ boundValue = String(Math.trunc(boundValue));
+ if (token.width !== null) {
+ boundValue = padValue(boundValue, token.width, token.flag);
+ }
+ result += boundValue;
+ } else if (token.conversion === "e") {
+ result += Number(boundValue).toExponential();
+ } else if (token.conversion === "E") {
+ result += Number(boundValue).toExponential().toUpperCase();
+ } else if (token.conversion === "f") {
+ if (token.precision !== null) {
+ boundValue = Number(boundValue).toFixed(token.precision);
+ }
+ if (token.width !== null) {
+ boundValue = padValue(String(boundValue), token.width, token.flag);
+ }
+ result += boundValue;
+ } else if (token.conversion === "o") {
+ result += (Number.parseInt(String(boundValue), 10) >>> 0).toString(8);
+ } else if (token.conversion === "s") {
+ if (token.width !== null) {
+ boundValue = padValue(String(boundValue), token.width, token.flag);
+ }
+ result += boundValue;
+ } else if (token.conversion === "S") {
+ if (token.width !== null) {
+ boundValue = padValue(String(boundValue), token.width, token.flag);
+ }
+ result += String(boundValue).toUpperCase();
+ } else if (token.conversion === "u") {
+ result += Number.parseInt(String(boundValue), 10) >>> 0;
+ } else if (token.conversion === "x") {
+ boundValue = (Number.parseInt(String(boundValue), 10) >>> 0).toString(16);
+ if (token.width !== null) {
+ boundValue = padValue(String(boundValue), token.width, token.flag);
+ }
+ result += boundValue;
+ } else {
+ throw new Error("Unknown format specifier.");
+ }
+ }
+ }
+ return result;
+ };
+ }, "createPrintf");
+ exports2.createPrintf = createPrintf;
+ }
+});
+
+// ../../node_modules/.pnpm/fast-printf@1.6.9/node_modules/fast-printf/dist/src/printf.js
+var require_printf = __commonJS({
+ "../../node_modules/.pnpm/fast-printf@1.6.9/node_modules/fast-printf/dist/src/printf.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.printf = exports2.createPrintf = void 0;
+ var createPrintf_1 = require_createPrintf();
+ Object.defineProperty(exports2, "createPrintf", { enumerable: true, get: function() {
+ return createPrintf_1.createPrintf;
+ } });
+ exports2.printf = createPrintf_1.createPrintf();
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/config.js
+var require_config = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/config.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.ROARR_LOG_FORMAT_VERSION = exports2.ROARR_VERSION = void 0;
+ exports2.ROARR_VERSION = "5.0.0";
+ exports2.ROARR_LOG_FORMAT_VERSION = "2.0.0";
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/utilities/hasOwnProperty.js
+var require_hasOwnProperty = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/utilities/hasOwnProperty.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.hasOwnProperty = void 0;
+ var hasOwnProperty2 = /* @__PURE__ */ __name((object, property) => {
+ return Object.prototype.hasOwnProperty.call(object, property);
+ }, "hasOwnProperty");
+ exports2.hasOwnProperty = hasOwnProperty2;
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/utilities/index.js
+var require_utilities = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/utilities/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.hasOwnProperty = void 0;
+ var hasOwnProperty_1 = require_hasOwnProperty();
+ Object.defineProperty(exports2, "hasOwnProperty", { enumerable: true, get: function() {
+ return hasOwnProperty_1.hasOwnProperty;
+ } });
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createLogger.js
+var require_createLogger = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createLogger.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
+ return mod && mod.__esModule ? mod : { "default": mod };
+ };
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createLogger = void 0;
+ var fast_printf_1 = require_printf();
+ var globalthis_1 = __importDefault(require_globalthis());
+ var config_1 = require_config();
+ var constants_1 = require_constants6();
+ var utilities_1 = require_utilities();
+ var loggedWarningAsyncLocalContext = false;
+ var globalThis2 = (0, globalthis_1.default)();
+ var getGlobalRoarrContext = /* @__PURE__ */ __name(() => {
+ return globalThis2.ROARR;
+ }, "getGlobalRoarrContext");
+ var createDefaultAsyncLocalContext = /* @__PURE__ */ __name(() => {
+ return {
+ messageContext: {},
+ transforms: []
+ };
+ }, "createDefaultAsyncLocalContext");
+ var getAsyncLocalContext = /* @__PURE__ */ __name(() => {
+ const asyncLocalStorage = getGlobalRoarrContext().asyncLocalStorage;
+ if (!asyncLocalStorage) {
+ throw new Error("AsyncLocalContext is unavailable.");
+ }
+ const asyncLocalContext = asyncLocalStorage.getStore();
+ if (asyncLocalContext) {
+ return asyncLocalContext;
+ }
+ return createDefaultAsyncLocalContext();
+ }, "getAsyncLocalContext");
+ var isAsyncLocalContextAvailable = /* @__PURE__ */ __name(() => {
+ return Boolean(getGlobalRoarrContext().asyncLocalStorage);
+ }, "isAsyncLocalContextAvailable");
+ var getSequence = /* @__PURE__ */ __name(() => {
+ if (isAsyncLocalContextAvailable()) {
+ const asyncLocalContext = getAsyncLocalContext();
+ if ((0, utilities_1.hasOwnProperty)(asyncLocalContext, "sequenceRoot") && (0, utilities_1.hasOwnProperty)(asyncLocalContext, "sequence")) {
+ return String(asyncLocalContext.sequenceRoot) + "." + String(asyncLocalContext.sequence++);
+ }
+ return String(getGlobalRoarrContext().sequence++);
+ }
+ return String(getGlobalRoarrContext().sequence++);
+ }, "getSequence");
+ var createLogger = /* @__PURE__ */ __name((onMessage, parentMessageContext = {}, transforms = []) => {
+ const log = /* @__PURE__ */ __name((a, b, c, d, e2, f, g, h, i, j) => {
+ const time = Date.now();
+ const sequence = getSequence();
+ let asyncLocalContext;
+ if (isAsyncLocalContextAvailable()) {
+ asyncLocalContext = getAsyncLocalContext();
+ } else {
+ asyncLocalContext = createDefaultAsyncLocalContext();
+ }
+ let context2;
+ let message;
+ if (typeof a === "string") {
+ context2 = {
+ ...asyncLocalContext.messageContext,
+ ...parentMessageContext
+ };
+ } else {
+ context2 = {
+ ...asyncLocalContext.messageContext,
+ ...parentMessageContext,
+ ...a
+ };
+ }
+ if (typeof a === "string" && b === void 0) {
+ message = a;
+ } else if (typeof a === "string") {
+ message = (0, fast_printf_1.printf)(a, b, c, d, e2, f, g, h, i, j);
+ } else {
+ let fallbackMessage = b;
+ if (typeof b !== "string") {
+ if (b === void 0) {
+ fallbackMessage = "";
+ } else {
+ throw new TypeError("Message must be a string. Received " + typeof b + ".");
+ }
+ }
+ message = (0, fast_printf_1.printf)(fallbackMessage, c, d, e2, f, g, h, i, j);
+ }
+ let packet = {
+ context: context2,
+ message,
+ sequence,
+ time,
+ version: config_1.ROARR_LOG_FORMAT_VERSION
+ };
+ for (const transform of [...asyncLocalContext.transforms, ...transforms]) {
+ packet = transform(packet);
+ if (typeof packet !== "object" || packet === null) {
+ throw new Error("Message transform function must return a message object.");
+ }
+ }
+ onMessage(packet);
+ }, "log");
+ log.child = (context2) => {
+ let asyncLocalContext;
+ if (isAsyncLocalContextAvailable()) {
+ asyncLocalContext = getAsyncLocalContext();
+ } else {
+ asyncLocalContext = createDefaultAsyncLocalContext();
+ }
+ if (typeof context2 === "function") {
+ return (0, exports2.createLogger)(onMessage, {
+ ...asyncLocalContext.messageContext,
+ ...parentMessageContext,
+ ...context2
+ }, [
+ context2,
+ ...transforms
+ ]);
+ }
+ return (0, exports2.createLogger)(onMessage, {
+ ...asyncLocalContext.messageContext,
+ ...parentMessageContext,
+ ...context2
+ }, transforms);
+ };
+ log.getContext = () => {
+ let asyncLocalContext;
+ if (isAsyncLocalContextAvailable()) {
+ asyncLocalContext = getAsyncLocalContext();
+ } else {
+ asyncLocalContext = createDefaultAsyncLocalContext();
+ }
+ return {
+ ...asyncLocalContext.messageContext,
+ ...parentMessageContext
+ };
+ };
+ log.adopt = async (routine, context2) => {
+ if (!isAsyncLocalContextAvailable()) {
+ if (loggedWarningAsyncLocalContext === false) {
+ loggedWarningAsyncLocalContext = true;
+ onMessage({
+ context: {
+ logLevel: constants_1.logLevels.warn,
+ package: "roarr"
+ },
+ message: "async_hooks are unavailable; Roarr.adopt will not function as expected",
+ sequence: getSequence(),
+ time: Date.now(),
+ version: config_1.ROARR_LOG_FORMAT_VERSION
+ });
+ }
+ return routine();
+ }
+ const asyncLocalContext = getAsyncLocalContext();
+ let sequenceRoot;
+ if ((0, utilities_1.hasOwnProperty)(asyncLocalContext, "sequenceRoot")) {
+ sequenceRoot = asyncLocalContext.sequenceRoot + "." + String(asyncLocalContext.sequence++);
+ } else {
+ sequenceRoot = String(getGlobalRoarrContext().sequence++);
+ }
+ let nextContext = {
+ ...asyncLocalContext.messageContext
+ };
+ const nextTransforms = [
+ ...asyncLocalContext.transforms
+ ];
+ if (typeof context2 === "function") {
+ nextTransforms.push(context2);
+ } else {
+ nextContext = {
+ ...nextContext,
+ ...context2
+ };
+ }
+ const asyncLocalStorage = getGlobalRoarrContext().asyncLocalStorage;
+ if (!asyncLocalStorage) {
+ throw new Error("Async local context unavailable.");
+ }
+ return asyncLocalStorage.run({
+ messageContext: nextContext,
+ sequence: 0,
+ sequenceRoot,
+ transforms: nextTransforms
+ }, () => {
+ return routine();
+ });
+ };
+ log.trace = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.trace
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.debug = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.debug
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.info = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.info
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.warn = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.warn
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.error = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.error
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.fatal = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.fatal
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ return log;
+ }, "createLogger");
+ exports2.createLogger = createLogger;
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createMockLogger.js
+var require_createMockLogger = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createMockLogger.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createMockLogger = void 0;
+ var constants_1 = require_constants6();
+ var createMockLogger = /* @__PURE__ */ __name((onMessage, parentContext) => {
+ const log = /* @__PURE__ */ __name(() => {
+ return void 0;
+ }, "log");
+ log.adopt = async (routine) => {
+ return routine();
+ };
+ log.child = (context2) => {
+ return (0, exports2.createMockLogger)(onMessage, parentContext);
+ };
+ log.getContext = () => {
+ return {};
+ };
+ log.trace = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.trace
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.debug = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.debug
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.info = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.info
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.warn = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.warn
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.error = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.error
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ log.fatal = (a, b, c, d, e2, f, g, h, i, j) => {
+ log.child({
+ logLevel: constants_1.logLevels.fatal
+ })(a, b, c, d, e2, f, g, h, i, j);
+ };
+ return log;
+ }, "createMockLogger");
+ exports2.createMockLogger = createMockLogger;
+ }
+});
+
+// ../../node_modules/.pnpm/semver-compare@1.0.0/node_modules/semver-compare/index.js
+var require_semver_compare = __commonJS({
+ "../../node_modules/.pnpm/semver-compare@1.0.0/node_modules/semver-compare/index.js"(exports2, module2) {
+ init_import_meta_url();
+ module2.exports = /* @__PURE__ */ __name(function cmp(a, b) {
+ var pa2 = a.split(".");
+ var pb = b.split(".");
+ for (var i = 0; i < 3; i++) {
+ var na = Number(pa2[i]);
+ var nb = Number(pb[i]);
+ if (na > nb)
+ return 1;
+ if (nb > na)
+ return -1;
+ if (!isNaN(na) && isNaN(nb))
+ return 1;
+ if (isNaN(na) && !isNaN(nb))
+ return -1;
+ }
+ return 0;
+ }, "cmp");
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createNodeWriter.js
+var require_createNodeWriter = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createNodeWriter.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createNodeWriter = void 0;
+ var createBlockingWriter = /* @__PURE__ */ __name((stream2) => {
+ return (message) => {
+ stream2.write(message + "\n");
+ };
+ }, "createBlockingWriter");
+ var createNodeWriter = /* @__PURE__ */ __name(() => {
+ var _a2;
+ const targetStream = ((_a2 = process.env.ROARR_STREAM) !== null && _a2 !== void 0 ? _a2 : "STDOUT").toUpperCase();
+ const stream2 = targetStream.toUpperCase() === "STDOUT" ? process.stdout : process.stderr;
+ return createBlockingWriter(stream2);
+ }, "createNodeWriter");
+ exports2.createNodeWriter = createNodeWriter;
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createRoarrInitialGlobalState.js
+var require_createRoarrInitialGlobalState = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/factories/createRoarrInitialGlobalState.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
+ return mod && mod.__esModule ? mod : { "default": mod };
+ };
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createRoarrInitialGlobalState = void 0;
+ var semver_compare_1 = __importDefault(require_semver_compare());
+ var config_1 = require_config();
+ var createNodeWriter_1 = require_createNodeWriter();
+ var createRoarrInitialGlobalState = /* @__PURE__ */ __name((currentState) => {
+ const versions = (currentState.versions || []).concat();
+ if (versions.length > 1) {
+ versions.sort(semver_compare_1.default);
+ }
+ const currentIsLatestVersion = !versions.length || (0, semver_compare_1.default)(config_1.ROARR_VERSION, versions[versions.length - 1]) === 1;
+ if (!versions.includes(config_1.ROARR_VERSION)) {
+ versions.push(config_1.ROARR_VERSION);
+ }
+ versions.sort(semver_compare_1.default);
+ let newState = {
+ sequence: 0,
+ ...currentState,
+ versions
+ };
+ if (currentIsLatestVersion || !newState.write) {
+ try {
+ const AsyncLocalStorage = require("async_hooks").AsyncLocalStorage;
+ const asyncLocalStorage = new AsyncLocalStorage();
+ newState = {
+ ...newState,
+ ...{
+ write: (0, createNodeWriter_1.createNodeWriter)()
+ },
+ asyncLocalStorage
+ };
+ } catch (_a2) {
+ }
+ }
+ return newState;
+ }, "createRoarrInitialGlobalState");
+ exports2.createRoarrInitialGlobalState = createRoarrInitialGlobalState;
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/getLogLevelName.js
+var require_getLogLevelName = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/getLogLevelName.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.getLogLevelName = void 0;
+ var getLogLevelName = /* @__PURE__ */ __name((numericLogLevel) => {
+ if (numericLogLevel <= 10) {
+ return "trace";
+ }
+ if (numericLogLevel <= 20) {
+ return "debug";
+ }
+ if (numericLogLevel <= 30) {
+ return "info";
+ }
+ if (numericLogLevel <= 40) {
+ return "warn";
+ }
+ if (numericLogLevel <= 50) {
+ return "error";
+ }
+ return "fatal";
+ }, "getLogLevelName");
+ exports2.getLogLevelName = getLogLevelName;
+ }
+});
+
+// ../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/Roarr.js
+var require_Roarr = __commonJS({
+ "../../node_modules/.pnpm/roarr@7.11.0/node_modules/roarr/dist/src/Roarr.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
+ return mod && mod.__esModule ? mod : { "default": mod };
+ };
+ var _a2;
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.ROARR = exports2.Roarr = exports2.logLevels = exports2.getLogLevelName = void 0;
+ var boolean_1 = require_lib5();
+ var fast_json_stringify_1 = __importDefault(require_fast_json_stringify());
+ var fast_safe_stringify_1 = __importDefault(require_fast_safe_stringify());
+ var globalthis_1 = __importDefault(require_globalthis());
+ var constants_1 = require_constants6();
+ Object.defineProperty(exports2, "logLevels", { enumerable: true, get: function() {
+ return constants_1.logLevels;
+ } });
+ var createLogger_1 = require_createLogger();
+ var createMockLogger_1 = require_createMockLogger();
+ var createRoarrInitialGlobalState_1 = require_createRoarrInitialGlobalState();
+ var getLogLevelName_1 = require_getLogLevelName();
+ Object.defineProperty(exports2, "getLogLevelName", { enumerable: true, get: function() {
+ return getLogLevelName_1.getLogLevelName;
+ } });
+ var fastStringify = (0, fast_json_stringify_1.default)({
+ properties: {
+ message: {
+ type: "string"
+ },
+ sequence: {
+ type: "string"
+ },
+ time: {
+ type: "integer"
+ },
+ version: {
+ type: "string"
+ }
+ },
+ type: "object"
+ });
+ var globalThis2 = (0, globalthis_1.default)();
+ var ROARR = globalThis2.ROARR = (0, createRoarrInitialGlobalState_1.createRoarrInitialGlobalState)(globalThis2.ROARR || {});
+ exports2.ROARR = ROARR;
+ var logFactory = createLogger_1.createLogger;
+ var enabled = (0, boolean_1.boolean)((_a2 = process.env.ROARR_LOG) !== null && _a2 !== void 0 ? _a2 : "");
+ if (!enabled) {
+ logFactory = createMockLogger_1.createMockLogger;
+ }
+ var serializeMessage = /* @__PURE__ */ __name((message) => {
+ return '{"context":' + (0, fast_safe_stringify_1.default)(message.context) + "," + fastStringify(message).slice(1);
+ }, "serializeMessage");
+ var Roarr = logFactory((message) => {
+ var _a3;
+ if (ROARR.write) {
+ ROARR.write(((_a3 = ROARR.serializeMessage) !== null && _a3 !== void 0 ? _a3 : serializeMessage)(message));
+ }
+ });
+ exports2.Roarr = Roarr;
+ }
+});
+
+// ../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/Logger.js
+var require_Logger = __commonJS({
+ "../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/Logger.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.Logger = void 0;
+ var roarr_1 = require_Roarr();
+ exports2.Logger = roarr_1.Roarr.child({
+ package: "http-terminator"
+ });
+ }
+});
+
+// ../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/factories/createInternalHttpTerminator.js
+var require_createInternalHttpTerminator = __commonJS({
+ "../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/factories/createInternalHttpTerminator.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
+ return mod && mod.__esModule ? mod : { "default": mod };
+ };
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createInternalHttpTerminator = void 0;
+ var http_1 = __importDefault(require("http"));
+ var p_wait_for_1 = __importDefault(require_p_wait_for());
+ var Logger_1 = require_Logger();
+ var log = Logger_1.Logger.child({
+ namespace: "createHttpTerminator"
+ });
+ var configurationDefaults = {
+ gracefulTerminationTimeout: 1e3
+ };
+ var createInternalHttpTerminator = /* @__PURE__ */ __name((configurationInput) => {
+ const configuration = {
+ ...configurationDefaults,
+ ...configurationInput
+ };
+ const server2 = configuration.server;
+ const sockets = /* @__PURE__ */ new Set();
+ const secureSockets = /* @__PURE__ */ new Set();
+ let terminating;
+ server2.on("connection", (socket) => {
+ if (terminating) {
+ socket.destroy();
+ } else {
+ sockets.add(socket);
+ socket.once("close", () => {
+ sockets.delete(socket);
+ });
+ }
+ });
+ server2.on("secureConnection", (socket) => {
+ if (terminating) {
+ socket.destroy();
+ } else {
+ secureSockets.add(socket);
+ socket.once("close", () => {
+ secureSockets.delete(socket);
+ });
+ }
+ });
+ const destroySocket = /* @__PURE__ */ __name((socket) => {
+ socket.destroy();
+ if (socket.server instanceof http_1.default.Server) {
+ sockets.delete(socket);
+ } else {
+ secureSockets.delete(socket);
+ }
+ }, "destroySocket");
+ const terminate = /* @__PURE__ */ __name(async () => {
+ if (terminating) {
+ log.warn("already terminating HTTP server");
+ return terminating;
+ }
+ let resolveTerminating;
+ let rejectTerminating;
+ terminating = new Promise((resolve18, reject) => {
+ resolveTerminating = resolve18;
+ rejectTerminating = reject;
+ });
+ server2.on("request", (incomingMessage, outgoingMessage) => {
+ if (!outgoingMessage.headersSent) {
+ outgoingMessage.setHeader("connection", "close");
+ }
+ });
+ for (const socket of sockets) {
+ if (!(socket.server instanceof http_1.default.Server)) {
+ continue;
+ }
+ const serverResponse = socket._httpMessage;
+ if (serverResponse) {
+ if (!serverResponse.headersSent) {
+ serverResponse.setHeader("connection", "close");
+ }
+ continue;
+ }
+ destroySocket(socket);
+ }
+ for (const socket of secureSockets) {
+ const serverResponse = socket._httpMessage;
+ if (serverResponse) {
+ if (!serverResponse.headersSent) {
+ serverResponse.setHeader("connection", "close");
+ }
+ continue;
+ }
+ destroySocket(socket);
+ }
+ try {
+ await (0, p_wait_for_1.default)(() => {
+ return sockets.size === 0 && secureSockets.size === 0;
+ }, {
+ interval: 10,
+ timeout: configuration.gracefulTerminationTimeout
+ });
+ } catch (_a2) {
+ } finally {
+ for (const socket of sockets) {
+ destroySocket(socket);
+ }
+ for (const socket of secureSockets) {
+ destroySocket(socket);
+ }
+ }
+ server2.close((error) => {
+ if (error) {
+ rejectTerminating(error);
+ } else {
+ resolveTerminating();
+ }
+ });
+ return terminating;
+ }, "terminate");
+ return {
+ secureSockets,
+ sockets,
+ terminate
+ };
+ }, "createInternalHttpTerminator");
+ exports2.createInternalHttpTerminator = createInternalHttpTerminator;
+ }
+});
+
+// ../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/factories/createHttpTerminator.js
+var require_createHttpTerminator = __commonJS({
+ "../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/factories/createHttpTerminator.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createHttpTerminator = void 0;
+ var createInternalHttpTerminator_1 = require_createInternalHttpTerminator();
+ var createHttpTerminator3 = /* @__PURE__ */ __name((configurationInput) => {
+ const httpTerminator = (0, createInternalHttpTerminator_1.createInternalHttpTerminator)(configurationInput);
+ return {
+ terminate: httpTerminator.terminate
+ };
+ }, "createHttpTerminator");
+ exports2.createHttpTerminator = createHttpTerminator3;
+ }
+});
+
+// ../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/index.js
+var require_src5 = __commonJS({
+ "../../node_modules/.pnpm/http-terminator@3.2.0/node_modules/http-terminator/dist/src/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.createHttpTerminator = void 0;
+ var createHttpTerminator_1 = require_createHttpTerminator();
+ Object.defineProperty(exports2, "createHttpTerminator", { enumerable: true, get: function() {
+ return createHttpTerminator_1.createHttpTerminator;
+ } });
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/stream.js
+var require_stream3 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/stream.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var { Duplex } = require("stream");
+ function emitClose(stream2) {
+ stream2.emit("close");
+ }
+ __name(emitClose, "emitClose");
+ function duplexOnEnd() {
+ if (!this.destroyed && this._writableState.finished) {
+ this.destroy();
+ }
+ }
+ __name(duplexOnEnd, "duplexOnEnd");
+ function duplexOnError(err) {
+ this.removeListener("error", duplexOnError);
+ this.destroy();
+ if (this.listenerCount("error") === 0) {
+ this.emit("error", err);
+ }
+ }
+ __name(duplexOnError, "duplexOnError");
+ function createWebSocketStream2(ws, options14) {
+ let terminateOnDestroy = true;
+ const duplex = new Duplex({
+ ...options14,
+ autoDestroy: false,
+ emitClose: false,
+ objectMode: false,
+ writableObjectMode: false
+ });
+ ws.on("message", /* @__PURE__ */ __name(function message(msg, isBinary) {
+ const data = !isBinary && duplex._readableState.objectMode ? msg.toString() : msg;
+ if (!duplex.push(data))
+ ws.pause();
+ }, "message"));
+ ws.once("error", /* @__PURE__ */ __name(function error(err) {
+ if (duplex.destroyed)
+ return;
+ terminateOnDestroy = false;
+ duplex.destroy(err);
+ }, "error"));
+ ws.once("close", /* @__PURE__ */ __name(function close() {
+ if (duplex.destroyed)
+ return;
+ duplex.push(null);
+ }, "close"));
+ duplex._destroy = function(err, callback) {
+ if (ws.readyState === ws.CLOSED) {
+ callback(err);
+ process.nextTick(emitClose, duplex);
+ return;
+ }
+ let called = false;
+ ws.once("error", /* @__PURE__ */ __name(function error(err2) {
+ called = true;
+ callback(err2);
+ }, "error"));
+ ws.once("close", /* @__PURE__ */ __name(function close() {
+ if (!called)
+ callback(err);
+ process.nextTick(emitClose, duplex);
+ }, "close"));
+ if (terminateOnDestroy)
+ ws.terminate();
+ };
+ duplex._final = function(callback) {
+ if (ws.readyState === ws.CONNECTING) {
+ ws.once("open", /* @__PURE__ */ __name(function open3() {
+ duplex._final(callback);
+ }, "open"));
+ return;
+ }
+ if (ws._socket === null)
+ return;
+ if (ws._socket._writableState.finished) {
+ callback();
+ if (duplex._readableState.endEmitted)
+ duplex.destroy();
+ } else {
+ ws._socket.once("finish", /* @__PURE__ */ __name(function finish() {
+ callback();
+ }, "finish"));
+ ws.close();
+ }
+ };
+ duplex._read = function() {
+ if (ws.isPaused)
+ ws.resume();
+ };
+ duplex._write = function(chunk, encoding, callback) {
+ if (ws.readyState === ws.CONNECTING) {
+ ws.once("open", /* @__PURE__ */ __name(function open3() {
+ duplex._write(chunk, encoding, callback);
+ }, "open"));
+ return;
+ }
+ ws.send(chunk, callback);
+ };
+ duplex.on("end", duplexOnEnd);
+ duplex.on("error", duplexOnError);
+ return duplex;
+ }
+ __name(createWebSocketStream2, "createWebSocketStream");
+ module2.exports = createWebSocketStream2;
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/constants.js
+var require_constants7 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/constants.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = {
+ BINARY_TYPES: ["nodebuffer", "arraybuffer", "fragments"],
+ EMPTY_BUFFER: Buffer.alloc(0),
+ GUID: "258EAFA5-E914-47DA-95CA-C5AB0DC85B11",
+ kForOnEventAttribute: Symbol("kIsForOnEventAttribute"),
+ kListener: Symbol("kListener"),
+ kStatusCode: Symbol("status-code"),
+ kWebSocket: Symbol("websocket"),
+ NOOP: () => {
+ }
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/buffer-util.js
+var require_buffer_util2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/buffer-util.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var { EMPTY_BUFFER } = require_constants7();
+ function concat(list, totalLength) {
+ if (list.length === 0)
+ return EMPTY_BUFFER;
+ if (list.length === 1)
+ return list[0];
+ const target = Buffer.allocUnsafe(totalLength);
+ let offset = 0;
+ for (let i = 0; i < list.length; i++) {
+ const buf = list[i];
+ target.set(buf, offset);
+ offset += buf.length;
+ }
+ if (offset < totalLength)
+ return target.slice(0, offset);
+ return target;
+ }
+ __name(concat, "concat");
+ function _mask(source, mask, output, offset, length) {
+ for (let i = 0; i < length; i++) {
+ output[offset + i] = source[i] ^ mask[i & 3];
+ }
+ }
+ __name(_mask, "_mask");
+ function _unmask(buffer, mask) {
+ for (let i = 0; i < buffer.length; i++) {
+ buffer[i] ^= mask[i & 3];
+ }
+ }
+ __name(_unmask, "_unmask");
+ function toArrayBuffer(buf) {
+ if (buf.byteLength === buf.buffer.byteLength) {
+ return buf.buffer;
+ }
+ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
+ }
+ __name(toArrayBuffer, "toArrayBuffer");
+ function toBuffer(data) {
+ toBuffer.readOnly = true;
+ if (Buffer.isBuffer(data))
+ return data;
+ let buf;
+ if (data instanceof ArrayBuffer) {
+ buf = Buffer.from(data);
+ } else if (ArrayBuffer.isView(data)) {
+ buf = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
+ } else {
+ buf = Buffer.from(data);
+ toBuffer.readOnly = false;
+ }
+ return buf;
+ }
+ __name(toBuffer, "toBuffer");
+ module2.exports = {
+ concat,
+ mask: _mask,
+ toArrayBuffer,
+ toBuffer,
+ unmask: _unmask
+ };
+ if (!process.env.WS_NO_BUFFER_UTIL) {
+ try {
+ const bufferUtil = require("bufferutil");
+ module2.exports.mask = function(source, mask, output, offset, length) {
+ if (length < 48)
+ _mask(source, mask, output, offset, length);
+ else
+ bufferUtil.mask(source, mask, output, offset, length);
+ };
+ module2.exports.unmask = function(buffer, mask) {
+ if (buffer.length < 32)
+ _unmask(buffer, mask);
+ else
+ bufferUtil.unmask(buffer, mask);
+ };
+ } catch (e2) {
+ }
+ }
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/limiter.js
+var require_limiter2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/limiter.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var kDone = Symbol("kDone");
+ var kRun = Symbol("kRun");
+ var Limiter = class {
+ /**
+ * Creates a new `Limiter`.
+ *
+ * @param {Number} [concurrency=Infinity] The maximum number of jobs allowed
+ * to run concurrently
+ */
+ constructor(concurrency) {
+ this[kDone] = () => {
+ this.pending--;
+ this[kRun]();
+ };
+ this.concurrency = concurrency || Infinity;
+ this.jobs = [];
+ this.pending = 0;
+ }
+ /**
+ * Adds a job to the queue.
+ *
+ * @param {Function} job The job to run
+ * @public
+ */
+ add(job) {
+ this.jobs.push(job);
+ this[kRun]();
+ }
+ /**
+ * Removes a job from the queue and runs it if possible.
+ *
+ * @private
+ */
+ [kRun]() {
+ if (this.pending === this.concurrency)
+ return;
+ if (this.jobs.length) {
+ const job = this.jobs.shift();
+ this.pending++;
+ job(this[kDone]);
+ }
+ }
+ };
+ __name(Limiter, "Limiter");
+ module2.exports = Limiter;
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/permessage-deflate.js
+var require_permessage_deflate2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/permessage-deflate.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var zlib = require("zlib");
+ var bufferUtil = require_buffer_util2();
+ var Limiter = require_limiter2();
+ var { kStatusCode } = require_constants7();
+ var TRAILER = Buffer.from([0, 0, 255, 255]);
+ var kPerMessageDeflate = Symbol("permessage-deflate");
+ var kTotalLength = Symbol("total-length");
+ var kCallback = Symbol("callback");
+ var kBuffers = Symbol("buffers");
+ var kError = Symbol("error");
+ var zlibLimiter;
+ var PerMessageDeflate = class {
+ /**
+ * Creates a PerMessageDeflate instance.
+ *
+ * @param {Object} [options] Configuration options
+ * @param {(Boolean|Number)} [options.clientMaxWindowBits] Advertise support
+ * for, or request, a custom client window size
+ * @param {Boolean} [options.clientNoContextTakeover=false] Advertise/
+ * acknowledge disabling of client context takeover
+ * @param {Number} [options.concurrencyLimit=10] The number of concurrent
+ * calls to zlib
+ * @param {(Boolean|Number)} [options.serverMaxWindowBits] Request/confirm the
+ * use of a custom server window size
+ * @param {Boolean} [options.serverNoContextTakeover=false] Request/accept
+ * disabling of server context takeover
+ * @param {Number} [options.threshold=1024] Size (in bytes) below which
+ * messages should not be compressed if context takeover is disabled
+ * @param {Object} [options.zlibDeflateOptions] Options to pass to zlib on
+ * deflate
+ * @param {Object} [options.zlibInflateOptions] Options to pass to zlib on
+ * inflate
+ * @param {Boolean} [isServer=false] Create the instance in either server or
+ * client mode
+ * @param {Number} [maxPayload=0] The maximum allowed message length
+ */
+ constructor(options14, isServer, maxPayload) {
+ this._maxPayload = maxPayload | 0;
+ this._options = options14 || {};
+ this._threshold = this._options.threshold !== void 0 ? this._options.threshold : 1024;
+ this._isServer = !!isServer;
+ this._deflate = null;
+ this._inflate = null;
+ this.params = null;
+ if (!zlibLimiter) {
+ const concurrency = this._options.concurrencyLimit !== void 0 ? this._options.concurrencyLimit : 10;
+ zlibLimiter = new Limiter(concurrency);
+ }
+ }
+ /**
+ * @type {String}
+ */
+ static get extensionName() {
+ return "permessage-deflate";
+ }
+ /**
+ * Create an extension negotiation offer.
+ *
+ * @return {Object} Extension parameters
+ * @public
+ */
+ offer() {
+ const params = {};
+ if (this._options.serverNoContextTakeover) {
+ params.server_no_context_takeover = true;
+ }
+ if (this._options.clientNoContextTakeover) {
+ params.client_no_context_takeover = true;
+ }
+ if (this._options.serverMaxWindowBits) {
+ params.server_max_window_bits = this._options.serverMaxWindowBits;
+ }
+ if (this._options.clientMaxWindowBits) {
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
+ } else if (this._options.clientMaxWindowBits == null) {
+ params.client_max_window_bits = true;
+ }
+ return params;
+ }
+ /**
+ * Accept an extension negotiation offer/response.
+ *
+ * @param {Array} configurations The extension negotiation offers/reponse
+ * @return {Object} Accepted configuration
+ * @public
+ */
+ accept(configurations) {
+ configurations = this.normalizeParams(configurations);
+ this.params = this._isServer ? this.acceptAsServer(configurations) : this.acceptAsClient(configurations);
+ return this.params;
+ }
+ /**
+ * Releases all resources used by the extension.
+ *
+ * @public
+ */
+ cleanup() {
+ if (this._inflate) {
+ this._inflate.close();
+ this._inflate = null;
+ }
+ if (this._deflate) {
+ const callback = this._deflate[kCallback];
+ this._deflate.close();
+ this._deflate = null;
+ if (callback) {
+ callback(
+ new Error(
+ "The deflate stream was closed while data was being processed"
+ )
+ );
+ }
+ }
+ }
+ /**
+ * Accept an extension negotiation offer.
+ *
+ * @param {Array} offers The extension negotiation offers
+ * @return {Object} Accepted configuration
+ * @private
+ */
+ acceptAsServer(offers) {
+ const opts = this._options;
+ const accepted = offers.find((params) => {
+ if (opts.serverNoContextTakeover === false && params.server_no_context_takeover || params.server_max_window_bits && (opts.serverMaxWindowBits === false || typeof opts.serverMaxWindowBits === "number" && opts.serverMaxWindowBits > params.server_max_window_bits) || typeof opts.clientMaxWindowBits === "number" && !params.client_max_window_bits) {
+ return false;
+ }
+ return true;
+ });
+ if (!accepted) {
+ throw new Error("None of the extension offers can be accepted");
+ }
+ if (opts.serverNoContextTakeover) {
+ accepted.server_no_context_takeover = true;
+ }
+ if (opts.clientNoContextTakeover) {
+ accepted.client_no_context_takeover = true;
+ }
+ if (typeof opts.serverMaxWindowBits === "number") {
+ accepted.server_max_window_bits = opts.serverMaxWindowBits;
+ }
+ if (typeof opts.clientMaxWindowBits === "number") {
+ accepted.client_max_window_bits = opts.clientMaxWindowBits;
+ } else if (accepted.client_max_window_bits === true || opts.clientMaxWindowBits === false) {
+ delete accepted.client_max_window_bits;
+ }
+ return accepted;
+ }
+ /**
+ * Accept the extension negotiation response.
+ *
+ * @param {Array} response The extension negotiation response
+ * @return {Object} Accepted configuration
+ * @private
+ */
+ acceptAsClient(response) {
+ const params = response[0];
+ if (this._options.clientNoContextTakeover === false && params.client_no_context_takeover) {
+ throw new Error('Unexpected parameter "client_no_context_takeover"');
+ }
+ if (!params.client_max_window_bits) {
+ if (typeof this._options.clientMaxWindowBits === "number") {
+ params.client_max_window_bits = this._options.clientMaxWindowBits;
+ }
+ } else if (this._options.clientMaxWindowBits === false || typeof this._options.clientMaxWindowBits === "number" && params.client_max_window_bits > this._options.clientMaxWindowBits) {
+ throw new Error(
+ 'Unexpected or invalid parameter "client_max_window_bits"'
+ );
+ }
+ return params;
+ }
+ /**
+ * Normalize parameters.
+ *
+ * @param {Array} configurations The extension negotiation offers/reponse
+ * @return {Array} The offers/response with normalized parameters
+ * @private
+ */
+ normalizeParams(configurations) {
+ configurations.forEach((params) => {
+ Object.keys(params).forEach((key) => {
+ let value = params[key];
+ if (value.length > 1) {
+ throw new Error(`Parameter "${key}" must have only a single value`);
+ }
+ value = value[0];
+ if (key === "client_max_window_bits") {
+ if (value !== true) {
+ const num = +value;
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
+ throw new TypeError(
+ `Invalid value for parameter "${key}": ${value}`
+ );
+ }
+ value = num;
+ } else if (!this._isServer) {
+ throw new TypeError(
+ `Invalid value for parameter "${key}": ${value}`
+ );
+ }
+ } else if (key === "server_max_window_bits") {
+ const num = +value;
+ if (!Number.isInteger(num) || num < 8 || num > 15) {
+ throw new TypeError(
+ `Invalid value for parameter "${key}": ${value}`
+ );
+ }
+ value = num;
+ } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
+ if (value !== true) {
+ throw new TypeError(
+ `Invalid value for parameter "${key}": ${value}`
+ );
+ }
+ } else {
+ throw new Error(`Unknown parameter "${key}"`);
+ }
+ params[key] = value;
+ });
+ });
+ return configurations;
+ }
+ /**
+ * Decompress data. Concurrency limited.
+ *
+ * @param {Buffer} data Compressed data
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
+ * @param {Function} callback Callback
+ * @public
+ */
+ decompress(data, fin, callback) {
+ zlibLimiter.add((done) => {
+ this._decompress(data, fin, (err, result) => {
+ done();
+ callback(err, result);
+ });
+ });
+ }
+ /**
+ * Compress data. Concurrency limited.
+ *
+ * @param {(Buffer|String)} data Data to compress
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
+ * @param {Function} callback Callback
+ * @public
+ */
+ compress(data, fin, callback) {
+ zlibLimiter.add((done) => {
+ this._compress(data, fin, (err, result) => {
+ done();
+ callback(err, result);
+ });
+ });
+ }
+ /**
+ * Decompress data.
+ *
+ * @param {Buffer} data Compressed data
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
+ * @param {Function} callback Callback
+ * @private
+ */
+ _decompress(data, fin, callback) {
+ const endpoint = this._isServer ? "client" : "server";
+ if (!this._inflate) {
+ const key = `${endpoint}_max_window_bits`;
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
+ this._inflate = zlib.createInflateRaw({
+ ...this._options.zlibInflateOptions,
+ windowBits
+ });
+ this._inflate[kPerMessageDeflate] = this;
+ this._inflate[kTotalLength] = 0;
+ this._inflate[kBuffers] = [];
+ this._inflate.on("error", inflateOnError);
+ this._inflate.on("data", inflateOnData);
+ }
+ this._inflate[kCallback] = callback;
+ this._inflate.write(data);
+ if (fin)
+ this._inflate.write(TRAILER);
+ this._inflate.flush(() => {
+ const err = this._inflate[kError];
+ if (err) {
+ this._inflate.close();
+ this._inflate = null;
+ callback(err);
+ return;
+ }
+ const data2 = bufferUtil.concat(
+ this._inflate[kBuffers],
+ this._inflate[kTotalLength]
+ );
+ if (this._inflate._readableState.endEmitted) {
+ this._inflate.close();
+ this._inflate = null;
+ } else {
+ this._inflate[kTotalLength] = 0;
+ this._inflate[kBuffers] = [];
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
+ this._inflate.reset();
+ }
+ }
+ callback(null, data2);
+ });
+ }
+ /**
+ * Compress data.
+ *
+ * @param {(Buffer|String)} data Data to compress
+ * @param {Boolean} fin Specifies whether or not this is the last fragment
+ * @param {Function} callback Callback
+ * @private
+ */
+ _compress(data, fin, callback) {
+ const endpoint = this._isServer ? "server" : "client";
+ if (!this._deflate) {
+ const key = `${endpoint}_max_window_bits`;
+ const windowBits = typeof this.params[key] !== "number" ? zlib.Z_DEFAULT_WINDOWBITS : this.params[key];
+ this._deflate = zlib.createDeflateRaw({
+ ...this._options.zlibDeflateOptions,
+ windowBits
+ });
+ this._deflate[kTotalLength] = 0;
+ this._deflate[kBuffers] = [];
+ this._deflate.on("data", deflateOnData);
+ }
+ this._deflate[kCallback] = callback;
+ this._deflate.write(data);
+ this._deflate.flush(zlib.Z_SYNC_FLUSH, () => {
+ if (!this._deflate) {
+ return;
+ }
+ let data2 = bufferUtil.concat(
+ this._deflate[kBuffers],
+ this._deflate[kTotalLength]
+ );
+ if (fin)
+ data2 = data2.slice(0, data2.length - 4);
+ this._deflate[kCallback] = null;
+ this._deflate[kTotalLength] = 0;
+ this._deflate[kBuffers] = [];
+ if (fin && this.params[`${endpoint}_no_context_takeover`]) {
+ this._deflate.reset();
+ }
+ callback(null, data2);
+ });
+ }
+ };
+ __name(PerMessageDeflate, "PerMessageDeflate");
+ module2.exports = PerMessageDeflate;
+ function deflateOnData(chunk) {
+ this[kBuffers].push(chunk);
+ this[kTotalLength] += chunk.length;
+ }
+ __name(deflateOnData, "deflateOnData");
+ function inflateOnData(chunk) {
+ this[kTotalLength] += chunk.length;
+ if (this[kPerMessageDeflate]._maxPayload < 1 || this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload) {
+ this[kBuffers].push(chunk);
+ return;
+ }
+ this[kError] = new RangeError("Max payload size exceeded");
+ this[kError].code = "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH";
+ this[kError][kStatusCode] = 1009;
+ this.removeListener("data", inflateOnData);
+ this.reset();
+ }
+ __name(inflateOnData, "inflateOnData");
+ function inflateOnError(err) {
+ this[kPerMessageDeflate]._inflate = null;
+ err[kStatusCode] = 1007;
+ this[kCallback](err);
+ }
+ __name(inflateOnError, "inflateOnError");
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/validation.js
+var require_validation2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/validation.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var tokenChars = [
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 0 - 15
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 16 - 31
+ 0,
+ 1,
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 1,
+ 1,
+ 0,
+ 1,
+ 1,
+ 0,
+ // 32 - 47
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ 0,
+ // 48 - 63
+ 0,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ // 64 - 79
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 0,
+ 0,
+ 1,
+ 1,
+ // 80 - 95
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ // 96 - 111
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 1,
+ 0,
+ 1,
+ 0,
+ 1,
+ 0
+ // 112 - 127
+ ];
+ function isValidStatusCode(code) {
+ return code >= 1e3 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006 || code >= 3e3 && code <= 4999;
+ }
+ __name(isValidStatusCode, "isValidStatusCode");
+ function _isValidUTF8(buf) {
+ const len = buf.length;
+ let i = 0;
+ while (i < len) {
+ if ((buf[i] & 128) === 0) {
+ i++;
+ } else if ((buf[i] & 224) === 192) {
+ if (i + 1 === len || (buf[i + 1] & 192) !== 128 || (buf[i] & 254) === 192) {
+ return false;
+ }
+ i += 2;
+ } else if ((buf[i] & 240) === 224) {
+ if (i + 2 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || buf[i] === 224 && (buf[i + 1] & 224) === 128 || // Overlong
+ buf[i] === 237 && (buf[i + 1] & 224) === 160) {
+ return false;
+ }
+ i += 3;
+ } else if ((buf[i] & 248) === 240) {
+ if (i + 3 >= len || (buf[i + 1] & 192) !== 128 || (buf[i + 2] & 192) !== 128 || (buf[i + 3] & 192) !== 128 || buf[i] === 240 && (buf[i + 1] & 240) === 128 || // Overlong
+ buf[i] === 244 && buf[i + 1] > 143 || buf[i] > 244) {
+ return false;
+ }
+ i += 4;
+ } else {
+ return false;
+ }
+ }
+ return true;
+ }
+ __name(_isValidUTF8, "_isValidUTF8");
+ module2.exports = {
+ isValidStatusCode,
+ isValidUTF8: _isValidUTF8,
+ tokenChars
+ };
+ if (!process.env.WS_NO_UTF_8_VALIDATE) {
+ try {
+ const isValidUTF8 = require("utf-8-validate");
+ module2.exports.isValidUTF8 = function(buf) {
+ return buf.length < 150 ? _isValidUTF8(buf) : isValidUTF8(buf);
+ };
+ } catch (e2) {
+ }
+ }
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/receiver.js
+var require_receiver3 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/receiver.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var { Writable } = require("stream");
+ var PerMessageDeflate = require_permessage_deflate2();
+ var {
+ BINARY_TYPES,
+ EMPTY_BUFFER,
+ kStatusCode,
+ kWebSocket
+ } = require_constants7();
+ var { concat, toArrayBuffer, unmask } = require_buffer_util2();
+ var { isValidStatusCode, isValidUTF8 } = require_validation2();
+ var GET_INFO = 0;
+ var GET_PAYLOAD_LENGTH_16 = 1;
+ var GET_PAYLOAD_LENGTH_64 = 2;
+ var GET_MASK = 3;
+ var GET_DATA = 4;
+ var INFLATING = 5;
+ var Receiver2 = class extends Writable {
+ /**
+ * Creates a Receiver instance.
+ *
+ * @param {Object} [options] Options object
+ * @param {String} [options.binaryType=nodebuffer] The type for binary data
+ * @param {Object} [options.extensions] An object containing the negotiated
+ * extensions
+ * @param {Boolean} [options.isServer=false] Specifies whether to operate in
+ * client or server mode
+ * @param {Number} [options.maxPayload=0] The maximum allowed message length
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
+ * not to skip UTF-8 validation for text and close messages
+ */
+ constructor(options14 = {}) {
+ super();
+ this._binaryType = options14.binaryType || BINARY_TYPES[0];
+ this._extensions = options14.extensions || {};
+ this._isServer = !!options14.isServer;
+ this._maxPayload = options14.maxPayload | 0;
+ this._skipUTF8Validation = !!options14.skipUTF8Validation;
+ this[kWebSocket] = void 0;
+ this._bufferedBytes = 0;
+ this._buffers = [];
+ this._compressed = false;
+ this._payloadLength = 0;
+ this._mask = void 0;
+ this._fragmented = 0;
+ this._masked = false;
+ this._fin = false;
+ this._opcode = 0;
+ this._totalPayloadLength = 0;
+ this._messageLength = 0;
+ this._fragments = [];
+ this._state = GET_INFO;
+ this._loop = false;
+ }
+ /**
+ * Implements `Writable.prototype._write()`.
+ *
+ * @param {Buffer} chunk The chunk of data to write
+ * @param {String} encoding The character encoding of `chunk`
+ * @param {Function} cb Callback
+ * @private
+ */
+ _write(chunk, encoding, cb) {
+ if (this._opcode === 8 && this._state == GET_INFO)
+ return cb();
+ this._bufferedBytes += chunk.length;
+ this._buffers.push(chunk);
+ this.startLoop(cb);
+ }
+ /**
+ * Consumes `n` bytes from the buffered data.
+ *
+ * @param {Number} n The number of bytes to consume
+ * @return {Buffer} The consumed bytes
+ * @private
+ */
+ consume(n) {
+ this._bufferedBytes -= n;
+ if (n === this._buffers[0].length)
+ return this._buffers.shift();
+ if (n < this._buffers[0].length) {
+ const buf = this._buffers[0];
+ this._buffers[0] = buf.slice(n);
+ return buf.slice(0, n);
+ }
+ const dst = Buffer.allocUnsafe(n);
+ do {
+ const buf = this._buffers[0];
+ const offset = dst.length - n;
+ if (n >= buf.length) {
+ dst.set(this._buffers.shift(), offset);
+ } else {
+ dst.set(new Uint8Array(buf.buffer, buf.byteOffset, n), offset);
+ this._buffers[0] = buf.slice(n);
+ }
+ n -= buf.length;
+ } while (n > 0);
+ return dst;
+ }
+ /**
+ * Starts the parsing loop.
+ *
+ * @param {Function} cb Callback
+ * @private
+ */
+ startLoop(cb) {
+ let err;
+ this._loop = true;
+ do {
+ switch (this._state) {
+ case GET_INFO:
+ err = this.getInfo();
+ break;
+ case GET_PAYLOAD_LENGTH_16:
+ err = this.getPayloadLength16();
+ break;
+ case GET_PAYLOAD_LENGTH_64:
+ err = this.getPayloadLength64();
+ break;
+ case GET_MASK:
+ this.getMask();
+ break;
+ case GET_DATA:
+ err = this.getData(cb);
+ break;
+ default:
+ this._loop = false;
+ return;
+ }
+ } while (this._loop);
+ cb(err);
+ }
+ /**
+ * Reads the first two bytes of a frame.
+ *
+ * @return {(RangeError|undefined)} A possible error
+ * @private
+ */
+ getInfo() {
+ if (this._bufferedBytes < 2) {
+ this._loop = false;
+ return;
+ }
+ const buf = this.consume(2);
+ if ((buf[0] & 48) !== 0) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "RSV2 and RSV3 must be clear",
+ true,
+ 1002,
+ "WS_ERR_UNEXPECTED_RSV_2_3"
+ );
+ }
+ const compressed = (buf[0] & 64) === 64;
+ if (compressed && !this._extensions[PerMessageDeflate.extensionName]) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "RSV1 must be clear",
+ true,
+ 1002,
+ "WS_ERR_UNEXPECTED_RSV_1"
+ );
+ }
+ this._fin = (buf[0] & 128) === 128;
+ this._opcode = buf[0] & 15;
+ this._payloadLength = buf[1] & 127;
+ if (this._opcode === 0) {
+ if (compressed) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "RSV1 must be clear",
+ true,
+ 1002,
+ "WS_ERR_UNEXPECTED_RSV_1"
+ );
+ }
+ if (!this._fragmented) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "invalid opcode 0",
+ true,
+ 1002,
+ "WS_ERR_INVALID_OPCODE"
+ );
+ }
+ this._opcode = this._fragmented;
+ } else if (this._opcode === 1 || this._opcode === 2) {
+ if (this._fragmented) {
+ this._loop = false;
+ return error(
+ RangeError,
+ `invalid opcode ${this._opcode}`,
+ true,
+ 1002,
+ "WS_ERR_INVALID_OPCODE"
+ );
+ }
+ this._compressed = compressed;
+ } else if (this._opcode > 7 && this._opcode < 11) {
+ if (!this._fin) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "FIN must be set",
+ true,
+ 1002,
+ "WS_ERR_EXPECTED_FIN"
+ );
+ }
+ if (compressed) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "RSV1 must be clear",
+ true,
+ 1002,
+ "WS_ERR_UNEXPECTED_RSV_1"
+ );
+ }
+ if (this._payloadLength > 125) {
+ this._loop = false;
+ return error(
+ RangeError,
+ `invalid payload length ${this._payloadLength}`,
+ true,
+ 1002,
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
+ );
+ }
+ } else {
+ this._loop = false;
+ return error(
+ RangeError,
+ `invalid opcode ${this._opcode}`,
+ true,
+ 1002,
+ "WS_ERR_INVALID_OPCODE"
+ );
+ }
+ if (!this._fin && !this._fragmented)
+ this._fragmented = this._opcode;
+ this._masked = (buf[1] & 128) === 128;
+ if (this._isServer) {
+ if (!this._masked) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "MASK must be set",
+ true,
+ 1002,
+ "WS_ERR_EXPECTED_MASK"
+ );
+ }
+ } else if (this._masked) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "MASK must be clear",
+ true,
+ 1002,
+ "WS_ERR_UNEXPECTED_MASK"
+ );
+ }
+ if (this._payloadLength === 126)
+ this._state = GET_PAYLOAD_LENGTH_16;
+ else if (this._payloadLength === 127)
+ this._state = GET_PAYLOAD_LENGTH_64;
+ else
+ return this.haveLength();
+ }
+ /**
+ * Gets extended payload length (7+16).
+ *
+ * @return {(RangeError|undefined)} A possible error
+ * @private
+ */
+ getPayloadLength16() {
+ if (this._bufferedBytes < 2) {
+ this._loop = false;
+ return;
+ }
+ this._payloadLength = this.consume(2).readUInt16BE(0);
+ return this.haveLength();
+ }
+ /**
+ * Gets extended payload length (7+64).
+ *
+ * @return {(RangeError|undefined)} A possible error
+ * @private
+ */
+ getPayloadLength64() {
+ if (this._bufferedBytes < 8) {
+ this._loop = false;
+ return;
+ }
+ const buf = this.consume(8);
+ const num = buf.readUInt32BE(0);
+ if (num > Math.pow(2, 53 - 32) - 1) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "Unsupported WebSocket frame: payload length > 2^53 - 1",
+ false,
+ 1009,
+ "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"
+ );
+ }
+ this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
+ return this.haveLength();
+ }
+ /**
+ * Payload length has been read.
+ *
+ * @return {(RangeError|undefined)} A possible error
+ * @private
+ */
+ haveLength() {
+ if (this._payloadLength && this._opcode < 8) {
+ this._totalPayloadLength += this._payloadLength;
+ if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) {
+ this._loop = false;
+ return error(
+ RangeError,
+ "Max payload size exceeded",
+ false,
+ 1009,
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
+ );
+ }
+ }
+ if (this._masked)
+ this._state = GET_MASK;
+ else
+ this._state = GET_DATA;
+ }
+ /**
+ * Reads mask bytes.
+ *
+ * @private
+ */
+ getMask() {
+ if (this._bufferedBytes < 4) {
+ this._loop = false;
+ return;
+ }
+ this._mask = this.consume(4);
+ this._state = GET_DATA;
+ }
+ /**
+ * Reads data bytes.
+ *
+ * @param {Function} cb Callback
+ * @return {(Error|RangeError|undefined)} A possible error
+ * @private
+ */
+ getData(cb) {
+ let data = EMPTY_BUFFER;
+ if (this._payloadLength) {
+ if (this._bufferedBytes < this._payloadLength) {
+ this._loop = false;
+ return;
+ }
+ data = this.consume(this._payloadLength);
+ if (this._masked && (this._mask[0] | this._mask[1] | this._mask[2] | this._mask[3]) !== 0) {
+ unmask(data, this._mask);
+ }
+ }
+ if (this._opcode > 7)
+ return this.controlMessage(data);
+ if (this._compressed) {
+ this._state = INFLATING;
+ this.decompress(data, cb);
+ return;
+ }
+ if (data.length) {
+ this._messageLength = this._totalPayloadLength;
+ this._fragments.push(data);
+ }
+ return this.dataMessage();
+ }
+ /**
+ * Decompresses data.
+ *
+ * @param {Buffer} data Compressed data
+ * @param {Function} cb Callback
+ * @private
+ */
+ decompress(data, cb) {
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
+ perMessageDeflate.decompress(data, this._fin, (err, buf) => {
+ if (err)
+ return cb(err);
+ if (buf.length) {
+ this._messageLength += buf.length;
+ if (this._messageLength > this._maxPayload && this._maxPayload > 0) {
+ return cb(
+ error(
+ RangeError,
+ "Max payload size exceeded",
+ false,
+ 1009,
+ "WS_ERR_UNSUPPORTED_MESSAGE_LENGTH"
+ )
+ );
+ }
+ this._fragments.push(buf);
+ }
+ const er = this.dataMessage();
+ if (er)
+ return cb(er);
+ this.startLoop(cb);
+ });
+ }
+ /**
+ * Handles a data message.
+ *
+ * @return {(Error|undefined)} A possible error
+ * @private
+ */
+ dataMessage() {
+ if (this._fin) {
+ const messageLength = this._messageLength;
+ const fragments = this._fragments;
+ this._totalPayloadLength = 0;
+ this._messageLength = 0;
+ this._fragmented = 0;
+ this._fragments = [];
+ if (this._opcode === 2) {
+ let data;
+ if (this._binaryType === "nodebuffer") {
+ data = concat(fragments, messageLength);
+ } else if (this._binaryType === "arraybuffer") {
+ data = toArrayBuffer(concat(fragments, messageLength));
+ } else {
+ data = fragments;
+ }
+ this.emit("message", data, true);
+ } else {
+ const buf = concat(fragments, messageLength);
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
+ this._loop = false;
+ return error(
+ Error,
+ "invalid UTF-8 sequence",
+ true,
+ 1007,
+ "WS_ERR_INVALID_UTF8"
+ );
+ }
+ this.emit("message", buf, false);
+ }
+ }
+ this._state = GET_INFO;
+ }
+ /**
+ * Handles a control message.
+ *
+ * @param {Buffer} data Data to handle
+ * @return {(Error|RangeError|undefined)} A possible error
+ * @private
+ */
+ controlMessage(data) {
+ if (this._opcode === 8) {
+ this._loop = false;
+ if (data.length === 0) {
+ this.emit("conclude", 1005, EMPTY_BUFFER);
+ this.end();
+ } else if (data.length === 1) {
+ return error(
+ RangeError,
+ "invalid payload length 1",
+ true,
+ 1002,
+ "WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH"
+ );
+ } else {
+ const code = data.readUInt16BE(0);
+ if (!isValidStatusCode(code)) {
+ return error(
+ RangeError,
+ `invalid status code ${code}`,
+ true,
+ 1002,
+ "WS_ERR_INVALID_CLOSE_CODE"
+ );
+ }
+ const buf = data.slice(2);
+ if (!this._skipUTF8Validation && !isValidUTF8(buf)) {
+ return error(
+ Error,
+ "invalid UTF-8 sequence",
+ true,
+ 1007,
+ "WS_ERR_INVALID_UTF8"
+ );
+ }
+ this.emit("conclude", code, buf);
+ this.end();
+ }
+ } else if (this._opcode === 9) {
+ this.emit("ping", data);
+ } else {
+ this.emit("pong", data);
+ }
+ this._state = GET_INFO;
+ }
+ };
+ __name(Receiver2, "Receiver");
+ module2.exports = Receiver2;
+ function error(ErrorCtor, message, prefix, statusCode, errorCode) {
+ const err = new ErrorCtor(
+ prefix ? `Invalid WebSocket frame: ${message}` : message
+ );
+ Error.captureStackTrace(err, error);
+ err.code = errorCode;
+ err[kStatusCode] = statusCode;
+ return err;
+ }
+ __name(error, "error");
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/sender.js
+var require_sender2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/sender.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var net3 = require("net");
+ var tls = require("tls");
+ var { randomFillSync } = require("crypto");
+ var PerMessageDeflate = require_permessage_deflate2();
+ var { EMPTY_BUFFER } = require_constants7();
+ var { isValidStatusCode } = require_validation2();
+ var { mask: applyMask, toBuffer } = require_buffer_util2();
+ var kByteLength = Symbol("kByteLength");
+ var maskBuffer = Buffer.alloc(4);
+ var Sender2 = class {
+ /**
+ * Creates a Sender instance.
+ *
+ * @param {(net.Socket|tls.Socket)} socket The connection socket
+ * @param {Object} [extensions] An object containing the negotiated extensions
+ * @param {Function} [generateMask] The function used to generate the masking
+ * key
+ */
+ constructor(socket, extensions, generateMask) {
+ this._extensions = extensions || {};
+ if (generateMask) {
+ this._generateMask = generateMask;
+ this._maskBuffer = Buffer.alloc(4);
+ }
+ this._socket = socket;
+ this._firstFragment = true;
+ this._compress = false;
+ this._bufferedBytes = 0;
+ this._deflating = false;
+ this._queue = [];
+ }
+ /**
+ * Frames a piece of data according to the HyBi WebSocket protocol.
+ *
+ * @param {(Buffer|String)} data The data to frame
+ * @param {Object} options Options object
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
+ * FIN bit
+ * @param {Function} [options.generateMask] The function used to generate the
+ * masking key
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
+ * `data`
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
+ * key
+ * @param {Number} options.opcode The opcode
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
+ * modified
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
+ * RSV1 bit
+ * @return {(Buffer|String)[]} The framed data
+ * @public
+ */
+ static frame(data, options14) {
+ let mask;
+ let merge = false;
+ let offset = 2;
+ let skipMasking = false;
+ if (options14.mask) {
+ mask = options14.maskBuffer || maskBuffer;
+ if (options14.generateMask) {
+ options14.generateMask(mask);
+ } else {
+ randomFillSync(mask, 0, 4);
+ }
+ skipMasking = (mask[0] | mask[1] | mask[2] | mask[3]) === 0;
+ offset = 6;
+ }
+ let dataLength;
+ if (typeof data === "string") {
+ if ((!options14.mask || skipMasking) && options14[kByteLength] !== void 0) {
+ dataLength = options14[kByteLength];
+ } else {
+ data = Buffer.from(data);
+ dataLength = data.length;
+ }
+ } else {
+ dataLength = data.length;
+ merge = options14.mask && options14.readOnly && !skipMasking;
+ }
+ let payloadLength = dataLength;
+ if (dataLength >= 65536) {
+ offset += 8;
+ payloadLength = 127;
+ } else if (dataLength > 125) {
+ offset += 2;
+ payloadLength = 126;
+ }
+ const target = Buffer.allocUnsafe(merge ? dataLength + offset : offset);
+ target[0] = options14.fin ? options14.opcode | 128 : options14.opcode;
+ if (options14.rsv1)
+ target[0] |= 64;
+ target[1] = payloadLength;
+ if (payloadLength === 126) {
+ target.writeUInt16BE(dataLength, 2);
+ } else if (payloadLength === 127) {
+ target[2] = target[3] = 0;
+ target.writeUIntBE(dataLength, 4, 6);
+ }
+ if (!options14.mask)
+ return [target, data];
+ target[1] |= 128;
+ target[offset - 4] = mask[0];
+ target[offset - 3] = mask[1];
+ target[offset - 2] = mask[2];
+ target[offset - 1] = mask[3];
+ if (skipMasking)
+ return [target, data];
+ if (merge) {
+ applyMask(data, mask, target, offset, dataLength);
+ return [target];
+ }
+ applyMask(data, mask, data, 0, dataLength);
+ return [target, data];
+ }
+ /**
+ * Sends a close message to the other peer.
+ *
+ * @param {Number} [code] The status code component of the body
+ * @param {(String|Buffer)} [data] The message component of the body
+ * @param {Boolean} [mask=false] Specifies whether or not to mask the message
+ * @param {Function} [cb] Callback
+ * @public
+ */
+ close(code, data, mask, cb) {
+ let buf;
+ if (code === void 0) {
+ buf = EMPTY_BUFFER;
+ } else if (typeof code !== "number" || !isValidStatusCode(code)) {
+ throw new TypeError("First argument must be a valid error code number");
+ } else if (data === void 0 || !data.length) {
+ buf = Buffer.allocUnsafe(2);
+ buf.writeUInt16BE(code, 0);
+ } else {
+ const length = Buffer.byteLength(data);
+ if (length > 123) {
+ throw new RangeError("The message must not be greater than 123 bytes");
+ }
+ buf = Buffer.allocUnsafe(2 + length);
+ buf.writeUInt16BE(code, 0);
+ if (typeof data === "string") {
+ buf.write(data, 2);
+ } else {
+ buf.set(data, 2);
+ }
+ }
+ const options14 = {
+ [kByteLength]: buf.length,
+ fin: true,
+ generateMask: this._generateMask,
+ mask,
+ maskBuffer: this._maskBuffer,
+ opcode: 8,
+ readOnly: false,
+ rsv1: false
+ };
+ if (this._deflating) {
+ this.enqueue([this.dispatch, buf, false, options14, cb]);
+ } else {
+ this.sendFrame(Sender2.frame(buf, options14), cb);
+ }
+ }
+ /**
+ * Sends a ping message to the other peer.
+ *
+ * @param {*} data The message to send
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
+ * @param {Function} [cb] Callback
+ * @public
+ */
+ ping(data, mask, cb) {
+ let byteLength;
+ let readOnly;
+ if (typeof data === "string") {
+ byteLength = Buffer.byteLength(data);
+ readOnly = false;
+ } else {
+ data = toBuffer(data);
+ byteLength = data.length;
+ readOnly = toBuffer.readOnly;
+ }
+ if (byteLength > 125) {
+ throw new RangeError("The data size must not be greater than 125 bytes");
+ }
+ const options14 = {
+ [kByteLength]: byteLength,
+ fin: true,
+ generateMask: this._generateMask,
+ mask,
+ maskBuffer: this._maskBuffer,
+ opcode: 9,
+ readOnly,
+ rsv1: false
+ };
+ if (this._deflating) {
+ this.enqueue([this.dispatch, data, false, options14, cb]);
+ } else {
+ this.sendFrame(Sender2.frame(data, options14), cb);
+ }
+ }
+ /**
+ * Sends a pong message to the other peer.
+ *
+ * @param {*} data The message to send
+ * @param {Boolean} [mask=false] Specifies whether or not to mask `data`
+ * @param {Function} [cb] Callback
+ * @public
+ */
+ pong(data, mask, cb) {
+ let byteLength;
+ let readOnly;
+ if (typeof data === "string") {
+ byteLength = Buffer.byteLength(data);
+ readOnly = false;
+ } else {
+ data = toBuffer(data);
+ byteLength = data.length;
+ readOnly = toBuffer.readOnly;
+ }
+ if (byteLength > 125) {
+ throw new RangeError("The data size must not be greater than 125 bytes");
+ }
+ const options14 = {
+ [kByteLength]: byteLength,
+ fin: true,
+ generateMask: this._generateMask,
+ mask,
+ maskBuffer: this._maskBuffer,
+ opcode: 10,
+ readOnly,
+ rsv1: false
+ };
+ if (this._deflating) {
+ this.enqueue([this.dispatch, data, false, options14, cb]);
+ } else {
+ this.sendFrame(Sender2.frame(data, options14), cb);
+ }
+ }
+ /**
+ * Sends a data message to the other peer.
+ *
+ * @param {*} data The message to send
+ * @param {Object} options Options object
+ * @param {Boolean} [options.binary=false] Specifies whether `data` is binary
+ * or text
+ * @param {Boolean} [options.compress=false] Specifies whether or not to
+ * compress `data`
+ * @param {Boolean} [options.fin=false] Specifies whether the fragment is the
+ * last one
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
+ * `data`
+ * @param {Function} [cb] Callback
+ * @public
+ */
+ send(data, options14, cb) {
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
+ let opcode = options14.binary ? 2 : 1;
+ let rsv1 = options14.compress;
+ let byteLength;
+ let readOnly;
+ if (typeof data === "string") {
+ byteLength = Buffer.byteLength(data);
+ readOnly = false;
+ } else {
+ data = toBuffer(data);
+ byteLength = data.length;
+ readOnly = toBuffer.readOnly;
+ }
+ if (this._firstFragment) {
+ this._firstFragment = false;
+ if (rsv1 && perMessageDeflate && perMessageDeflate.params[perMessageDeflate._isServer ? "server_no_context_takeover" : "client_no_context_takeover"]) {
+ rsv1 = byteLength >= perMessageDeflate._threshold;
+ }
+ this._compress = rsv1;
+ } else {
+ rsv1 = false;
+ opcode = 0;
+ }
+ if (options14.fin)
+ this._firstFragment = true;
+ if (perMessageDeflate) {
+ const opts = {
+ [kByteLength]: byteLength,
+ fin: options14.fin,
+ generateMask: this._generateMask,
+ mask: options14.mask,
+ maskBuffer: this._maskBuffer,
+ opcode,
+ readOnly,
+ rsv1
+ };
+ if (this._deflating) {
+ this.enqueue([this.dispatch, data, this._compress, opts, cb]);
+ } else {
+ this.dispatch(data, this._compress, opts, cb);
+ }
+ } else {
+ this.sendFrame(
+ Sender2.frame(data, {
+ [kByteLength]: byteLength,
+ fin: options14.fin,
+ generateMask: this._generateMask,
+ mask: options14.mask,
+ maskBuffer: this._maskBuffer,
+ opcode,
+ readOnly,
+ rsv1: false
+ }),
+ cb
+ );
+ }
+ }
+ /**
+ * Dispatches a message.
+ *
+ * @param {(Buffer|String)} data The message to send
+ * @param {Boolean} [compress=false] Specifies whether or not to compress
+ * `data`
+ * @param {Object} options Options object
+ * @param {Boolean} [options.fin=false] Specifies whether or not to set the
+ * FIN bit
+ * @param {Function} [options.generateMask] The function used to generate the
+ * masking key
+ * @param {Boolean} [options.mask=false] Specifies whether or not to mask
+ * `data`
+ * @param {Buffer} [options.maskBuffer] The buffer used to store the masking
+ * key
+ * @param {Number} options.opcode The opcode
+ * @param {Boolean} [options.readOnly=false] Specifies whether `data` can be
+ * modified
+ * @param {Boolean} [options.rsv1=false] Specifies whether or not to set the
+ * RSV1 bit
+ * @param {Function} [cb] Callback
+ * @private
+ */
+ dispatch(data, compress, options14, cb) {
+ if (!compress) {
+ this.sendFrame(Sender2.frame(data, options14), cb);
+ return;
+ }
+ const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName];
+ this._bufferedBytes += options14[kByteLength];
+ this._deflating = true;
+ perMessageDeflate.compress(data, options14.fin, (_2, buf) => {
+ if (this._socket.destroyed) {
+ const err = new Error(
+ "The socket was closed while data was being compressed"
+ );
+ if (typeof cb === "function")
+ cb(err);
+ for (let i = 0; i < this._queue.length; i++) {
+ const params = this._queue[i];
+ const callback = params[params.length - 1];
+ if (typeof callback === "function")
+ callback(err);
+ }
+ return;
+ }
+ this._bufferedBytes -= options14[kByteLength];
+ this._deflating = false;
+ options14.readOnly = false;
+ this.sendFrame(Sender2.frame(buf, options14), cb);
+ this.dequeue();
+ });
+ }
+ /**
+ * Executes queued send operations.
+ *
+ * @private
+ */
+ dequeue() {
+ while (!this._deflating && this._queue.length) {
+ const params = this._queue.shift();
+ this._bufferedBytes -= params[3][kByteLength];
+ Reflect.apply(params[0], this, params.slice(1));
+ }
+ }
+ /**
+ * Enqueues a send operation.
+ *
+ * @param {Array} params Send operation parameters.
+ * @private
+ */
+ enqueue(params) {
+ this._bufferedBytes += params[3][kByteLength];
+ this._queue.push(params);
+ }
+ /**
+ * Sends a frame.
+ *
+ * @param {Buffer[]} list The frame to send
+ * @param {Function} [cb] Callback
+ * @private
+ */
+ sendFrame(list, cb) {
+ if (list.length === 2) {
+ this._socket.cork();
+ this._socket.write(list[0]);
+ this._socket.write(list[1], cb);
+ this._socket.uncork();
+ } else {
+ this._socket.write(list[0], cb);
+ }
+ }
+ };
+ __name(Sender2, "Sender");
+ module2.exports = Sender2;
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/event-target.js
+var require_event_target2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/event-target.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var { kForOnEventAttribute, kListener } = require_constants7();
+ var kCode = Symbol("kCode");
+ var kData = Symbol("kData");
+ var kError = Symbol("kError");
+ var kMessage = Symbol("kMessage");
+ var kReason = Symbol("kReason");
+ var kTarget = Symbol("kTarget");
+ var kType = Symbol("kType");
+ var kWasClean = Symbol("kWasClean");
+ var Event2 = class {
+ /**
+ * Create a new `Event`.
+ *
+ * @param {String} type The name of the event
+ * @throws {TypeError} If the `type` argument is not specified
+ */
+ constructor(type) {
+ this[kTarget] = null;
+ this[kType] = type;
+ }
+ /**
+ * @type {*}
+ */
+ get target() {
+ return this[kTarget];
+ }
+ /**
+ * @type {String}
+ */
+ get type() {
+ return this[kType];
+ }
+ };
+ __name(Event2, "Event");
+ Object.defineProperty(Event2.prototype, "target", { enumerable: true });
+ Object.defineProperty(Event2.prototype, "type", { enumerable: true });
+ var CloseEvent = class extends Event2 {
+ /**
+ * Create a new `CloseEvent`.
+ *
+ * @param {String} type The name of the event
+ * @param {Object} [options] A dictionary object that allows for setting
+ * attributes via object members of the same name
+ * @param {Number} [options.code=0] The status code explaining why the
+ * connection was closed
+ * @param {String} [options.reason=''] A human-readable string explaining why
+ * the connection was closed
+ * @param {Boolean} [options.wasClean=false] Indicates whether or not the
+ * connection was cleanly closed
+ */
+ constructor(type, options14 = {}) {
+ super(type);
+ this[kCode] = options14.code === void 0 ? 0 : options14.code;
+ this[kReason] = options14.reason === void 0 ? "" : options14.reason;
+ this[kWasClean] = options14.wasClean === void 0 ? false : options14.wasClean;
+ }
+ /**
+ * @type {Number}
+ */
+ get code() {
+ return this[kCode];
+ }
+ /**
+ * @type {String}
+ */
+ get reason() {
+ return this[kReason];
+ }
+ /**
+ * @type {Boolean}
+ */
+ get wasClean() {
+ return this[kWasClean];
+ }
+ };
+ __name(CloseEvent, "CloseEvent");
+ Object.defineProperty(CloseEvent.prototype, "code", { enumerable: true });
+ Object.defineProperty(CloseEvent.prototype, "reason", { enumerable: true });
+ Object.defineProperty(CloseEvent.prototype, "wasClean", { enumerable: true });
+ var ErrorEvent2 = class extends Event2 {
+ /**
+ * Create a new `ErrorEvent`.
+ *
+ * @param {String} type The name of the event
+ * @param {Object} [options] A dictionary object that allows for setting
+ * attributes via object members of the same name
+ * @param {*} [options.error=null] The error that generated this event
+ * @param {String} [options.message=''] The error message
+ */
+ constructor(type, options14 = {}) {
+ super(type);
+ this[kError] = options14.error === void 0 ? null : options14.error;
+ this[kMessage] = options14.message === void 0 ? "" : options14.message;
+ }
+ /**
+ * @type {*}
+ */
+ get error() {
+ return this[kError];
+ }
+ /**
+ * @type {String}
+ */
+ get message() {
+ return this[kMessage];
+ }
+ };
+ __name(ErrorEvent2, "ErrorEvent");
+ Object.defineProperty(ErrorEvent2.prototype, "error", { enumerable: true });
+ Object.defineProperty(ErrorEvent2.prototype, "message", { enumerable: true });
+ var MessageEvent = class extends Event2 {
+ /**
+ * Create a new `MessageEvent`.
+ *
+ * @param {String} type The name of the event
+ * @param {Object} [options] A dictionary object that allows for setting
+ * attributes via object members of the same name
+ * @param {*} [options.data=null] The message content
+ */
+ constructor(type, options14 = {}) {
+ super(type);
+ this[kData] = options14.data === void 0 ? null : options14.data;
+ }
+ /**
+ * @type {*}
+ */
+ get data() {
+ return this[kData];
+ }
+ };
+ __name(MessageEvent, "MessageEvent");
+ Object.defineProperty(MessageEvent.prototype, "data", { enumerable: true });
+ var EventTarget2 = {
+ /**
+ * Register an event listener.
+ *
+ * @param {String} type A string representing the event type to listen for
+ * @param {(Function|Object)} handler The listener to add
+ * @param {Object} [options] An options object specifies characteristics about
+ * the event listener
+ * @param {Boolean} [options.once=false] A `Boolean` indicating that the
+ * listener should be invoked at most once after being added. If `true`,
+ * the listener would be automatically removed when invoked.
+ * @public
+ */
+ addEventListener(type, handler15, options14 = {}) {
+ for (const listener of this.listeners(type)) {
+ if (!options14[kForOnEventAttribute] && listener[kListener] === handler15 && !listener[kForOnEventAttribute]) {
+ return;
+ }
+ }
+ let wrapper;
+ if (type === "message") {
+ wrapper = /* @__PURE__ */ __name(function onMessage(data, isBinary) {
+ const event = new MessageEvent("message", {
+ data: isBinary ? data : data.toString()
+ });
+ event[kTarget] = this;
+ callListener(handler15, this, event);
+ }, "onMessage");
+ } else if (type === "close") {
+ wrapper = /* @__PURE__ */ __name(function onClose(code, message) {
+ const event = new CloseEvent("close", {
+ code,
+ reason: message.toString(),
+ wasClean: this._closeFrameReceived && this._closeFrameSent
+ });
+ event[kTarget] = this;
+ callListener(handler15, this, event);
+ }, "onClose");
+ } else if (type === "error") {
+ wrapper = /* @__PURE__ */ __name(function onError(error) {
+ const event = new ErrorEvent2("error", {
+ error,
+ message: error.message
+ });
+ event[kTarget] = this;
+ callListener(handler15, this, event);
+ }, "onError");
+ } else if (type === "open") {
+ wrapper = /* @__PURE__ */ __name(function onOpen() {
+ const event = new Event2("open");
+ event[kTarget] = this;
+ callListener(handler15, this, event);
+ }, "onOpen");
+ } else {
+ return;
+ }
+ wrapper[kForOnEventAttribute] = !!options14[kForOnEventAttribute];
+ wrapper[kListener] = handler15;
+ if (options14.once) {
+ this.once(type, wrapper);
+ } else {
+ this.on(type, wrapper);
+ }
+ },
+ /**
+ * Remove an event listener.
+ *
+ * @param {String} type A string representing the event type to remove
+ * @param {(Function|Object)} handler The listener to remove
+ * @public
+ */
+ removeEventListener(type, handler15) {
+ for (const listener of this.listeners(type)) {
+ if (listener[kListener] === handler15 && !listener[kForOnEventAttribute]) {
+ this.removeListener(type, listener);
+ break;
+ }
+ }
+ }
+ };
+ module2.exports = {
+ CloseEvent,
+ ErrorEvent: ErrorEvent2,
+ Event: Event2,
+ EventTarget: EventTarget2,
+ MessageEvent
+ };
+ function callListener(listener, thisArg, event) {
+ if (typeof listener === "object" && listener.handleEvent) {
+ listener.handleEvent.call(listener, event);
+ } else {
+ listener.call(thisArg, event);
+ }
+ }
+ __name(callListener, "callListener");
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/extension.js
+var require_extension2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/extension.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var { tokenChars } = require_validation2();
+ function push(dest, name, elem) {
+ if (dest[name] === void 0)
+ dest[name] = [elem];
+ else
+ dest[name].push(elem);
+ }
+ __name(push, "push");
+ function parse4(header) {
+ const offers = /* @__PURE__ */ Object.create(null);
+ let params = /* @__PURE__ */ Object.create(null);
+ let mustUnescape = false;
+ let isEscaping = false;
+ let inQuotes = false;
+ let extensionName;
+ let paramName;
+ let start = -1;
+ let code = -1;
+ let end = -1;
+ let i = 0;
+ for (; i < header.length; i++) {
+ code = header.charCodeAt(i);
+ if (extensionName === void 0) {
+ if (end === -1 && tokenChars[code] === 1) {
+ if (start === -1)
+ start = i;
+ } else if (i !== 0 && (code === 32 || code === 9)) {
+ if (end === -1 && start !== -1)
+ end = i;
+ } else if (code === 59 || code === 44) {
+ if (start === -1) {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ if (end === -1)
+ end = i;
+ const name = header.slice(start, end);
+ if (code === 44) {
+ push(offers, name, params);
+ params = /* @__PURE__ */ Object.create(null);
+ } else {
+ extensionName = name;
+ }
+ start = end = -1;
+ } else {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ } else if (paramName === void 0) {
+ if (end === -1 && tokenChars[code] === 1) {
+ if (start === -1)
+ start = i;
+ } else if (code === 32 || code === 9) {
+ if (end === -1 && start !== -1)
+ end = i;
+ } else if (code === 59 || code === 44) {
+ if (start === -1) {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ if (end === -1)
+ end = i;
+ push(params, header.slice(start, end), true);
+ if (code === 44) {
+ push(offers, extensionName, params);
+ params = /* @__PURE__ */ Object.create(null);
+ extensionName = void 0;
+ }
+ start = end = -1;
+ } else if (code === 61 && start !== -1 && end === -1) {
+ paramName = header.slice(start, i);
+ start = end = -1;
+ } else {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ } else {
+ if (isEscaping) {
+ if (tokenChars[code] !== 1) {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ if (start === -1)
+ start = i;
+ else if (!mustUnescape)
+ mustUnescape = true;
+ isEscaping = false;
+ } else if (inQuotes) {
+ if (tokenChars[code] === 1) {
+ if (start === -1)
+ start = i;
+ } else if (code === 34 && start !== -1) {
+ inQuotes = false;
+ end = i;
+ } else if (code === 92) {
+ isEscaping = true;
+ } else {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ } else if (code === 34 && header.charCodeAt(i - 1) === 61) {
+ inQuotes = true;
+ } else if (end === -1 && tokenChars[code] === 1) {
+ if (start === -1)
+ start = i;
+ } else if (start !== -1 && (code === 32 || code === 9)) {
+ if (end === -1)
+ end = i;
+ } else if (code === 59 || code === 44) {
+ if (start === -1) {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ if (end === -1)
+ end = i;
+ let value = header.slice(start, end);
+ if (mustUnescape) {
+ value = value.replace(/\\/g, "");
+ mustUnescape = false;
+ }
+ push(params, paramName, value);
+ if (code === 44) {
+ push(offers, extensionName, params);
+ params = /* @__PURE__ */ Object.create(null);
+ extensionName = void 0;
+ }
+ paramName = void 0;
+ start = end = -1;
+ } else {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ }
+ }
+ if (start === -1 || inQuotes || code === 32 || code === 9) {
+ throw new SyntaxError("Unexpected end of input");
+ }
+ if (end === -1)
+ end = i;
+ const token = header.slice(start, end);
+ if (extensionName === void 0) {
+ push(offers, token, params);
+ } else {
+ if (paramName === void 0) {
+ push(params, token, true);
+ } else if (mustUnescape) {
+ push(params, paramName, token.replace(/\\/g, ""));
+ } else {
+ push(params, paramName, token);
+ }
+ push(offers, extensionName, params);
+ }
+ return offers;
+ }
+ __name(parse4, "parse");
+ function format8(extensions) {
+ return Object.keys(extensions).map((extension) => {
+ let configurations = extensions[extension];
+ if (!Array.isArray(configurations))
+ configurations = [configurations];
+ return configurations.map((params) => {
+ return [extension].concat(
+ Object.keys(params).map((k) => {
+ let values = params[k];
+ if (!Array.isArray(values))
+ values = [values];
+ return values.map((v) => v === true ? k : `${k}=${v}`).join("; ");
+ })
+ ).join("; ");
+ }).join(", ");
+ }).join(", ");
+ }
+ __name(format8, "format");
+ module2.exports = { format: format8, parse: parse4 };
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/websocket.js
+var require_websocket3 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/websocket.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var EventEmitter3 = require("events");
+ var https2 = require("https");
+ var http3 = require("http");
+ var net3 = require("net");
+ var tls = require("tls");
+ var { randomBytes, createHash } = require("crypto");
+ var { Readable } = require("stream");
+ var { URL: URL4 } = require("url");
+ var PerMessageDeflate = require_permessage_deflate2();
+ var Receiver2 = require_receiver3();
+ var Sender2 = require_sender2();
+ var {
+ BINARY_TYPES,
+ EMPTY_BUFFER,
+ GUID,
+ kForOnEventAttribute,
+ kListener,
+ kStatusCode,
+ kWebSocket,
+ NOOP
+ } = require_constants7();
+ var {
+ EventTarget: { addEventListener, removeEventListener }
+ } = require_event_target2();
+ var { format: format8, parse: parse4 } = require_extension2();
+ var { toBuffer } = require_buffer_util2();
+ var closeTimeout = 30 * 1e3;
+ var kAborted = Symbol("kAborted");
+ var protocolVersions = [8, 13];
+ var readyStates = ["CONNECTING", "OPEN", "CLOSING", "CLOSED"];
+ var subprotocolRegex = /^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;
+ var WebSocket2 = class extends EventEmitter3 {
+ /**
+ * Create a new `WebSocket`.
+ *
+ * @param {(String|URL)} address The URL to which to connect
+ * @param {(String|String[])} [protocols] The subprotocols
+ * @param {Object} [options] Connection options
+ */
+ constructor(address, protocols, options14) {
+ super();
+ this._binaryType = BINARY_TYPES[0];
+ this._closeCode = 1006;
+ this._closeFrameReceived = false;
+ this._closeFrameSent = false;
+ this._closeMessage = EMPTY_BUFFER;
+ this._closeTimer = null;
+ this._extensions = {};
+ this._paused = false;
+ this._protocol = "";
+ this._readyState = WebSocket2.CONNECTING;
+ this._receiver = null;
+ this._sender = null;
+ this._socket = null;
+ if (address !== null) {
+ this._bufferedAmount = 0;
+ this._isServer = false;
+ this._redirects = 0;
+ if (protocols === void 0) {
+ protocols = [];
+ } else if (!Array.isArray(protocols)) {
+ if (typeof protocols === "object" && protocols !== null) {
+ options14 = protocols;
+ protocols = [];
+ } else {
+ protocols = [protocols];
+ }
+ }
+ initAsClient(this, address, protocols, options14);
+ } else {
+ this._isServer = true;
+ }
+ }
+ /**
+ * This deviates from the WHATWG interface since ws doesn't support the
+ * required default "blob" type (instead we define a custom "nodebuffer"
+ * type).
+ *
+ * @type {String}
+ */
+ get binaryType() {
+ return this._binaryType;
+ }
+ set binaryType(type) {
+ if (!BINARY_TYPES.includes(type))
+ return;
+ this._binaryType = type;
+ if (this._receiver)
+ this._receiver._binaryType = type;
+ }
+ /**
+ * @type {Number}
+ */
+ get bufferedAmount() {
+ if (!this._socket)
+ return this._bufferedAmount;
+ return this._socket._writableState.length + this._sender._bufferedBytes;
+ }
+ /**
+ * @type {String}
+ */
+ get extensions() {
+ return Object.keys(this._extensions).join();
+ }
+ /**
+ * @type {Boolean}
+ */
+ get isPaused() {
+ return this._paused;
+ }
+ /**
+ * @type {Function}
+ */
+ /* istanbul ignore next */
+ get onclose() {
+ return null;
+ }
+ /**
+ * @type {Function}
+ */
+ /* istanbul ignore next */
+ get onerror() {
+ return null;
+ }
+ /**
+ * @type {Function}
+ */
+ /* istanbul ignore next */
+ get onopen() {
+ return null;
+ }
+ /**
+ * @type {Function}
+ */
+ /* istanbul ignore next */
+ get onmessage() {
+ return null;
+ }
+ /**
+ * @type {String}
+ */
+ get protocol() {
+ return this._protocol;
+ }
+ /**
+ * @type {Number}
+ */
+ get readyState() {
+ return this._readyState;
+ }
+ /**
+ * @type {String}
+ */
+ get url() {
+ return this._url;
+ }
+ /**
+ * Set up the socket and the internal resources.
+ *
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
+ * server and client
+ * @param {Buffer} head The first packet of the upgraded stream
+ * @param {Object} options Options object
+ * @param {Function} [options.generateMask] The function used to generate the
+ * masking key
+ * @param {Number} [options.maxPayload=0] The maximum allowed message size
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
+ * not to skip UTF-8 validation for text and close messages
+ * @private
+ */
+ setSocket(socket, head, options14) {
+ const receiver = new Receiver2({
+ binaryType: this.binaryType,
+ extensions: this._extensions,
+ isServer: this._isServer,
+ maxPayload: options14.maxPayload,
+ skipUTF8Validation: options14.skipUTF8Validation
+ });
+ this._sender = new Sender2(socket, this._extensions, options14.generateMask);
+ this._receiver = receiver;
+ this._socket = socket;
+ receiver[kWebSocket] = this;
+ socket[kWebSocket] = this;
+ receiver.on("conclude", receiverOnConclude);
+ receiver.on("drain", receiverOnDrain);
+ receiver.on("error", receiverOnError);
+ receiver.on("message", receiverOnMessage);
+ receiver.on("ping", receiverOnPing);
+ receiver.on("pong", receiverOnPong);
+ socket.setTimeout(0);
+ socket.setNoDelay();
+ if (head.length > 0)
+ socket.unshift(head);
+ socket.on("close", socketOnClose);
+ socket.on("data", socketOnData);
+ socket.on("end", socketOnEnd);
+ socket.on("error", socketOnError);
+ this._readyState = WebSocket2.OPEN;
+ this.emit("open");
+ }
+ /**
+ * Emit the `'close'` event.
+ *
+ * @private
+ */
+ emitClose() {
+ if (!this._socket) {
+ this._readyState = WebSocket2.CLOSED;
+ this.emit("close", this._closeCode, this._closeMessage);
+ return;
+ }
+ if (this._extensions[PerMessageDeflate.extensionName]) {
+ this._extensions[PerMessageDeflate.extensionName].cleanup();
+ }
+ this._receiver.removeAllListeners();
+ this._readyState = WebSocket2.CLOSED;
+ this.emit("close", this._closeCode, this._closeMessage);
+ }
+ /**
+ * Start a closing handshake.
+ *
+ * +----------+ +-----------+ +----------+
+ * - - -|ws.close()|-->|close frame|-->|ws.close()|- - -
+ * | +----------+ +-----------+ +----------+ |
+ * +----------+ +-----------+ |
+ * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING
+ * +----------+ +-----------+ |
+ * | | | +---+ |
+ * +------------------------+-->|fin| - - - -
+ * | +---+ | +---+
+ * - - - - -|fin|<---------------------+
+ * +---+
+ *
+ * @param {Number} [code] Status code explaining why the connection is closing
+ * @param {(String|Buffer)} [data] The reason why the connection is
+ * closing
+ * @public
+ */
+ close(code, data) {
+ if (this.readyState === WebSocket2.CLOSED)
+ return;
+ if (this.readyState === WebSocket2.CONNECTING) {
+ const msg = "WebSocket was closed before the connection was established";
+ return abortHandshake(this, this._req, msg);
+ }
+ if (this.readyState === WebSocket2.CLOSING) {
+ if (this._closeFrameSent && (this._closeFrameReceived || this._receiver._writableState.errorEmitted)) {
+ this._socket.end();
+ }
+ return;
+ }
+ this._readyState = WebSocket2.CLOSING;
+ this._sender.close(code, data, !this._isServer, (err) => {
+ if (err)
+ return;
+ this._closeFrameSent = true;
+ if (this._closeFrameReceived || this._receiver._writableState.errorEmitted) {
+ this._socket.end();
+ }
+ });
+ this._closeTimer = setTimeout(
+ this._socket.destroy.bind(this._socket),
+ closeTimeout
+ );
+ }
+ /**
+ * Pause the socket.
+ *
+ * @public
+ */
+ pause() {
+ if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) {
+ return;
+ }
+ this._paused = true;
+ this._socket.pause();
+ }
+ /**
+ * Send a ping.
+ *
+ * @param {*} [data] The data to send
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
+ * @param {Function} [cb] Callback which is executed when the ping is sent
+ * @public
+ */
+ ping(data, mask, cb) {
+ if (this.readyState === WebSocket2.CONNECTING) {
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
+ }
+ if (typeof data === "function") {
+ cb = data;
+ data = mask = void 0;
+ } else if (typeof mask === "function") {
+ cb = mask;
+ mask = void 0;
+ }
+ if (typeof data === "number")
+ data = data.toString();
+ if (this.readyState !== WebSocket2.OPEN) {
+ sendAfterClose(this, data, cb);
+ return;
+ }
+ if (mask === void 0)
+ mask = !this._isServer;
+ this._sender.ping(data || EMPTY_BUFFER, mask, cb);
+ }
+ /**
+ * Send a pong.
+ *
+ * @param {*} [data] The data to send
+ * @param {Boolean} [mask] Indicates whether or not to mask `data`
+ * @param {Function} [cb] Callback which is executed when the pong is sent
+ * @public
+ */
+ pong(data, mask, cb) {
+ if (this.readyState === WebSocket2.CONNECTING) {
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
+ }
+ if (typeof data === "function") {
+ cb = data;
+ data = mask = void 0;
+ } else if (typeof mask === "function") {
+ cb = mask;
+ mask = void 0;
+ }
+ if (typeof data === "number")
+ data = data.toString();
+ if (this.readyState !== WebSocket2.OPEN) {
+ sendAfterClose(this, data, cb);
+ return;
+ }
+ if (mask === void 0)
+ mask = !this._isServer;
+ this._sender.pong(data || EMPTY_BUFFER, mask, cb);
+ }
+ /**
+ * Resume the socket.
+ *
+ * @public
+ */
+ resume() {
+ if (this.readyState === WebSocket2.CONNECTING || this.readyState === WebSocket2.CLOSED) {
+ return;
+ }
+ this._paused = false;
+ if (!this._receiver._writableState.needDrain)
+ this._socket.resume();
+ }
+ /**
+ * Send a data message.
+ *
+ * @param {*} data The message to send
+ * @param {Object} [options] Options object
+ * @param {Boolean} [options.binary] Specifies whether `data` is binary or
+ * text
+ * @param {Boolean} [options.compress] Specifies whether or not to compress
+ * `data`
+ * @param {Boolean} [options.fin=true] Specifies whether the fragment is the
+ * last one
+ * @param {Boolean} [options.mask] Specifies whether or not to mask `data`
+ * @param {Function} [cb] Callback which is executed when data is written out
+ * @public
+ */
+ send(data, options14, cb) {
+ if (this.readyState === WebSocket2.CONNECTING) {
+ throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");
+ }
+ if (typeof options14 === "function") {
+ cb = options14;
+ options14 = {};
+ }
+ if (typeof data === "number")
+ data = data.toString();
+ if (this.readyState !== WebSocket2.OPEN) {
+ sendAfterClose(this, data, cb);
+ return;
+ }
+ const opts = {
+ binary: typeof data !== "string",
+ mask: !this._isServer,
+ compress: true,
+ fin: true,
+ ...options14
+ };
+ if (!this._extensions[PerMessageDeflate.extensionName]) {
+ opts.compress = false;
+ }
+ this._sender.send(data || EMPTY_BUFFER, opts, cb);
+ }
+ /**
+ * Forcibly close the connection.
+ *
+ * @public
+ */
+ terminate() {
+ if (this.readyState === WebSocket2.CLOSED)
+ return;
+ if (this.readyState === WebSocket2.CONNECTING) {
+ const msg = "WebSocket was closed before the connection was established";
+ return abortHandshake(this, this._req, msg);
+ }
+ if (this._socket) {
+ this._readyState = WebSocket2.CLOSING;
+ this._socket.destroy();
+ }
+ }
+ };
+ __name(WebSocket2, "WebSocket");
+ Object.defineProperty(WebSocket2, "CONNECTING", {
+ enumerable: true,
+ value: readyStates.indexOf("CONNECTING")
+ });
+ Object.defineProperty(WebSocket2.prototype, "CONNECTING", {
+ enumerable: true,
+ value: readyStates.indexOf("CONNECTING")
+ });
+ Object.defineProperty(WebSocket2, "OPEN", {
+ enumerable: true,
+ value: readyStates.indexOf("OPEN")
+ });
+ Object.defineProperty(WebSocket2.prototype, "OPEN", {
+ enumerable: true,
+ value: readyStates.indexOf("OPEN")
+ });
+ Object.defineProperty(WebSocket2, "CLOSING", {
+ enumerable: true,
+ value: readyStates.indexOf("CLOSING")
+ });
+ Object.defineProperty(WebSocket2.prototype, "CLOSING", {
+ enumerable: true,
+ value: readyStates.indexOf("CLOSING")
+ });
+ Object.defineProperty(WebSocket2, "CLOSED", {
+ enumerable: true,
+ value: readyStates.indexOf("CLOSED")
+ });
+ Object.defineProperty(WebSocket2.prototype, "CLOSED", {
+ enumerable: true,
+ value: readyStates.indexOf("CLOSED")
+ });
+ [
+ "binaryType",
+ "bufferedAmount",
+ "extensions",
+ "isPaused",
+ "protocol",
+ "readyState",
+ "url"
+ ].forEach((property) => {
+ Object.defineProperty(WebSocket2.prototype, property, { enumerable: true });
+ });
+ ["open", "error", "close", "message"].forEach((method) => {
+ Object.defineProperty(WebSocket2.prototype, `on${method}`, {
+ enumerable: true,
+ get() {
+ for (const listener of this.listeners(method)) {
+ if (listener[kForOnEventAttribute])
+ return listener[kListener];
+ }
+ return null;
+ },
+ set(handler15) {
+ for (const listener of this.listeners(method)) {
+ if (listener[kForOnEventAttribute]) {
+ this.removeListener(method, listener);
+ break;
+ }
+ }
+ if (typeof handler15 !== "function")
+ return;
+ this.addEventListener(method, handler15, {
+ [kForOnEventAttribute]: true
+ });
+ }
+ });
+ });
+ WebSocket2.prototype.addEventListener = addEventListener;
+ WebSocket2.prototype.removeEventListener = removeEventListener;
+ module2.exports = WebSocket2;
+ function initAsClient(websocket, address, protocols, options14) {
+ const opts = {
+ protocolVersion: protocolVersions[1],
+ maxPayload: 100 * 1024 * 1024,
+ skipUTF8Validation: false,
+ perMessageDeflate: true,
+ followRedirects: false,
+ maxRedirects: 10,
+ ...options14,
+ createConnection: void 0,
+ socketPath: void 0,
+ hostname: void 0,
+ protocol: void 0,
+ timeout: void 0,
+ method: "GET",
+ host: void 0,
+ path: void 0,
+ port: void 0
+ };
+ if (!protocolVersions.includes(opts.protocolVersion)) {
+ throw new RangeError(
+ `Unsupported protocol version: ${opts.protocolVersion} (supported versions: ${protocolVersions.join(", ")})`
+ );
+ }
+ let parsedUrl;
+ if (address instanceof URL4) {
+ parsedUrl = address;
+ websocket._url = address.href;
+ } else {
+ try {
+ parsedUrl = new URL4(address);
+ } catch (e2) {
+ throw new SyntaxError(`Invalid URL: ${address}`);
+ }
+ websocket._url = address;
+ }
+ const isSecure = parsedUrl.protocol === "wss:";
+ const isIpcUrl = parsedUrl.protocol === "ws+unix:";
+ let invalidUrlMessage;
+ if (parsedUrl.protocol !== "ws:" && !isSecure && !isIpcUrl) {
+ invalidUrlMessage = `The URL's protocol must be one of "ws:", "wss:", or "ws+unix:"`;
+ } else if (isIpcUrl && !parsedUrl.pathname) {
+ invalidUrlMessage = "The URL's pathname is empty";
+ } else if (parsedUrl.hash) {
+ invalidUrlMessage = "The URL contains a fragment identifier";
+ }
+ if (invalidUrlMessage) {
+ const err = new SyntaxError(invalidUrlMessage);
+ if (websocket._redirects === 0) {
+ throw err;
+ } else {
+ emitErrorAndClose(websocket, err);
+ return;
+ }
+ }
+ const defaultPort = isSecure ? 443 : 80;
+ const key = randomBytes(16).toString("base64");
+ const request = isSecure ? https2.request : http3.request;
+ const protocolSet = /* @__PURE__ */ new Set();
+ let perMessageDeflate;
+ opts.createConnection = isSecure ? tlsConnect : netConnect;
+ opts.defaultPort = opts.defaultPort || defaultPort;
+ opts.port = parsedUrl.port || defaultPort;
+ opts.host = parsedUrl.hostname.startsWith("[") ? parsedUrl.hostname.slice(1, -1) : parsedUrl.hostname;
+ opts.headers = {
+ ...opts.headers,
+ "Sec-WebSocket-Version": opts.protocolVersion,
+ "Sec-WebSocket-Key": key,
+ Connection: "Upgrade",
+ Upgrade: "websocket"
+ };
+ opts.path = parsedUrl.pathname + parsedUrl.search;
+ opts.timeout = opts.handshakeTimeout;
+ if (opts.perMessageDeflate) {
+ perMessageDeflate = new PerMessageDeflate(
+ opts.perMessageDeflate !== true ? opts.perMessageDeflate : {},
+ false,
+ opts.maxPayload
+ );
+ opts.headers["Sec-WebSocket-Extensions"] = format8({
+ [PerMessageDeflate.extensionName]: perMessageDeflate.offer()
+ });
+ }
+ if (protocols.length) {
+ for (const protocol of protocols) {
+ if (typeof protocol !== "string" || !subprotocolRegex.test(protocol) || protocolSet.has(protocol)) {
+ throw new SyntaxError(
+ "An invalid or duplicated subprotocol was specified"
+ );
+ }
+ protocolSet.add(protocol);
+ }
+ opts.headers["Sec-WebSocket-Protocol"] = protocols.join(",");
+ }
+ if (opts.origin) {
+ if (opts.protocolVersion < 13) {
+ opts.headers["Sec-WebSocket-Origin"] = opts.origin;
+ } else {
+ opts.headers.Origin = opts.origin;
+ }
+ }
+ if (parsedUrl.username || parsedUrl.password) {
+ opts.auth = `${parsedUrl.username}:${parsedUrl.password}`;
+ }
+ if (isIpcUrl) {
+ const parts = opts.path.split(":");
+ opts.socketPath = parts[0];
+ opts.path = parts[1];
+ }
+ let req;
+ if (opts.followRedirects) {
+ if (websocket._redirects === 0) {
+ websocket._originalIpc = isIpcUrl;
+ websocket._originalSecure = isSecure;
+ websocket._originalHostOrSocketPath = isIpcUrl ? opts.socketPath : parsedUrl.host;
+ const headers = options14 && options14.headers;
+ options14 = { ...options14, headers: {} };
+ if (headers) {
+ for (const [key2, value] of Object.entries(headers)) {
+ options14.headers[key2.toLowerCase()] = value;
+ }
+ }
+ } else if (websocket.listenerCount("redirect") === 0) {
+ const isSameHost = isIpcUrl ? websocket._originalIpc ? opts.socketPath === websocket._originalHostOrSocketPath : false : websocket._originalIpc ? false : parsedUrl.host === websocket._originalHostOrSocketPath;
+ if (!isSameHost || websocket._originalSecure && !isSecure) {
+ delete opts.headers.authorization;
+ delete opts.headers.cookie;
+ if (!isSameHost)
+ delete opts.headers.host;
+ opts.auth = void 0;
+ }
+ }
+ if (opts.auth && !options14.headers.authorization) {
+ options14.headers.authorization = "Basic " + Buffer.from(opts.auth).toString("base64");
+ }
+ req = websocket._req = request(opts);
+ if (websocket._redirects) {
+ websocket.emit("redirect", websocket.url, req);
+ }
+ } else {
+ req = websocket._req = request(opts);
+ }
+ if (opts.timeout) {
+ req.on("timeout", () => {
+ abortHandshake(websocket, req, "Opening handshake has timed out");
+ });
+ }
+ req.on("error", (err) => {
+ if (req === null || req[kAborted])
+ return;
+ req = websocket._req = null;
+ emitErrorAndClose(websocket, err);
+ });
+ req.on("response", (res) => {
+ const location = res.headers.location;
+ const statusCode = res.statusCode;
+ if (location && opts.followRedirects && statusCode >= 300 && statusCode < 400) {
+ if (++websocket._redirects > opts.maxRedirects) {
+ abortHandshake(websocket, req, "Maximum redirects exceeded");
+ return;
+ }
+ req.abort();
+ let addr;
+ try {
+ addr = new URL4(location, address);
+ } catch (e2) {
+ const err = new SyntaxError(`Invalid URL: ${location}`);
+ emitErrorAndClose(websocket, err);
+ return;
+ }
+ initAsClient(websocket, addr, protocols, options14);
+ } else if (!websocket.emit("unexpected-response", req, res)) {
+ abortHandshake(
+ websocket,
+ req,
+ `Unexpected server response: ${res.statusCode}`
+ );
+ }
+ });
+ req.on("upgrade", (res, socket, head) => {
+ websocket.emit("upgrade", res);
+ if (websocket.readyState !== WebSocket2.CONNECTING)
+ return;
+ req = websocket._req = null;
+ if (res.headers.upgrade.toLowerCase() !== "websocket") {
+ abortHandshake(websocket, socket, "Invalid Upgrade header");
+ return;
+ }
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
+ if (res.headers["sec-websocket-accept"] !== digest) {
+ abortHandshake(websocket, socket, "Invalid Sec-WebSocket-Accept header");
+ return;
+ }
+ const serverProt = res.headers["sec-websocket-protocol"];
+ let protError;
+ if (serverProt !== void 0) {
+ if (!protocolSet.size) {
+ protError = "Server sent a subprotocol but none was requested";
+ } else if (!protocolSet.has(serverProt)) {
+ protError = "Server sent an invalid subprotocol";
+ }
+ } else if (protocolSet.size) {
+ protError = "Server sent no subprotocol";
+ }
+ if (protError) {
+ abortHandshake(websocket, socket, protError);
+ return;
+ }
+ if (serverProt)
+ websocket._protocol = serverProt;
+ const secWebSocketExtensions = res.headers["sec-websocket-extensions"];
+ if (secWebSocketExtensions !== void 0) {
+ if (!perMessageDeflate) {
+ const message = "Server sent a Sec-WebSocket-Extensions header but no extension was requested";
+ abortHandshake(websocket, socket, message);
+ return;
+ }
+ let extensions;
+ try {
+ extensions = parse4(secWebSocketExtensions);
+ } catch (err) {
+ const message = "Invalid Sec-WebSocket-Extensions header";
+ abortHandshake(websocket, socket, message);
+ return;
+ }
+ const extensionNames = Object.keys(extensions);
+ if (extensionNames.length !== 1 || extensionNames[0] !== PerMessageDeflate.extensionName) {
+ const message = "Server indicated an extension that was not requested";
+ abortHandshake(websocket, socket, message);
+ return;
+ }
+ try {
+ perMessageDeflate.accept(extensions[PerMessageDeflate.extensionName]);
+ } catch (err) {
+ const message = "Invalid Sec-WebSocket-Extensions header";
+ abortHandshake(websocket, socket, message);
+ return;
+ }
+ websocket._extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
+ }
+ websocket.setSocket(socket, head, {
+ generateMask: opts.generateMask,
+ maxPayload: opts.maxPayload,
+ skipUTF8Validation: opts.skipUTF8Validation
+ });
+ });
+ req.end();
+ }
+ __name(initAsClient, "initAsClient");
+ function emitErrorAndClose(websocket, err) {
+ websocket._readyState = WebSocket2.CLOSING;
+ websocket.emit("error", err);
+ websocket.emitClose();
+ }
+ __name(emitErrorAndClose, "emitErrorAndClose");
+ function netConnect(options14) {
+ options14.path = options14.socketPath;
+ return net3.connect(options14);
+ }
+ __name(netConnect, "netConnect");
+ function tlsConnect(options14) {
+ options14.path = void 0;
+ if (!options14.servername && options14.servername !== "") {
+ options14.servername = net3.isIP(options14.host) ? "" : options14.host;
+ }
+ return tls.connect(options14);
+ }
+ __name(tlsConnect, "tlsConnect");
+ function abortHandshake(websocket, stream2, message) {
+ websocket._readyState = WebSocket2.CLOSING;
+ const err = new Error(message);
+ Error.captureStackTrace(err, abortHandshake);
+ if (stream2.setHeader) {
+ stream2[kAborted] = true;
+ stream2.abort();
+ if (stream2.socket && !stream2.socket.destroyed) {
+ stream2.socket.destroy();
+ }
+ process.nextTick(emitErrorAndClose, websocket, err);
+ } else {
+ stream2.destroy(err);
+ stream2.once("error", websocket.emit.bind(websocket, "error"));
+ stream2.once("close", websocket.emitClose.bind(websocket));
+ }
+ }
+ __name(abortHandshake, "abortHandshake");
+ function sendAfterClose(websocket, data, cb) {
+ if (data) {
+ const length = toBuffer(data).length;
+ if (websocket._socket)
+ websocket._sender._bufferedBytes += length;
+ else
+ websocket._bufferedAmount += length;
+ }
+ if (cb) {
+ const err = new Error(
+ `WebSocket is not open: readyState ${websocket.readyState} (${readyStates[websocket.readyState]})`
+ );
+ cb(err);
+ }
+ }
+ __name(sendAfterClose, "sendAfterClose");
+ function receiverOnConclude(code, reason) {
+ const websocket = this[kWebSocket];
+ websocket._closeFrameReceived = true;
+ websocket._closeMessage = reason;
+ websocket._closeCode = code;
+ if (websocket._socket[kWebSocket] === void 0)
+ return;
+ websocket._socket.removeListener("data", socketOnData);
+ process.nextTick(resume, websocket._socket);
+ if (code === 1005)
+ websocket.close();
+ else
+ websocket.close(code, reason);
+ }
+ __name(receiverOnConclude, "receiverOnConclude");
+ function receiverOnDrain() {
+ const websocket = this[kWebSocket];
+ if (!websocket.isPaused)
+ websocket._socket.resume();
+ }
+ __name(receiverOnDrain, "receiverOnDrain");
+ function receiverOnError(err) {
+ const websocket = this[kWebSocket];
+ if (websocket._socket[kWebSocket] !== void 0) {
+ websocket._socket.removeListener("data", socketOnData);
+ process.nextTick(resume, websocket._socket);
+ websocket.close(err[kStatusCode]);
+ }
+ websocket.emit("error", err);
+ }
+ __name(receiverOnError, "receiverOnError");
+ function receiverOnFinish() {
+ this[kWebSocket].emitClose();
+ }
+ __name(receiverOnFinish, "receiverOnFinish");
+ function receiverOnMessage(data, isBinary) {
+ this[kWebSocket].emit("message", data, isBinary);
+ }
+ __name(receiverOnMessage, "receiverOnMessage");
+ function receiverOnPing(data) {
+ const websocket = this[kWebSocket];
+ websocket.pong(data, !websocket._isServer, NOOP);
+ websocket.emit("ping", data);
+ }
+ __name(receiverOnPing, "receiverOnPing");
+ function receiverOnPong(data) {
+ this[kWebSocket].emit("pong", data);
+ }
+ __name(receiverOnPong, "receiverOnPong");
+ function resume(stream2) {
+ stream2.resume();
+ }
+ __name(resume, "resume");
+ function socketOnClose() {
+ const websocket = this[kWebSocket];
+ this.removeListener("close", socketOnClose);
+ this.removeListener("data", socketOnData);
+ this.removeListener("end", socketOnEnd);
+ websocket._readyState = WebSocket2.CLOSING;
+ let chunk;
+ if (!this._readableState.endEmitted && !websocket._closeFrameReceived && !websocket._receiver._writableState.errorEmitted && (chunk = websocket._socket.read()) !== null) {
+ websocket._receiver.write(chunk);
+ }
+ websocket._receiver.end();
+ this[kWebSocket] = void 0;
+ clearTimeout(websocket._closeTimer);
+ if (websocket._receiver._writableState.finished || websocket._receiver._writableState.errorEmitted) {
+ websocket.emitClose();
+ } else {
+ websocket._receiver.on("error", receiverOnFinish);
+ websocket._receiver.on("finish", receiverOnFinish);
+ }
+ }
+ __name(socketOnClose, "socketOnClose");
+ function socketOnData(chunk) {
+ if (!this[kWebSocket]._receiver.write(chunk)) {
+ this.pause();
+ }
+ }
+ __name(socketOnData, "socketOnData");
+ function socketOnEnd() {
+ const websocket = this[kWebSocket];
+ websocket._readyState = WebSocket2.CLOSING;
+ websocket._receiver.end();
+ this.end();
+ }
+ __name(socketOnEnd, "socketOnEnd");
+ function socketOnError() {
+ const websocket = this[kWebSocket];
+ this.removeListener("error", socketOnError);
+ this.on("error", NOOP);
+ if (websocket) {
+ websocket._readyState = WebSocket2.CLOSING;
+ this.destroy();
+ }
+ }
+ __name(socketOnError, "socketOnError");
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/subprotocol.js
+var require_subprotocol = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/subprotocol.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var { tokenChars } = require_validation2();
+ function parse4(header) {
+ const protocols = /* @__PURE__ */ new Set();
+ let start = -1;
+ let end = -1;
+ let i = 0;
+ for (i; i < header.length; i++) {
+ const code = header.charCodeAt(i);
+ if (end === -1 && tokenChars[code] === 1) {
+ if (start === -1)
+ start = i;
+ } else if (i !== 0 && (code === 32 || code === 9)) {
+ if (end === -1 && start !== -1)
+ end = i;
+ } else if (code === 44) {
+ if (start === -1) {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ if (end === -1)
+ end = i;
+ const protocol2 = header.slice(start, end);
+ if (protocols.has(protocol2)) {
+ throw new SyntaxError(`The "${protocol2}" subprotocol is duplicated`);
+ }
+ protocols.add(protocol2);
+ start = end = -1;
+ } else {
+ throw new SyntaxError(`Unexpected character at index ${i}`);
+ }
+ }
+ if (start === -1 || end !== -1) {
+ throw new SyntaxError("Unexpected end of input");
+ }
+ const protocol = header.slice(start, i);
+ if (protocols.has(protocol)) {
+ throw new SyntaxError(`The "${protocol}" subprotocol is duplicated`);
+ }
+ protocols.add(protocol);
+ return protocols;
+ }
+ __name(parse4, "parse");
+ module2.exports = { parse: parse4 };
+ }
+});
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/websocket-server.js
+var require_websocket_server2 = __commonJS({
+ "../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/lib/websocket-server.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var EventEmitter3 = require("events");
+ var http3 = require("http");
+ var https2 = require("https");
+ var net3 = require("net");
+ var tls = require("tls");
+ var { createHash } = require("crypto");
+ var extension = require_extension2();
+ var PerMessageDeflate = require_permessage_deflate2();
+ var subprotocol = require_subprotocol();
+ var WebSocket2 = require_websocket3();
+ var { GUID, kWebSocket } = require_constants7();
+ var keyRegex = /^[+/0-9A-Za-z]{22}==$/;
+ var RUNNING = 0;
+ var CLOSING = 1;
+ var CLOSED = 2;
+ var WebSocketServer2 = class extends EventEmitter3 {
+ /**
+ * Create a `WebSocketServer` instance.
+ *
+ * @param {Object} options Configuration options
+ * @param {Number} [options.backlog=511] The maximum length of the queue of
+ * pending connections
+ * @param {Boolean} [options.clientTracking=true] Specifies whether or not to
+ * track clients
+ * @param {Function} [options.handleProtocols] A hook to handle protocols
+ * @param {String} [options.host] The hostname where to bind the server
+ * @param {Number} [options.maxPayload=104857600] The maximum allowed message
+ * size
+ * @param {Boolean} [options.noServer=false] Enable no server mode
+ * @param {String} [options.path] Accept only connections matching this path
+ * @param {(Boolean|Object)} [options.perMessageDeflate=false] Enable/disable
+ * permessage-deflate
+ * @param {Number} [options.port] The port where to bind the server
+ * @param {(http.Server|https.Server)} [options.server] A pre-created HTTP/S
+ * server to use
+ * @param {Boolean} [options.skipUTF8Validation=false] Specifies whether or
+ * not to skip UTF-8 validation for text and close messages
+ * @param {Function} [options.verifyClient] A hook to reject connections
+ * @param {Function} [options.WebSocket=WebSocket] Specifies the `WebSocket`
+ * class to use. It must be the `WebSocket` class or class that extends it
+ * @param {Function} [callback] A listener for the `listening` event
+ */
+ constructor(options14, callback) {
+ super();
+ options14 = {
+ maxPayload: 100 * 1024 * 1024,
+ skipUTF8Validation: false,
+ perMessageDeflate: false,
+ handleProtocols: null,
+ clientTracking: true,
+ verifyClient: null,
+ noServer: false,
+ backlog: null,
+ // use default (511 as implemented in net.js)
+ server: null,
+ host: null,
+ path: null,
+ port: null,
+ WebSocket: WebSocket2,
+ ...options14
+ };
+ if (options14.port == null && !options14.server && !options14.noServer || options14.port != null && (options14.server || options14.noServer) || options14.server && options14.noServer) {
+ throw new TypeError(
+ 'One and only one of the "port", "server", or "noServer" options must be specified'
+ );
+ }
+ if (options14.port != null) {
+ this._server = http3.createServer((req, res) => {
+ const body = http3.STATUS_CODES[426];
+ res.writeHead(426, {
+ "Content-Length": body.length,
+ "Content-Type": "text/plain"
+ });
+ res.end(body);
+ });
+ this._server.listen(
+ options14.port,
+ options14.host,
+ options14.backlog,
+ callback
+ );
+ } else if (options14.server) {
+ this._server = options14.server;
+ }
+ if (this._server) {
+ const emitConnection = this.emit.bind(this, "connection");
+ this._removeListeners = addListeners(this._server, {
+ listening: this.emit.bind(this, "listening"),
+ error: this.emit.bind(this, "error"),
+ upgrade: (req, socket, head) => {
+ this.handleUpgrade(req, socket, head, emitConnection);
+ }
+ });
+ }
+ if (options14.perMessageDeflate === true)
+ options14.perMessageDeflate = {};
+ if (options14.clientTracking) {
+ this.clients = /* @__PURE__ */ new Set();
+ this._shouldEmitClose = false;
+ }
+ this.options = options14;
+ this._state = RUNNING;
+ }
+ /**
+ * Returns the bound address, the address family name, and port of the server
+ * as reported by the operating system if listening on an IP socket.
+ * If the server is listening on a pipe or UNIX domain socket, the name is
+ * returned as a string.
+ *
+ * @return {(Object|String|null)} The address of the server
+ * @public
+ */
+ address() {
+ if (this.options.noServer) {
+ throw new Error('The server is operating in "noServer" mode');
+ }
+ if (!this._server)
+ return null;
+ return this._server.address();
+ }
+ /**
+ * Stop the server from accepting new connections and emit the `'close'` event
+ * when all existing connections are closed.
+ *
+ * @param {Function} [cb] A one-time listener for the `'close'` event
+ * @public
+ */
+ close(cb) {
+ if (this._state === CLOSED) {
+ if (cb) {
+ this.once("close", () => {
+ cb(new Error("The server is not running"));
+ });
+ }
+ process.nextTick(emitClose, this);
+ return;
+ }
+ if (cb)
+ this.once("close", cb);
+ if (this._state === CLOSING)
+ return;
+ this._state = CLOSING;
+ if (this.options.noServer || this.options.server) {
+ if (this._server) {
+ this._removeListeners();
+ this._removeListeners = this._server = null;
+ }
+ if (this.clients) {
+ if (!this.clients.size) {
+ process.nextTick(emitClose, this);
+ } else {
+ this._shouldEmitClose = true;
+ }
+ } else {
+ process.nextTick(emitClose, this);
+ }
+ } else {
+ const server2 = this._server;
+ this._removeListeners();
+ this._removeListeners = this._server = null;
+ server2.close(() => {
+ emitClose(this);
+ });
+ }
+ }
+ /**
+ * See if a given request should be handled by this server instance.
+ *
+ * @param {http.IncomingMessage} req Request object to inspect
+ * @return {Boolean} `true` if the request is valid, else `false`
+ * @public
+ */
+ shouldHandle(req) {
+ if (this.options.path) {
+ const index = req.url.indexOf("?");
+ const pathname = index !== -1 ? req.url.slice(0, index) : req.url;
+ if (pathname !== this.options.path)
+ return false;
+ }
+ return true;
+ }
+ /**
+ * Handle a HTTP Upgrade request.
+ *
+ * @param {http.IncomingMessage} req The request object
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
+ * server and client
+ * @param {Buffer} head The first packet of the upgraded stream
+ * @param {Function} cb Callback
+ * @public
+ */
+ handleUpgrade(req, socket, head, cb) {
+ socket.on("error", socketOnError);
+ const key = req.headers["sec-websocket-key"];
+ const version2 = +req.headers["sec-websocket-version"];
+ if (req.method !== "GET") {
+ const message = "Invalid HTTP method";
+ abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
+ return;
+ }
+ if (req.headers.upgrade.toLowerCase() !== "websocket") {
+ const message = "Invalid Upgrade header";
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
+ return;
+ }
+ if (!key || !keyRegex.test(key)) {
+ const message = "Missing or invalid Sec-WebSocket-Key header";
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
+ return;
+ }
+ if (version2 !== 8 && version2 !== 13) {
+ const message = "Missing or invalid Sec-WebSocket-Version header";
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
+ return;
+ }
+ if (!this.shouldHandle(req)) {
+ abortHandshake(socket, 400);
+ return;
+ }
+ const secWebSocketProtocol = req.headers["sec-websocket-protocol"];
+ let protocols = /* @__PURE__ */ new Set();
+ if (secWebSocketProtocol !== void 0) {
+ try {
+ protocols = subprotocol.parse(secWebSocketProtocol);
+ } catch (err) {
+ const message = "Invalid Sec-WebSocket-Protocol header";
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
+ return;
+ }
+ }
+ const secWebSocketExtensions = req.headers["sec-websocket-extensions"];
+ const extensions = {};
+ if (this.options.perMessageDeflate && secWebSocketExtensions !== void 0) {
+ const perMessageDeflate = new PerMessageDeflate(
+ this.options.perMessageDeflate,
+ true,
+ this.options.maxPayload
+ );
+ try {
+ const offers = extension.parse(secWebSocketExtensions);
+ if (offers[PerMessageDeflate.extensionName]) {
+ perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]);
+ extensions[PerMessageDeflate.extensionName] = perMessageDeflate;
+ }
+ } catch (err) {
+ const message = "Invalid or unacceptable Sec-WebSocket-Extensions header";
+ abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
+ return;
+ }
+ }
+ if (this.options.verifyClient) {
+ const info = {
+ origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`],
+ secure: !!(req.socket.authorized || req.socket.encrypted),
+ req
+ };
+ if (this.options.verifyClient.length === 2) {
+ this.options.verifyClient(info, (verified, code, message, headers) => {
+ if (!verified) {
+ return abortHandshake(socket, code || 401, message, headers);
+ }
+ this.completeUpgrade(
+ extensions,
+ key,
+ protocols,
+ req,
+ socket,
+ head,
+ cb
+ );
+ });
+ return;
+ }
+ if (!this.options.verifyClient(info))
+ return abortHandshake(socket, 401);
+ }
+ this.completeUpgrade(extensions, key, protocols, req, socket, head, cb);
+ }
+ /**
+ * Upgrade the connection to WebSocket.
+ *
+ * @param {Object} extensions The accepted extensions
+ * @param {String} key The value of the `Sec-WebSocket-Key` header
+ * @param {Set} protocols The subprotocols
+ * @param {http.IncomingMessage} req The request object
+ * @param {(net.Socket|tls.Socket)} socket The network socket between the
+ * server and client
+ * @param {Buffer} head The first packet of the upgraded stream
+ * @param {Function} cb Callback
+ * @throws {Error} If called more than once with the same socket
+ * @private
+ */
+ completeUpgrade(extensions, key, protocols, req, socket, head, cb) {
+ if (!socket.readable || !socket.writable)
+ return socket.destroy();
+ if (socket[kWebSocket]) {
+ throw new Error(
+ "server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration"
+ );
+ }
+ if (this._state > RUNNING)
+ return abortHandshake(socket, 503);
+ const digest = createHash("sha1").update(key + GUID).digest("base64");
+ const headers = [
+ "HTTP/1.1 101 Switching Protocols",
+ "Upgrade: websocket",
+ "Connection: Upgrade",
+ `Sec-WebSocket-Accept: ${digest}`
+ ];
+ const ws = new this.options.WebSocket(null);
+ if (protocols.size) {
+ const protocol = this.options.handleProtocols ? this.options.handleProtocols(protocols, req) : protocols.values().next().value;
+ if (protocol) {
+ headers.push(`Sec-WebSocket-Protocol: ${protocol}`);
+ ws._protocol = protocol;
+ }
+ }
+ if (extensions[PerMessageDeflate.extensionName]) {
+ const params = extensions[PerMessageDeflate.extensionName].params;
+ const value = extension.format({
+ [PerMessageDeflate.extensionName]: [params]
+ });
+ headers.push(`Sec-WebSocket-Extensions: ${value}`);
+ ws._extensions = extensions;
+ }
+ this.emit("headers", headers, req);
+ socket.write(headers.concat("\r\n").join("\r\n"));
+ socket.removeListener("error", socketOnError);
+ ws.setSocket(socket, head, {
+ maxPayload: this.options.maxPayload,
+ skipUTF8Validation: this.options.skipUTF8Validation
+ });
+ if (this.clients) {
+ this.clients.add(ws);
+ ws.on("close", () => {
+ this.clients.delete(ws);
+ if (this._shouldEmitClose && !this.clients.size) {
+ process.nextTick(emitClose, this);
+ }
+ });
+ }
+ cb(ws, req);
+ }
+ };
+ __name(WebSocketServer2, "WebSocketServer");
+ module2.exports = WebSocketServer2;
+ function addListeners(server2, map) {
+ for (const event of Object.keys(map))
+ server2.on(event, map[event]);
+ return /* @__PURE__ */ __name(function removeListeners() {
+ for (const event of Object.keys(map)) {
+ server2.removeListener(event, map[event]);
+ }
+ }, "removeListeners");
+ }
+ __name(addListeners, "addListeners");
+ function emitClose(server2) {
+ server2._state = CLOSED;
+ server2.emit("close");
+ }
+ __name(emitClose, "emitClose");
+ function socketOnError() {
+ this.destroy();
+ }
+ __name(socketOnError, "socketOnError");
+ function abortHandshake(socket, code, message, headers) {
+ message = message || http3.STATUS_CODES[code];
+ headers = {
+ Connection: "close",
+ "Content-Type": "text/html",
+ "Content-Length": Buffer.byteLength(message),
+ ...headers
+ };
+ socket.once("finish", socket.destroy);
+ socket.end(
+ `HTTP/1.1 ${code} ${http3.STATUS_CODES[code]}\r
+` + Object.keys(headers).map((h) => `${h}: ${headers[h]}`).join("\r\n") + "\r\n\r\n" + message
+ );
+ }
+ __name(abortHandshake, "abortHandshake");
+ function abortHandshakeOrEmitwsClientError(server2, req, socket, code, message) {
+ if (server2.listenerCount("wsClientError")) {
+ const err = new Error(message);
+ Error.captureStackTrace(err, abortHandshakeOrEmitwsClientError);
+ server2.emit("wsClientError", err, socket, req);
+ } else {
+ abortHandshake(socket, code, message);
+ }
+ }
+ __name(abortHandshakeOrEmitwsClientError, "abortHandshakeOrEmitwsClientError");
+ }
+});
+
+// ../../node_modules/.pnpm/buffer-from@1.1.2/node_modules/buffer-from/index.js
+var require_buffer_from = __commonJS({
+ "../../node_modules/.pnpm/buffer-from@1.1.2/node_modules/buffer-from/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var toString = Object.prototype.toString;
+ var isModern = typeof Buffer !== "undefined" && typeof Buffer.alloc === "function" && typeof Buffer.allocUnsafe === "function" && typeof Buffer.from === "function";
+ function isArrayBuffer(input) {
+ return toString.call(input).slice(8, -1) === "ArrayBuffer";
+ }
+ __name(isArrayBuffer, "isArrayBuffer");
+ function fromArrayBuffer(obj, byteOffset, length) {
+ byteOffset >>>= 0;
+ var maxLength = obj.byteLength - byteOffset;
+ if (maxLength < 0) {
+ throw new RangeError("'offset' is out of bounds");
+ }
+ if (length === void 0) {
+ length = maxLength;
+ } else {
+ length >>>= 0;
+ if (length > maxLength) {
+ throw new RangeError("'length' is out of bounds");
+ }
+ }
+ return isModern ? Buffer.from(obj.slice(byteOffset, byteOffset + length)) : new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)));
+ }
+ __name(fromArrayBuffer, "fromArrayBuffer");
+ function fromString(string, encoding) {
+ if (typeof encoding !== "string" || encoding === "") {
+ encoding = "utf8";
+ }
+ if (!Buffer.isEncoding(encoding)) {
+ throw new TypeError('"encoding" must be a valid string encoding');
+ }
+ return isModern ? Buffer.from(string, encoding) : new Buffer(string, encoding);
+ }
+ __name(fromString, "fromString");
+ function bufferFrom(value, encodingOrOffset, length) {
+ if (typeof value === "number") {
+ throw new TypeError('"value" argument must not be a number');
+ }
+ if (isArrayBuffer(value)) {
+ return fromArrayBuffer(value, encodingOrOffset, length);
+ }
+ if (typeof value === "string") {
+ return fromString(value, encodingOrOffset);
+ }
+ return isModern ? Buffer.from(value) : new Buffer(value);
+ }
+ __name(bufferFrom, "bufferFrom");
+ module2.exports = bufferFrom;
+ }
+});
+
+// ../../node_modules/.pnpm/source-map-support@0.5.21/node_modules/source-map-support/source-map-support.js
+var require_source_map_support = __commonJS({
+ "../../node_modules/.pnpm/source-map-support@0.5.21/node_modules/source-map-support/source-map-support.js"(exports2, module2) {
+ init_import_meta_url();
+ var SourceMapConsumer = require("source-map").SourceMapConsumer;
+ var path45 = require("path");
+ var fs20;
+ try {
+ fs20 = require("fs");
+ if (!fs20.existsSync || !fs20.readFileSync) {
+ fs20 = null;
+ }
+ } catch (err) {
+ }
+ var bufferFrom = require_buffer_from();
+ function dynamicRequire(mod, request) {
+ return mod.require(request);
+ }
+ __name(dynamicRequire, "dynamicRequire");
+ var errorFormatterInstalled = false;
+ var uncaughtShimInstalled = false;
+ var emptyCacheBetweenOperations = false;
+ var environment = "auto";
+ var fileContentsCache = {};
+ var sourceMapCache = {};
+ var reSourceMap = /^data:application\/json[^,]+base64,/;
+ var retrieveFileHandlers = [];
+ var retrieveMapHandlers = [];
+ function isInBrowser() {
+ if (environment === "browser")
+ return true;
+ if (environment === "node")
+ return false;
+ return typeof window !== "undefined" && typeof XMLHttpRequest === "function" && !(window.require && window.module && window.process && window.process.type === "renderer");
+ }
+ __name(isInBrowser, "isInBrowser");
+ function hasGlobalProcessEventEmitter() {
+ return typeof process === "object" && process !== null && typeof process.on === "function";
+ }
+ __name(hasGlobalProcessEventEmitter, "hasGlobalProcessEventEmitter");
+ function globalProcessVersion() {
+ if (typeof process === "object" && process !== null) {
+ return process.version;
+ } else {
+ return "";
+ }
+ }
+ __name(globalProcessVersion, "globalProcessVersion");
+ function globalProcessStderr() {
+ if (typeof process === "object" && process !== null) {
+ return process.stderr;
+ }
+ }
+ __name(globalProcessStderr, "globalProcessStderr");
+ function globalProcessExit(code) {
+ if (typeof process === "object" && process !== null && typeof process.exit === "function") {
+ return process.exit(code);
+ }
+ }
+ __name(globalProcessExit, "globalProcessExit");
+ function handlerExec(list) {
+ return function(arg) {
+ for (var i = 0; i < list.length; i++) {
+ var ret = list[i](arg);
+ if (ret) {
+ return ret;
+ }
+ }
+ return null;
+ };
+ }
+ __name(handlerExec, "handlerExec");
+ var retrieveFile = handlerExec(retrieveFileHandlers);
+ retrieveFileHandlers.push(function(path46) {
+ path46 = path46.trim();
+ if (/^file:/.test(path46)) {
+ path46 = path46.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
+ return drive ? "" : (
+ // file:///C:/dir/file -> C:/dir/file
+ "/"
+ );
+ });
+ }
+ if (path46 in fileContentsCache) {
+ return fileContentsCache[path46];
+ }
+ var contents = "";
+ try {
+ if (!fs20) {
+ var xhr = new XMLHttpRequest();
+ xhr.open(
+ "GET",
+ path46,
+ /** async */
+ false
+ );
+ xhr.send(null);
+ if (xhr.readyState === 4 && xhr.status === 200) {
+ contents = xhr.responseText;
+ }
+ } else if (fs20.existsSync(path46)) {
+ contents = fs20.readFileSync(path46, "utf8");
+ }
+ } catch (er) {
+ }
+ return fileContentsCache[path46] = contents;
+ });
+ function supportRelativeURL(file, url3) {
+ if (!file)
+ return url3;
+ var dir = path45.dirname(file);
+ var match = /^\w+:\/\/[^\/]*/.exec(dir);
+ var protocol = match ? match[0] : "";
+ var startPath = dir.slice(protocol.length);
+ if (protocol && /^\/\w\:/.test(startPath)) {
+ protocol += "/";
+ return protocol + path45.resolve(dir.slice(protocol.length), url3).replace(/\\/g, "/");
+ }
+ return protocol + path45.resolve(dir.slice(protocol.length), url3);
+ }
+ __name(supportRelativeURL, "supportRelativeURL");
+ function retrieveSourceMapURL(source) {
+ var fileData;
+ if (isInBrowser()) {
+ try {
+ var xhr = new XMLHttpRequest();
+ xhr.open("GET", source, false);
+ xhr.send(null);
+ fileData = xhr.readyState === 4 ? xhr.responseText : null;
+ var sourceMapHeader = xhr.getResponseHeader("SourceMap") || xhr.getResponseHeader("X-SourceMap");
+ if (sourceMapHeader) {
+ return sourceMapHeader;
+ }
+ } catch (e2) {
+ }
+ }
+ fileData = retrieveFile(source);
+ var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
+ var lastMatch, match;
+ while (match = re.exec(fileData))
+ lastMatch = match;
+ if (!lastMatch)
+ return null;
+ return lastMatch[1];
+ }
+ __name(retrieveSourceMapURL, "retrieveSourceMapURL");
+ var retrieveSourceMap = handlerExec(retrieveMapHandlers);
+ retrieveMapHandlers.push(function(source) {
+ var sourceMappingURL = retrieveSourceMapURL(source);
+ if (!sourceMappingURL)
+ return null;
+ var sourceMapData;
+ if (reSourceMap.test(sourceMappingURL)) {
+ var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(",") + 1);
+ sourceMapData = bufferFrom(rawData, "base64").toString();
+ sourceMappingURL = source;
+ } else {
+ sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
+ sourceMapData = retrieveFile(sourceMappingURL);
+ }
+ if (!sourceMapData) {
+ return null;
+ }
+ return {
+ url: sourceMappingURL,
+ map: sourceMapData
+ };
+ });
+ function mapSourcePosition(position) {
+ var sourceMap = sourceMapCache[position.source];
+ if (!sourceMap) {
+ var urlAndMap = retrieveSourceMap(position.source);
+ if (urlAndMap) {
+ sourceMap = sourceMapCache[position.source] = {
+ url: urlAndMap.url,
+ map: new SourceMapConsumer(urlAndMap.map)
+ };
+ if (sourceMap.map.sourcesContent) {
+ sourceMap.map.sources.forEach(function(source, i) {
+ var contents = sourceMap.map.sourcesContent[i];
+ if (contents) {
+ var url3 = supportRelativeURL(sourceMap.url, source);
+ fileContentsCache[url3] = contents;
+ }
+ });
+ }
+ } else {
+ sourceMap = sourceMapCache[position.source] = {
+ url: null,
+ map: null
+ };
+ }
+ }
+ if (sourceMap && sourceMap.map && typeof sourceMap.map.originalPositionFor === "function") {
+ var originalPosition = sourceMap.map.originalPositionFor(position);
+ if (originalPosition.source !== null) {
+ originalPosition.source = supportRelativeURL(
+ sourceMap.url,
+ originalPosition.source
+ );
+ return originalPosition;
+ }
+ }
+ return position;
+ }
+ __name(mapSourcePosition, "mapSourcePosition");
+ function mapEvalOrigin(origin) {
+ var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
+ if (match) {
+ var position = mapSourcePosition({
+ source: match[2],
+ line: +match[3],
+ column: match[4] - 1
+ });
+ return "eval at " + match[1] + " (" + position.source + ":" + position.line + ":" + (position.column + 1) + ")";
+ }
+ match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
+ if (match) {
+ return "eval at " + match[1] + " (" + mapEvalOrigin(match[2]) + ")";
+ }
+ return origin;
+ }
+ __name(mapEvalOrigin, "mapEvalOrigin");
+ function CallSiteToString() {
+ var fileName;
+ var fileLocation = "";
+ if (this.isNative()) {
+ fileLocation = "native";
+ } else {
+ fileName = this.getScriptNameOrSourceURL();
+ if (!fileName && this.isEval()) {
+ fileLocation = this.getEvalOrigin();
+ fileLocation += ", ";
+ }
+ if (fileName) {
+ fileLocation += fileName;
+ } else {
+ fileLocation += "";
+ }
+ var lineNumber = this.getLineNumber();
+ if (lineNumber != null) {
+ fileLocation += ":" + lineNumber;
+ var columnNumber = this.getColumnNumber();
+ if (columnNumber) {
+ fileLocation += ":" + columnNumber;
+ }
+ }
+ }
+ var line = "";
+ var functionName = this.getFunctionName();
+ var addSuffix = true;
+ var isConstructor = this.isConstructor();
+ var isMethodCall = !(this.isToplevel() || isConstructor);
+ if (isMethodCall) {
+ var typeName = this.getTypeName();
+ if (typeName === "[object Object]") {
+ typeName = "null";
+ }
+ var methodName = this.getMethodName();
+ if (functionName) {
+ if (typeName && functionName.indexOf(typeName) != 0) {
+ line += typeName + ".";
+ }
+ line += functionName;
+ if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
+ line += " [as " + methodName + "]";
+ }
+ } else {
+ line += typeName + "." + (methodName || "");
+ }
+ } else if (isConstructor) {
+ line += "new " + (functionName || "");
+ } else if (functionName) {
+ line += functionName;
+ } else {
+ line += fileLocation;
+ addSuffix = false;
+ }
+ if (addSuffix) {
+ line += " (" + fileLocation + ")";
+ }
+ return line;
+ }
+ __name(CallSiteToString, "CallSiteToString");
+ function cloneCallSite(frame) {
+ var object = {};
+ Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
+ object[name] = /^(?:is|get)/.test(name) ? function() {
+ return frame[name].call(frame);
+ } : frame[name];
+ });
+ object.toString = CallSiteToString;
+ return object;
+ }
+ __name(cloneCallSite, "cloneCallSite");
+ function wrapCallSite(frame, state) {
+ if (state === void 0) {
+ state = { nextPosition: null, curPosition: null };
+ }
+ if (frame.isNative()) {
+ state.curPosition = null;
+ return frame;
+ }
+ var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
+ if (source) {
+ var line = frame.getLineNumber();
+ var column = frame.getColumnNumber() - 1;
+ var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
+ var headerLength = noHeader.test(globalProcessVersion()) ? 0 : 62;
+ if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
+ column -= headerLength;
+ }
+ var position = mapSourcePosition({
+ source,
+ line,
+ column
+ });
+ state.curPosition = position;
+ frame = cloneCallSite(frame);
+ var originalFunctionName = frame.getFunctionName;
+ frame.getFunctionName = function() {
+ if (state.nextPosition == null) {
+ return originalFunctionName();
+ }
+ return state.nextPosition.name || originalFunctionName();
+ };
+ frame.getFileName = function() {
+ return position.source;
+ };
+ frame.getLineNumber = function() {
+ return position.line;
+ };
+ frame.getColumnNumber = function() {
+ return position.column + 1;
+ };
+ frame.getScriptNameOrSourceURL = function() {
+ return position.source;
+ };
+ return frame;
+ }
+ var origin = frame.isEval() && frame.getEvalOrigin();
+ if (origin) {
+ origin = mapEvalOrigin(origin);
+ frame = cloneCallSite(frame);
+ frame.getEvalOrigin = function() {
+ return origin;
+ };
+ return frame;
+ }
+ return frame;
+ }
+ __name(wrapCallSite, "wrapCallSite");
+ function prepareStackTrace(error, stack) {
+ if (emptyCacheBetweenOperations) {
+ fileContentsCache = {};
+ sourceMapCache = {};
+ }
+ var name = error.name || "Error";
+ var message = error.message || "";
+ var errorString = name + ": " + message;
+ var state = { nextPosition: null, curPosition: null };
+ var processedStack = [];
+ for (var i = stack.length - 1; i >= 0; i--) {
+ processedStack.push("\n at " + wrapCallSite(stack[i], state));
+ state.nextPosition = state.curPosition;
+ }
+ state.curPosition = state.nextPosition = null;
+ return errorString + processedStack.reverse().join("");
+ }
+ __name(prepareStackTrace, "prepareStackTrace");
+ function getErrorSource(error) {
+ var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
+ if (match) {
+ var source = match[1];
+ var line = +match[2];
+ var column = +match[3];
+ var contents = fileContentsCache[source];
+ if (!contents && fs20 && fs20.existsSync(source)) {
+ try {
+ contents = fs20.readFileSync(source, "utf8");
+ } catch (er) {
+ contents = "";
+ }
+ }
+ if (contents) {
+ var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
+ if (code) {
+ return source + ":" + line + "\n" + code + "\n" + new Array(column).join(" ") + "^";
+ }
+ }
+ }
+ return null;
+ }
+ __name(getErrorSource, "getErrorSource");
+ function printErrorAndExit(error) {
+ var source = getErrorSource(error);
+ var stderr = globalProcessStderr();
+ if (stderr && stderr._handle && stderr._handle.setBlocking) {
+ stderr._handle.setBlocking(true);
+ }
+ if (source) {
+ console.error();
+ console.error(source);
+ }
+ console.error(error.stack);
+ globalProcessExit(1);
+ }
+ __name(printErrorAndExit, "printErrorAndExit");
+ function shimEmitUncaughtException() {
+ var origEmit = process.emit;
+ process.emit = function(type) {
+ if (type === "uncaughtException") {
+ var hasStack = arguments[1] && arguments[1].stack;
+ var hasListeners = this.listeners(type).length > 0;
+ if (hasStack && !hasListeners) {
+ return printErrorAndExit(arguments[1]);
+ }
+ }
+ return origEmit.apply(this, arguments);
+ };
+ }
+ __name(shimEmitUncaughtException, "shimEmitUncaughtException");
+ var originalRetrieveFileHandlers = retrieveFileHandlers.slice(0);
+ var originalRetrieveMapHandlers = retrieveMapHandlers.slice(0);
+ exports2.wrapCallSite = wrapCallSite;
+ exports2.getErrorSource = getErrorSource;
+ exports2.mapSourcePosition = mapSourcePosition;
+ exports2.retrieveSourceMap = retrieveSourceMap;
+ exports2.install = function(options14) {
+ options14 = options14 || {};
+ if (options14.environment) {
+ environment = options14.environment;
+ if (["node", "browser", "auto"].indexOf(environment) === -1) {
+ throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}");
+ }
+ }
+ if (options14.retrieveFile) {
+ if (options14.overrideRetrieveFile) {
+ retrieveFileHandlers.length = 0;
+ }
+ retrieveFileHandlers.unshift(options14.retrieveFile);
+ }
+ if (options14.retrieveSourceMap) {
+ if (options14.overrideRetrieveSourceMap) {
+ retrieveMapHandlers.length = 0;
+ }
+ retrieveMapHandlers.unshift(options14.retrieveSourceMap);
+ }
+ if (options14.hookRequire && !isInBrowser()) {
+ var Module = dynamicRequire(module2, "module");
+ var $compile = Module.prototype._compile;
+ if (!$compile.__sourceMapSupport) {
+ Module.prototype._compile = function(content, filename) {
+ fileContentsCache[filename] = content;
+ sourceMapCache[filename] = void 0;
+ return $compile.call(this, content, filename);
+ };
+ Module.prototype._compile.__sourceMapSupport = true;
+ }
+ }
+ if (!emptyCacheBetweenOperations) {
+ emptyCacheBetweenOperations = "emptyCacheBetweenOperations" in options14 ? options14.emptyCacheBetweenOperations : false;
+ }
+ if (!errorFormatterInstalled) {
+ errorFormatterInstalled = true;
+ Error.prepareStackTrace = prepareStackTrace;
+ }
+ if (!uncaughtShimInstalled) {
+ var installHandler = "handleUncaughtExceptions" in options14 ? options14.handleUncaughtExceptions : true;
+ try {
+ var worker_threads = dynamicRequire(module2, "worker_threads");
+ if (worker_threads.isMainThread === false) {
+ installHandler = false;
+ }
+ } catch (e2) {
+ }
+ if (installHandler && hasGlobalProcessEventEmitter()) {
+ uncaughtShimInstalled = true;
+ shimEmitUncaughtException();
+ }
+ }
+ };
+ exports2.resetRetrieveHandlers = function() {
+ retrieveFileHandlers.length = 0;
+ retrieveMapHandlers.length = 0;
+ retrieveFileHandlers = originalRetrieveFileHandlers.slice(0);
+ retrieveMapHandlers = originalRetrieveMapHandlers.slice(0);
+ retrieveSourceMap = handlerExec(retrieveMapHandlers);
+ retrieveFile = handlerExec(retrieveFileHandlers);
+ };
+ }
+});
+
+// ../pages-shared/metadata-generator/constants.ts
+var REDIRECTS_VERSION, HEADERS_VERSION, ANALYTICS_VERSION, PERMITTED_STATUS_CODES, HEADER_SEPARATOR, MAX_LINE_LENGTH, MAX_HEADER_RULES, MAX_DYNAMIC_REDIRECT_RULES, MAX_STATIC_REDIRECT_RULES, UNSET_OPERATOR, SPLAT_REGEX, PLACEHOLDER_REGEX;
+var init_constants = __esm({
+ "../pages-shared/metadata-generator/constants.ts"() {
+ init_import_meta_url();
+ REDIRECTS_VERSION = 1;
+ HEADERS_VERSION = 2;
+ ANALYTICS_VERSION = 1;
+ PERMITTED_STATUS_CODES = /* @__PURE__ */ new Set([200, 301, 302, 303, 307, 308]);
+ HEADER_SEPARATOR = ":";
+ MAX_LINE_LENGTH = 2e3;
+ MAX_HEADER_RULES = 100;
+ MAX_DYNAMIC_REDIRECT_RULES = 100;
+ MAX_STATIC_REDIRECT_RULES = 2e3;
+ UNSET_OPERATOR = "! ";
+ SPLAT_REGEX = /\*/g;
+ PLACEHOLDER_REGEX = /:[A-Za-z]\w*/g;
+ }
+});
+
+// ../pages-shared/metadata-generator/createMetadataObject.ts
+function createMetadataObject({
+ redirects,
+ headers,
+ webAnalyticsToken,
+ deploymentId,
+ failOpen,
+ logger: logger2 = /* @__PURE__ */ __name((_message) => {
+ }, "logger")
+}) {
+ return {
+ ...constructRedirects({ redirects, logger: logger2 }),
+ ...constructHeaders({ headers, logger: logger2 }),
+ ...constructWebAnalytics({ webAnalyticsToken, logger: logger2 }),
+ deploymentId,
+ failOpen
+ };
+}
+function constructRedirects({
+ redirects,
+ logger: logger2
+}) {
+ if (!redirects)
+ return {};
+ const num_valid = redirects.rules.length;
+ const num_invalid = redirects.invalid.length;
+ logger2(
+ `Parsed ${num_valid} valid redirect rule${num_valid === 1 ? "" : "s"}.`
+ );
+ if (num_invalid > 0) {
+ logger2(`Found invalid redirect lines:`);
+ for (const { line, lineNumber, message } of redirects.invalid) {
+ if (line)
+ logger2(` - ${lineNumber ? `#${lineNumber}: ` : ""}${line}`);
+ logger2(` ${message}`);
+ }
+ }
+ if (num_valid === 0) {
+ return {};
+ }
+ const staticRedirects = {};
+ const dynamicRedirects = {};
+ let canCreateStaticRule = true;
+ for (const rule of redirects.rules) {
+ if (!rule.from.match(SPLAT_REGEX) && !rule.from.match(PLACEHOLDER_REGEX)) {
+ if (canCreateStaticRule) {
+ staticRedirects[rule.from] = {
+ status: rule.status,
+ to: rule.to,
+ lineNumber: rule.lineNumber
+ };
+ continue;
+ } else {
+ logger2(
+ `Info: the redirect rule ${rule.from} \u2192 ${rule.status} ${rule.to} could be made more performant by bringing it above any lines with splats or placeholders.`
+ );
+ }
+ }
+ dynamicRedirects[rule.from] = { status: rule.status, to: rule.to };
+ canCreateStaticRule = false;
+ }
+ return {
+ redirects: {
+ version: REDIRECTS_VERSION,
+ staticRules: staticRedirects,
+ rules: dynamicRedirects
+ }
+ };
+}
+function constructHeaders({
+ headers,
+ logger: logger2
+}) {
+ if (!headers)
+ return {};
+ const num_valid = headers.rules.length;
+ const num_invalid = headers.invalid.length;
+ logger2(`Parsed ${num_valid} valid header rule${num_valid === 1 ? "" : "s"}.`);
+ if (num_invalid > 0) {
+ logger2(`Found invalid header lines:`);
+ for (const { line, lineNumber, message } of headers.invalid) {
+ if (line)
+ logger2(` - ${lineNumber ? `#${lineNumber}: ` : ""} ${line}`);
+ logger2(` ${message}`);
+ }
+ }
+ if (num_valid === 0) {
+ return {};
+ }
+ const rules = {};
+ for (const rule of headers.rules) {
+ rules[rule.path] = {};
+ if (Object.keys(rule.headers).length) {
+ rules[rule.path].set = rule.headers;
+ }
+ if (rule.unsetHeaders.length) {
+ rules[rule.path].unset = rule.unsetHeaders;
+ }
+ }
+ return {
+ headers: {
+ version: HEADERS_VERSION,
+ rules
+ }
+ };
+}
+function constructWebAnalytics({
+ webAnalyticsToken
+}) {
+ if (!webAnalyticsToken)
+ return {};
+ return {
+ analytics: {
+ version: ANALYTICS_VERSION,
+ token: webAnalyticsToken
+ }
+ };
+}
+var init_createMetadataObject = __esm({
+ "../pages-shared/metadata-generator/createMetadataObject.ts"() {
+ init_import_meta_url();
+ init_constants();
+ __name(createMetadataObject, "createMetadataObject");
+ __name(constructRedirects, "constructRedirects");
+ __name(constructHeaders, "constructHeaders");
+ __name(constructWebAnalytics, "constructWebAnalytics");
+ }
+});
+
+// ../pages-shared/metadata-generator/validateURL.ts
+function urlHasHost(token) {
+ const host = URL_REGEX.exec(token);
+ return Boolean(host && host.groups && host.groups.host);
+}
+var extractPathname, URL_REGEX, HOST_WITH_PORT_REGEX, PATH_REGEX, validateUrl;
+var init_validateURL = __esm({
+ "../pages-shared/metadata-generator/validateURL.ts"() {
+ init_import_meta_url();
+ extractPathname = /* @__PURE__ */ __name((path45 = "/", includeSearch, includeHash) => {
+ if (!path45.startsWith("/"))
+ path45 = `/${path45}`;
+ const url3 = new URL(`//${path45}`, "relative://");
+ return `${url3.pathname}${includeSearch ? url3.search : ""}${includeHash ? url3.hash : ""}`;
+ }, "extractPathname");
+ URL_REGEX = /^https:\/\/+(?[^/]+)\/?(?.*)/;
+ HOST_WITH_PORT_REGEX = /.*:\d+$/;
+ PATH_REGEX = /^\//;
+ validateUrl = /* @__PURE__ */ __name((token, onlyRelative = false, disallowPorts = false, includeSearch = false, includeHash = false) => {
+ const host = URL_REGEX.exec(token);
+ if (host && host.groups && host.groups.host) {
+ if (onlyRelative)
+ return [
+ void 0,
+ `Only relative URLs are allowed. Skipping absolute URL ${token}.`
+ ];
+ if (disallowPorts && host.groups.host.match(HOST_WITH_PORT_REGEX)) {
+ return [
+ void 0,
+ `Specifying ports is not supported. Skipping absolute URL ${token}.`
+ ];
+ }
+ return [
+ `https://${host.groups.host}${extractPathname(
+ host.groups.path,
+ includeSearch,
+ includeHash
+ )}`,
+ void 0
+ ];
+ } else {
+ if (!token.startsWith("/") && onlyRelative)
+ token = `/${token}`;
+ const path45 = PATH_REGEX.exec(token);
+ if (path45) {
+ try {
+ return [extractPathname(token, includeSearch, includeHash), void 0];
+ } catch {
+ return [void 0, `Error parsing URL segment ${token}. Skipping.`];
+ }
+ }
+ }
+ return [
+ void 0,
+ onlyRelative ? "URLs should begin with a forward-slash." : 'URLs should either be relative (e.g. begin with a forward-slash), or use HTTPS (e.g. begin with "https://").'
+ ];
+ }, "validateUrl");
+ __name(urlHasHost, "urlHasHost");
+ }
+});
+
+// ../pages-shared/metadata-generator/parseHeaders.ts
+function parseHeaders(input) {
+ const lines = input.split("\n");
+ const rules = [];
+ const invalid = [];
+ let rule = void 0;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ if (line.length === 0 || line.startsWith("#"))
+ continue;
+ if (line.length > MAX_LINE_LENGTH) {
+ invalid.push({
+ message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${MAX_LINE_LENGTH}.`
+ });
+ continue;
+ }
+ if (LINE_IS_PROBABLY_A_PATH.test(line)) {
+ if (rules.length >= MAX_HEADER_RULES) {
+ invalid.push({
+ message: `Maximum number of rules supported is ${MAX_HEADER_RULES}. Skipping remaining ${lines.length - i} lines of file.`
+ });
+ break;
+ }
+ if (rule) {
+ if (isValidRule(rule)) {
+ rules.push({
+ path: rule.path,
+ headers: rule.headers,
+ unsetHeaders: rule.unsetHeaders
+ });
+ } else {
+ invalid.push({
+ line: rule.line,
+ lineNumber: i + 1,
+ message: "No headers specified"
+ });
+ }
+ }
+ const [path45, pathError] = validateUrl(line, false, true);
+ if (pathError) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: pathError
+ });
+ rule = void 0;
+ continue;
+ }
+ rule = {
+ path: path45,
+ line,
+ headers: {},
+ unsetHeaders: []
+ };
+ continue;
+ }
+ if (!line.includes(HEADER_SEPARATOR)) {
+ if (!rule) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: "Expected a path beginning with at least one forward-slash"
+ });
+ } else {
+ if (line.trim().startsWith(UNSET_OPERATOR)) {
+ rule.unsetHeaders.push(line.trim().replace(UNSET_OPERATOR, ""));
+ } else {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: "Expected a colon-separated header pair (e.g. name: value)"
+ });
+ }
+ }
+ continue;
+ }
+ const [rawName, ...rawValue] = line.split(HEADER_SEPARATOR);
+ const name = rawName.trim().toLowerCase();
+ if (name.includes(" ")) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: "Header name cannot include spaces"
+ });
+ continue;
+ }
+ const value = rawValue.join(HEADER_SEPARATOR).trim();
+ if (name === "") {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: "No header name specified"
+ });
+ continue;
+ }
+ if (value === "") {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: "No header value specified"
+ });
+ continue;
+ }
+ if (!rule) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: `Path should come before header (${name}: ${value})`
+ });
+ continue;
+ }
+ const existingValues = rule.headers[name];
+ rule.headers[name] = existingValues ? `${existingValues}, ${value}` : value;
+ }
+ if (rule) {
+ if (isValidRule(rule)) {
+ rules.push({
+ path: rule.path,
+ headers: rule.headers,
+ unsetHeaders: rule.unsetHeaders
+ });
+ } else {
+ invalid.push({ line: rule.line, message: "No headers specified" });
+ }
+ }
+ return {
+ rules,
+ invalid
+ };
+}
+function isValidRule(rule) {
+ return Object.keys(rule.headers).length > 0 || rule.unsetHeaders.length > 0;
+}
+var LINE_IS_PROBABLY_A_PATH;
+var init_parseHeaders = __esm({
+ "../pages-shared/metadata-generator/parseHeaders.ts"() {
+ init_import_meta_url();
+ init_constants();
+ init_validateURL();
+ LINE_IS_PROBABLY_A_PATH = new RegExp(/^([^\s]+:\/\/|^\/)/);
+ __name(parseHeaders, "parseHeaders");
+ __name(isValidRule, "isValidRule");
+ }
+});
+
+// ../pages-shared/metadata-generator/parseRedirects.ts
+function parseRedirects(input) {
+ const lines = input.split("\n");
+ const rules = [];
+ const seen_paths = /* @__PURE__ */ new Set();
+ const invalid = [];
+ let staticRules = 0;
+ let dynamicRules = 0;
+ let canCreateStaticRule = true;
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].trim();
+ if (line.length === 0 || line.startsWith("#"))
+ continue;
+ if (line.length > MAX_LINE_LENGTH) {
+ invalid.push({
+ message: `Ignoring line ${i + 1} as it exceeds the maximum allowed length of ${MAX_LINE_LENGTH}.`
+ });
+ continue;
+ }
+ const tokens = line.split(/\s+/);
+ if (tokens.length < 2 || tokens.length > 3) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: `Expected exactly 2 or 3 whitespace-separated tokens. Got ${tokens.length}.`
+ });
+ continue;
+ }
+ const [str_from, str_to, str_status = "302"] = tokens;
+ const fromResult = validateUrl(str_from, true, true, false, false);
+ if (fromResult[0] === void 0) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: fromResult[1]
+ });
+ continue;
+ }
+ const from = fromResult[0];
+ if (canCreateStaticRule && !from.match(SPLAT_REGEX) && !from.match(PLACEHOLDER_REGEX)) {
+ staticRules += 1;
+ if (staticRules > MAX_STATIC_REDIRECT_RULES) {
+ invalid.push({
+ message: `Maximum number of static rules supported is ${MAX_STATIC_REDIRECT_RULES}. Skipping line.`
+ });
+ continue;
+ }
+ } else {
+ dynamicRules += 1;
+ canCreateStaticRule = false;
+ if (dynamicRules > MAX_DYNAMIC_REDIRECT_RULES) {
+ invalid.push({
+ message: `Maximum number of dynamic rules supported is ${MAX_DYNAMIC_REDIRECT_RULES}. Skipping remaining ${lines.length - i} lines of file.`
+ });
+ break;
+ }
+ }
+ const toResult = validateUrl(str_to, false, false, true, true);
+ if (toResult[0] === void 0) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: toResult[1]
+ });
+ continue;
+ }
+ const to = toResult[0];
+ const status = Number(str_status);
+ if (isNaN(status) || !PERMITTED_STATUS_CODES.has(status)) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: `Valid status codes are 200, 301, 302 (default), 303, 307, or 308. Got ${str_status}.`
+ });
+ continue;
+ }
+ if (/\/\*?$/.test(from) && /\/index(.html)?$/.test(to) && !urlHasHost(to)) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: "Infinite loop detected in this rule and has been ignored. This will cause a redirect to strip `.html` or `/index` and end up triggering this rule again. Please fix or remove this rule to silence this warning."
+ });
+ continue;
+ }
+ if (seen_paths.has(from)) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: `Ignoring duplicate rule for path ${from}.`
+ });
+ continue;
+ }
+ seen_paths.add(from);
+ if (status === 200) {
+ if (urlHasHost(to)) {
+ invalid.push({
+ line,
+ lineNumber: i + 1,
+ message: `Proxy (200) redirects can only point to relative paths. Got ${to}`
+ });
+ continue;
+ }
+ }
+ rules.push({ from, to, status, lineNumber: i + 1 });
+ }
+ return {
+ rules,
+ invalid
+ };
+}
+var init_parseRedirects = __esm({
+ "../pages-shared/metadata-generator/parseRedirects.ts"() {
+ init_import_meta_url();
+ init_constants();
+ init_validateURL();
+ __name(parseRedirects, "parseRedirects");
+ }
+});
+
+// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js
+var require_Mime = __commonJS({
+ "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/Mime.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ function Mime() {
+ this._types = /* @__PURE__ */ Object.create(null);
+ this._extensions = /* @__PURE__ */ Object.create(null);
+ for (let i = 0; i < arguments.length; i++) {
+ this.define(arguments[i]);
+ }
+ this.define = this.define.bind(this);
+ this.getType = this.getType.bind(this);
+ this.getExtension = this.getExtension.bind(this);
+ }
+ __name(Mime, "Mime");
+ Mime.prototype.define = function(typeMap, force) {
+ for (let type in typeMap) {
+ let extensions = typeMap[type].map(function(t2) {
+ return t2.toLowerCase();
+ });
+ type = type.toLowerCase();
+ for (let i = 0; i < extensions.length; i++) {
+ const ext = extensions[i];
+ if (ext[0] === "*") {
+ continue;
+ }
+ if (!force && ext in this._types) {
+ throw new Error(
+ 'Attempt to change mapping for "' + ext + '" extension from "' + this._types[ext] + '" to "' + type + '". Pass `force=true` to allow this, otherwise remove "' + ext + '" from the list of extensions for "' + type + '".'
+ );
+ }
+ this._types[ext] = type;
+ }
+ if (force || !this._extensions[type]) {
+ const ext = extensions[0];
+ this._extensions[type] = ext[0] !== "*" ? ext : ext.substr(1);
+ }
+ }
+ };
+ Mime.prototype.getType = function(path45) {
+ path45 = String(path45);
+ let last = path45.replace(/^.*[/\\]/, "").toLowerCase();
+ let ext = last.replace(/^.*\./, "").toLowerCase();
+ let hasPath = last.length < path45.length;
+ let hasDot = ext.length < last.length - 1;
+ return (hasDot || !hasPath) && this._types[ext] || null;
+ };
+ Mime.prototype.getExtension = function(type) {
+ type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
+ return type && this._extensions[type.toLowerCase()] || null;
+ };
+ module2.exports = Mime;
+ }
+});
+
+// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js
+var require_standard = __commonJS({
+ "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/standard.js"(exports2, module2) {
+ init_import_meta_url();
+ module2.exports = { "application/andrew-inset": ["ez"], "application/applixware": ["aw"], "application/atom+xml": ["atom"], "application/atomcat+xml": ["atomcat"], "application/atomdeleted+xml": ["atomdeleted"], "application/atomsvc+xml": ["atomsvc"], "application/atsc-dwd+xml": ["dwd"], "application/atsc-held+xml": ["held"], "application/atsc-rsat+xml": ["rsat"], "application/bdoc": ["bdoc"], "application/calendar+xml": ["xcs"], "application/ccxml+xml": ["ccxml"], "application/cdfx+xml": ["cdfx"], "application/cdmi-capability": ["cdmia"], "application/cdmi-container": ["cdmic"], "application/cdmi-domain": ["cdmid"], "application/cdmi-object": ["cdmio"], "application/cdmi-queue": ["cdmiq"], "application/cu-seeme": ["cu"], "application/dash+xml": ["mpd"], "application/davmount+xml": ["davmount"], "application/docbook+xml": ["dbk"], "application/dssc+der": ["dssc"], "application/dssc+xml": ["xdssc"], "application/ecmascript": ["es", "ecma"], "application/emma+xml": ["emma"], "application/emotionml+xml": ["emotionml"], "application/epub+zip": ["epub"], "application/exi": ["exi"], "application/express": ["exp"], "application/fdt+xml": ["fdt"], "application/font-tdpfr": ["pfr"], "application/geo+json": ["geojson"], "application/gml+xml": ["gml"], "application/gpx+xml": ["gpx"], "application/gxf": ["gxf"], "application/gzip": ["gz"], "application/hjson": ["hjson"], "application/hyperstudio": ["stk"], "application/inkml+xml": ["ink", "inkml"], "application/ipfix": ["ipfix"], "application/its+xml": ["its"], "application/java-archive": ["jar", "war", "ear"], "application/java-serialized-object": ["ser"], "application/java-vm": ["class"], "application/javascript": ["js", "mjs"], "application/json": ["json", "map"], "application/json5": ["json5"], "application/jsonml+json": ["jsonml"], "application/ld+json": ["jsonld"], "application/lgr+xml": ["lgr"], "application/lost+xml": ["lostxml"], "application/mac-binhex40": ["hqx"], "application/mac-compactpro": ["cpt"], "application/mads+xml": ["mads"], "application/manifest+json": ["webmanifest"], "application/marc": ["mrc"], "application/marcxml+xml": ["mrcx"], "application/mathematica": ["ma", "nb", "mb"], "application/mathml+xml": ["mathml"], "application/mbox": ["mbox"], "application/mediaservercontrol+xml": ["mscml"], "application/metalink+xml": ["metalink"], "application/metalink4+xml": ["meta4"], "application/mets+xml": ["mets"], "application/mmt-aei+xml": ["maei"], "application/mmt-usd+xml": ["musd"], "application/mods+xml": ["mods"], "application/mp21": ["m21", "mp21"], "application/mp4": ["mp4s", "m4p"], "application/msword": ["doc", "dot"], "application/mxf": ["mxf"], "application/n-quads": ["nq"], "application/n-triples": ["nt"], "application/node": ["cjs"], "application/octet-stream": ["bin", "dms", "lrf", "mar", "so", "dist", "distz", "pkg", "bpk", "dump", "elc", "deploy", "exe", "dll", "deb", "dmg", "iso", "img", "msi", "msp", "msm", "buffer"], "application/oda": ["oda"], "application/oebps-package+xml": ["opf"], "application/ogg": ["ogx"], "application/omdoc+xml": ["omdoc"], "application/onenote": ["onetoc", "onetoc2", "onetmp", "onepkg"], "application/oxps": ["oxps"], "application/p2p-overlay+xml": ["relo"], "application/patch-ops-error+xml": ["xer"], "application/pdf": ["pdf"], "application/pgp-encrypted": ["pgp"], "application/pgp-signature": ["asc", "sig"], "application/pics-rules": ["prf"], "application/pkcs10": ["p10"], "application/pkcs7-mime": ["p7m", "p7c"], "application/pkcs7-signature": ["p7s"], "application/pkcs8": ["p8"], "application/pkix-attr-cert": ["ac"], "application/pkix-cert": ["cer"], "application/pkix-crl": ["crl"], "application/pkix-pkipath": ["pkipath"], "application/pkixcmp": ["pki"], "application/pls+xml": ["pls"], "application/postscript": ["ai", "eps", "ps"], "application/provenance+xml": ["provx"], "application/pskc+xml": ["pskcxml"], "application/raml+yaml": ["raml"], "application/rdf+xml": ["rdf", "owl"], "application/reginfo+xml": ["rif"], "application/relax-ng-compact-syntax": ["rnc"], "application/resource-lists+xml": ["rl"], "application/resource-lists-diff+xml": ["rld"], "application/rls-services+xml": ["rs"], "application/route-apd+xml": ["rapd"], "application/route-s-tsid+xml": ["sls"], "application/route-usd+xml": ["rusd"], "application/rpki-ghostbusters": ["gbr"], "application/rpki-manifest": ["mft"], "application/rpki-roa": ["roa"], "application/rsd+xml": ["rsd"], "application/rss+xml": ["rss"], "application/rtf": ["rtf"], "application/sbml+xml": ["sbml"], "application/scvp-cv-request": ["scq"], "application/scvp-cv-response": ["scs"], "application/scvp-vp-request": ["spq"], "application/scvp-vp-response": ["spp"], "application/sdp": ["sdp"], "application/senml+xml": ["senmlx"], "application/sensml+xml": ["sensmlx"], "application/set-payment-initiation": ["setpay"], "application/set-registration-initiation": ["setreg"], "application/shf+xml": ["shf"], "application/sieve": ["siv", "sieve"], "application/smil+xml": ["smi", "smil"], "application/sparql-query": ["rq"], "application/sparql-results+xml": ["srx"], "application/srgs": ["gram"], "application/srgs+xml": ["grxml"], "application/sru+xml": ["sru"], "application/ssdl+xml": ["ssdl"], "application/ssml+xml": ["ssml"], "application/swid+xml": ["swidtag"], "application/tei+xml": ["tei", "teicorpus"], "application/thraud+xml": ["tfi"], "application/timestamped-data": ["tsd"], "application/toml": ["toml"], "application/trig": ["trig"], "application/ttml+xml": ["ttml"], "application/ubjson": ["ubj"], "application/urc-ressheet+xml": ["rsheet"], "application/urc-targetdesc+xml": ["td"], "application/voicexml+xml": ["vxml"], "application/wasm": ["wasm"], "application/widget": ["wgt"], "application/winhlp": ["hlp"], "application/wsdl+xml": ["wsdl"], "application/wspolicy+xml": ["wspolicy"], "application/xaml+xml": ["xaml"], "application/xcap-att+xml": ["xav"], "application/xcap-caps+xml": ["xca"], "application/xcap-diff+xml": ["xdf"], "application/xcap-el+xml": ["xel"], "application/xcap-ns+xml": ["xns"], "application/xenc+xml": ["xenc"], "application/xhtml+xml": ["xhtml", "xht"], "application/xliff+xml": ["xlf"], "application/xml": ["xml", "xsl", "xsd", "rng"], "application/xml-dtd": ["dtd"], "application/xop+xml": ["xop"], "application/xproc+xml": ["xpl"], "application/xslt+xml": ["*xsl", "xslt"], "application/xspf+xml": ["xspf"], "application/xv+xml": ["mxml", "xhvml", "xvml", "xvm"], "application/yang": ["yang"], "application/yin+xml": ["yin"], "application/zip": ["zip"], "audio/3gpp": ["*3gpp"], "audio/adpcm": ["adp"], "audio/amr": ["amr"], "audio/basic": ["au", "snd"], "audio/midi": ["mid", "midi", "kar", "rmi"], "audio/mobile-xmf": ["mxmf"], "audio/mp3": ["*mp3"], "audio/mp4": ["m4a", "mp4a"], "audio/mpeg": ["mpga", "mp2", "mp2a", "mp3", "m2a", "m3a"], "audio/ogg": ["oga", "ogg", "spx", "opus"], "audio/s3m": ["s3m"], "audio/silk": ["sil"], "audio/wav": ["wav"], "audio/wave": ["*wav"], "audio/webm": ["weba"], "audio/xm": ["xm"], "font/collection": ["ttc"], "font/otf": ["otf"], "font/ttf": ["ttf"], "font/woff": ["woff"], "font/woff2": ["woff2"], "image/aces": ["exr"], "image/apng": ["apng"], "image/avif": ["avif"], "image/bmp": ["bmp"], "image/cgm": ["cgm"], "image/dicom-rle": ["drle"], "image/emf": ["emf"], "image/fits": ["fits"], "image/g3fax": ["g3"], "image/gif": ["gif"], "image/heic": ["heic"], "image/heic-sequence": ["heics"], "image/heif": ["heif"], "image/heif-sequence": ["heifs"], "image/hej2k": ["hej2"], "image/hsj2": ["hsj2"], "image/ief": ["ief"], "image/jls": ["jls"], "image/jp2": ["jp2", "jpg2"], "image/jpeg": ["jpeg", "jpg", "jpe"], "image/jph": ["jph"], "image/jphc": ["jhc"], "image/jpm": ["jpm"], "image/jpx": ["jpx", "jpf"], "image/jxr": ["jxr"], "image/jxra": ["jxra"], "image/jxrs": ["jxrs"], "image/jxs": ["jxs"], "image/jxsc": ["jxsc"], "image/jxsi": ["jxsi"], "image/jxss": ["jxss"], "image/ktx": ["ktx"], "image/ktx2": ["ktx2"], "image/png": ["png"], "image/sgi": ["sgi"], "image/svg+xml": ["svg", "svgz"], "image/t38": ["t38"], "image/tiff": ["tif", "tiff"], "image/tiff-fx": ["tfx"], "image/webp": ["webp"], "image/wmf": ["wmf"], "message/disposition-notification": ["disposition-notification"], "message/global": ["u8msg"], "message/global-delivery-status": ["u8dsn"], "message/global-disposition-notification": ["u8mdn"], "message/global-headers": ["u8hdr"], "message/rfc822": ["eml", "mime"], "model/3mf": ["3mf"], "model/gltf+json": ["gltf"], "model/gltf-binary": ["glb"], "model/iges": ["igs", "iges"], "model/mesh": ["msh", "mesh", "silo"], "model/mtl": ["mtl"], "model/obj": ["obj"], "model/step+xml": ["stpx"], "model/step+zip": ["stpz"], "model/step-xml+zip": ["stpxz"], "model/stl": ["stl"], "model/vrml": ["wrl", "vrml"], "model/x3d+binary": ["*x3db", "x3dbz"], "model/x3d+fastinfoset": ["x3db"], "model/x3d+vrml": ["*x3dv", "x3dvz"], "model/x3d+xml": ["x3d", "x3dz"], "model/x3d-vrml": ["x3dv"], "text/cache-manifest": ["appcache", "manifest"], "text/calendar": ["ics", "ifb"], "text/coffeescript": ["coffee", "litcoffee"], "text/css": ["css"], "text/csv": ["csv"], "text/html": ["html", "htm", "shtml"], "text/jade": ["jade"], "text/jsx": ["jsx"], "text/less": ["less"], "text/markdown": ["markdown", "md"], "text/mathml": ["mml"], "text/mdx": ["mdx"], "text/n3": ["n3"], "text/plain": ["txt", "text", "conf", "def", "list", "log", "in", "ini"], "text/richtext": ["rtx"], "text/rtf": ["*rtf"], "text/sgml": ["sgml", "sgm"], "text/shex": ["shex"], "text/slim": ["slim", "slm"], "text/spdx": ["spdx"], "text/stylus": ["stylus", "styl"], "text/tab-separated-values": ["tsv"], "text/troff": ["t", "tr", "roff", "man", "me", "ms"], "text/turtle": ["ttl"], "text/uri-list": ["uri", "uris", "urls"], "text/vcard": ["vcard"], "text/vtt": ["vtt"], "text/xml": ["*xml"], "text/yaml": ["yaml", "yml"], "video/3gpp": ["3gp", "3gpp"], "video/3gpp2": ["3g2"], "video/h261": ["h261"], "video/h263": ["h263"], "video/h264": ["h264"], "video/iso.segment": ["m4s"], "video/jpeg": ["jpgv"], "video/jpm": ["*jpm", "jpgm"], "video/mj2": ["mj2", "mjp2"], "video/mp2t": ["ts"], "video/mp4": ["mp4", "mp4v", "mpg4"], "video/mpeg": ["mpeg", "mpg", "mpe", "m1v", "m2v"], "video/ogg": ["ogv"], "video/quicktime": ["qt", "mov"], "video/webm": ["webm"] };
+ }
+});
+
+// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js
+var require_other = __commonJS({
+ "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/types/other.js"(exports2, module2) {
+ init_import_meta_url();
+ module2.exports = { "application/prs.cww": ["cww"], "application/vnd.1000minds.decision-model+xml": ["1km"], "application/vnd.3gpp.pic-bw-large": ["plb"], "application/vnd.3gpp.pic-bw-small": ["psb"], "application/vnd.3gpp.pic-bw-var": ["pvb"], "application/vnd.3gpp2.tcap": ["tcap"], "application/vnd.3m.post-it-notes": ["pwn"], "application/vnd.accpac.simply.aso": ["aso"], "application/vnd.accpac.simply.imp": ["imp"], "application/vnd.acucobol": ["acu"], "application/vnd.acucorp": ["atc", "acutc"], "application/vnd.adobe.air-application-installer-package+zip": ["air"], "application/vnd.adobe.formscentral.fcdt": ["fcdt"], "application/vnd.adobe.fxp": ["fxp", "fxpl"], "application/vnd.adobe.xdp+xml": ["xdp"], "application/vnd.adobe.xfdf": ["xfdf"], "application/vnd.ahead.space": ["ahead"], "application/vnd.airzip.filesecure.azf": ["azf"], "application/vnd.airzip.filesecure.azs": ["azs"], "application/vnd.amazon.ebook": ["azw"], "application/vnd.americandynamics.acc": ["acc"], "application/vnd.amiga.ami": ["ami"], "application/vnd.android.package-archive": ["apk"], "application/vnd.anser-web-certificate-issue-initiation": ["cii"], "application/vnd.anser-web-funds-transfer-initiation": ["fti"], "application/vnd.antix.game-component": ["atx"], "application/vnd.apple.installer+xml": ["mpkg"], "application/vnd.apple.keynote": ["key"], "application/vnd.apple.mpegurl": ["m3u8"], "application/vnd.apple.numbers": ["numbers"], "application/vnd.apple.pages": ["pages"], "application/vnd.apple.pkpass": ["pkpass"], "application/vnd.aristanetworks.swi": ["swi"], "application/vnd.astraea-software.iota": ["iota"], "application/vnd.audiograph": ["aep"], "application/vnd.balsamiq.bmml+xml": ["bmml"], "application/vnd.blueice.multipass": ["mpm"], "application/vnd.bmi": ["bmi"], "application/vnd.businessobjects": ["rep"], "application/vnd.chemdraw+xml": ["cdxml"], "application/vnd.chipnuts.karaoke-mmd": ["mmd"], "application/vnd.cinderella": ["cdy"], "application/vnd.citationstyles.style+xml": ["csl"], "application/vnd.claymore": ["cla"], "application/vnd.cloanto.rp9": ["rp9"], "application/vnd.clonk.c4group": ["c4g", "c4d", "c4f", "c4p", "c4u"], "application/vnd.cluetrust.cartomobile-config": ["c11amc"], "application/vnd.cluetrust.cartomobile-config-pkg": ["c11amz"], "application/vnd.commonspace": ["csp"], "application/vnd.contact.cmsg": ["cdbcmsg"], "application/vnd.cosmocaller": ["cmc"], "application/vnd.crick.clicker": ["clkx"], "application/vnd.crick.clicker.keyboard": ["clkk"], "application/vnd.crick.clicker.palette": ["clkp"], "application/vnd.crick.clicker.template": ["clkt"], "application/vnd.crick.clicker.wordbank": ["clkw"], "application/vnd.criticaltools.wbs+xml": ["wbs"], "application/vnd.ctc-posml": ["pml"], "application/vnd.cups-ppd": ["ppd"], "application/vnd.curl.car": ["car"], "application/vnd.curl.pcurl": ["pcurl"], "application/vnd.dart": ["dart"], "application/vnd.data-vision.rdz": ["rdz"], "application/vnd.dbf": ["dbf"], "application/vnd.dece.data": ["uvf", "uvvf", "uvd", "uvvd"], "application/vnd.dece.ttml+xml": ["uvt", "uvvt"], "application/vnd.dece.unspecified": ["uvx", "uvvx"], "application/vnd.dece.zip": ["uvz", "uvvz"], "application/vnd.denovo.fcselayout-link": ["fe_launch"], "application/vnd.dna": ["dna"], "application/vnd.dolby.mlp": ["mlp"], "application/vnd.dpgraph": ["dpg"], "application/vnd.dreamfactory": ["dfac"], "application/vnd.ds-keypoint": ["kpxx"], "application/vnd.dvb.ait": ["ait"], "application/vnd.dvb.service": ["svc"], "application/vnd.dynageo": ["geo"], "application/vnd.ecowin.chart": ["mag"], "application/vnd.enliven": ["nml"], "application/vnd.epson.esf": ["esf"], "application/vnd.epson.msf": ["msf"], "application/vnd.epson.quickanime": ["qam"], "application/vnd.epson.salt": ["slt"], "application/vnd.epson.ssf": ["ssf"], "application/vnd.eszigno3+xml": ["es3", "et3"], "application/vnd.ezpix-album": ["ez2"], "application/vnd.ezpix-package": ["ez3"], "application/vnd.fdf": ["fdf"], "application/vnd.fdsn.mseed": ["mseed"], "application/vnd.fdsn.seed": ["seed", "dataless"], "application/vnd.flographit": ["gph"], "application/vnd.fluxtime.clip": ["ftc"], "application/vnd.framemaker": ["fm", "frame", "maker", "book"], "application/vnd.frogans.fnc": ["fnc"], "application/vnd.frogans.ltf": ["ltf"], "application/vnd.fsc.weblaunch": ["fsc"], "application/vnd.fujitsu.oasys": ["oas"], "application/vnd.fujitsu.oasys2": ["oa2"], "application/vnd.fujitsu.oasys3": ["oa3"], "application/vnd.fujitsu.oasysgp": ["fg5"], "application/vnd.fujitsu.oasysprs": ["bh2"], "application/vnd.fujixerox.ddd": ["ddd"], "application/vnd.fujixerox.docuworks": ["xdw"], "application/vnd.fujixerox.docuworks.binder": ["xbd"], "application/vnd.fuzzysheet": ["fzs"], "application/vnd.genomatix.tuxedo": ["txd"], "application/vnd.geogebra.file": ["ggb"], "application/vnd.geogebra.tool": ["ggt"], "application/vnd.geometry-explorer": ["gex", "gre"], "application/vnd.geonext": ["gxt"], "application/vnd.geoplan": ["g2w"], "application/vnd.geospace": ["g3w"], "application/vnd.gmx": ["gmx"], "application/vnd.google-apps.document": ["gdoc"], "application/vnd.google-apps.presentation": ["gslides"], "application/vnd.google-apps.spreadsheet": ["gsheet"], "application/vnd.google-earth.kml+xml": ["kml"], "application/vnd.google-earth.kmz": ["kmz"], "application/vnd.grafeq": ["gqf", "gqs"], "application/vnd.groove-account": ["gac"], "application/vnd.groove-help": ["ghf"], "application/vnd.groove-identity-message": ["gim"], "application/vnd.groove-injector": ["grv"], "application/vnd.groove-tool-message": ["gtm"], "application/vnd.groove-tool-template": ["tpl"], "application/vnd.groove-vcard": ["vcg"], "application/vnd.hal+xml": ["hal"], "application/vnd.handheld-entertainment+xml": ["zmm"], "application/vnd.hbci": ["hbci"], "application/vnd.hhe.lesson-player": ["les"], "application/vnd.hp-hpgl": ["hpgl"], "application/vnd.hp-hpid": ["hpid"], "application/vnd.hp-hps": ["hps"], "application/vnd.hp-jlyt": ["jlt"], "application/vnd.hp-pcl": ["pcl"], "application/vnd.hp-pclxl": ["pclxl"], "application/vnd.hydrostatix.sof-data": ["sfd-hdstx"], "application/vnd.ibm.minipay": ["mpy"], "application/vnd.ibm.modcap": ["afp", "listafp", "list3820"], "application/vnd.ibm.rights-management": ["irm"], "application/vnd.ibm.secure-container": ["sc"], "application/vnd.iccprofile": ["icc", "icm"], "application/vnd.igloader": ["igl"], "application/vnd.immervision-ivp": ["ivp"], "application/vnd.immervision-ivu": ["ivu"], "application/vnd.insors.igm": ["igm"], "application/vnd.intercon.formnet": ["xpw", "xpx"], "application/vnd.intergeo": ["i2g"], "application/vnd.intu.qbo": ["qbo"], "application/vnd.intu.qfx": ["qfx"], "application/vnd.ipunplugged.rcprofile": ["rcprofile"], "application/vnd.irepository.package+xml": ["irp"], "application/vnd.is-xpr": ["xpr"], "application/vnd.isac.fcs": ["fcs"], "application/vnd.jam": ["jam"], "application/vnd.jcp.javame.midlet-rms": ["rms"], "application/vnd.jisp": ["jisp"], "application/vnd.joost.joda-archive": ["joda"], "application/vnd.kahootz": ["ktz", "ktr"], "application/vnd.kde.karbon": ["karbon"], "application/vnd.kde.kchart": ["chrt"], "application/vnd.kde.kformula": ["kfo"], "application/vnd.kde.kivio": ["flw"], "application/vnd.kde.kontour": ["kon"], "application/vnd.kde.kpresenter": ["kpr", "kpt"], "application/vnd.kde.kspread": ["ksp"], "application/vnd.kde.kword": ["kwd", "kwt"], "application/vnd.kenameaapp": ["htke"], "application/vnd.kidspiration": ["kia"], "application/vnd.kinar": ["kne", "knp"], "application/vnd.koan": ["skp", "skd", "skt", "skm"], "application/vnd.kodak-descriptor": ["sse"], "application/vnd.las.las+xml": ["lasxml"], "application/vnd.llamagraphics.life-balance.desktop": ["lbd"], "application/vnd.llamagraphics.life-balance.exchange+xml": ["lbe"], "application/vnd.lotus-1-2-3": ["123"], "application/vnd.lotus-approach": ["apr"], "application/vnd.lotus-freelance": ["pre"], "application/vnd.lotus-notes": ["nsf"], "application/vnd.lotus-organizer": ["org"], "application/vnd.lotus-screencam": ["scm"], "application/vnd.lotus-wordpro": ["lwp"], "application/vnd.macports.portpkg": ["portpkg"], "application/vnd.mapbox-vector-tile": ["mvt"], "application/vnd.mcd": ["mcd"], "application/vnd.medcalcdata": ["mc1"], "application/vnd.mediastation.cdkey": ["cdkey"], "application/vnd.mfer": ["mwf"], "application/vnd.mfmp": ["mfm"], "application/vnd.micrografx.flo": ["flo"], "application/vnd.micrografx.igx": ["igx"], "application/vnd.mif": ["mif"], "application/vnd.mobius.daf": ["daf"], "application/vnd.mobius.dis": ["dis"], "application/vnd.mobius.mbk": ["mbk"], "application/vnd.mobius.mqy": ["mqy"], "application/vnd.mobius.msl": ["msl"], "application/vnd.mobius.plc": ["plc"], "application/vnd.mobius.txf": ["txf"], "application/vnd.mophun.application": ["mpn"], "application/vnd.mophun.certificate": ["mpc"], "application/vnd.mozilla.xul+xml": ["xul"], "application/vnd.ms-artgalry": ["cil"], "application/vnd.ms-cab-compressed": ["cab"], "application/vnd.ms-excel": ["xls", "xlm", "xla", "xlc", "xlt", "xlw"], "application/vnd.ms-excel.addin.macroenabled.12": ["xlam"], "application/vnd.ms-excel.sheet.binary.macroenabled.12": ["xlsb"], "application/vnd.ms-excel.sheet.macroenabled.12": ["xlsm"], "application/vnd.ms-excel.template.macroenabled.12": ["xltm"], "application/vnd.ms-fontobject": ["eot"], "application/vnd.ms-htmlhelp": ["chm"], "application/vnd.ms-ims": ["ims"], "application/vnd.ms-lrm": ["lrm"], "application/vnd.ms-officetheme": ["thmx"], "application/vnd.ms-outlook": ["msg"], "application/vnd.ms-pki.seccat": ["cat"], "application/vnd.ms-pki.stl": ["*stl"], "application/vnd.ms-powerpoint": ["ppt", "pps", "pot"], "application/vnd.ms-powerpoint.addin.macroenabled.12": ["ppam"], "application/vnd.ms-powerpoint.presentation.macroenabled.12": ["pptm"], "application/vnd.ms-powerpoint.slide.macroenabled.12": ["sldm"], "application/vnd.ms-powerpoint.slideshow.macroenabled.12": ["ppsm"], "application/vnd.ms-powerpoint.template.macroenabled.12": ["potm"], "application/vnd.ms-project": ["mpp", "mpt"], "application/vnd.ms-word.document.macroenabled.12": ["docm"], "application/vnd.ms-word.template.macroenabled.12": ["dotm"], "application/vnd.ms-works": ["wps", "wks", "wcm", "wdb"], "application/vnd.ms-wpl": ["wpl"], "application/vnd.ms-xpsdocument": ["xps"], "application/vnd.mseq": ["mseq"], "application/vnd.musician": ["mus"], "application/vnd.muvee.style": ["msty"], "application/vnd.mynfc": ["taglet"], "application/vnd.neurolanguage.nlu": ["nlu"], "application/vnd.nitf": ["ntf", "nitf"], "application/vnd.noblenet-directory": ["nnd"], "application/vnd.noblenet-sealer": ["nns"], "application/vnd.noblenet-web": ["nnw"], "application/vnd.nokia.n-gage.ac+xml": ["*ac"], "application/vnd.nokia.n-gage.data": ["ngdat"], "application/vnd.nokia.n-gage.symbian.install": ["n-gage"], "application/vnd.nokia.radio-preset": ["rpst"], "application/vnd.nokia.radio-presets": ["rpss"], "application/vnd.novadigm.edm": ["edm"], "application/vnd.novadigm.edx": ["edx"], "application/vnd.novadigm.ext": ["ext"], "application/vnd.oasis.opendocument.chart": ["odc"], "application/vnd.oasis.opendocument.chart-template": ["otc"], "application/vnd.oasis.opendocument.database": ["odb"], "application/vnd.oasis.opendocument.formula": ["odf"], "application/vnd.oasis.opendocument.formula-template": ["odft"], "application/vnd.oasis.opendocument.graphics": ["odg"], "application/vnd.oasis.opendocument.graphics-template": ["otg"], "application/vnd.oasis.opendocument.image": ["odi"], "application/vnd.oasis.opendocument.image-template": ["oti"], "application/vnd.oasis.opendocument.presentation": ["odp"], "application/vnd.oasis.opendocument.presentation-template": ["otp"], "application/vnd.oasis.opendocument.spreadsheet": ["ods"], "application/vnd.oasis.opendocument.spreadsheet-template": ["ots"], "application/vnd.oasis.opendocument.text": ["odt"], "application/vnd.oasis.opendocument.text-master": ["odm"], "application/vnd.oasis.opendocument.text-template": ["ott"], "application/vnd.oasis.opendocument.text-web": ["oth"], "application/vnd.olpc-sugar": ["xo"], "application/vnd.oma.dd2+xml": ["dd2"], "application/vnd.openblox.game+xml": ["obgx"], "application/vnd.openofficeorg.extension": ["oxt"], "application/vnd.openstreetmap.data+xml": ["osm"], "application/vnd.openxmlformats-officedocument.presentationml.presentation": ["pptx"], "application/vnd.openxmlformats-officedocument.presentationml.slide": ["sldx"], "application/vnd.openxmlformats-officedocument.presentationml.slideshow": ["ppsx"], "application/vnd.openxmlformats-officedocument.presentationml.template": ["potx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": ["xlsx"], "application/vnd.openxmlformats-officedocument.spreadsheetml.template": ["xltx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.document": ["docx"], "application/vnd.openxmlformats-officedocument.wordprocessingml.template": ["dotx"], "application/vnd.osgeo.mapguide.package": ["mgp"], "application/vnd.osgi.dp": ["dp"], "application/vnd.osgi.subsystem": ["esa"], "application/vnd.palm": ["pdb", "pqa", "oprc"], "application/vnd.pawaafile": ["paw"], "application/vnd.pg.format": ["str"], "application/vnd.pg.osasli": ["ei6"], "application/vnd.picsel": ["efif"], "application/vnd.pmi.widget": ["wg"], "application/vnd.pocketlearn": ["plf"], "application/vnd.powerbuilder6": ["pbd"], "application/vnd.previewsystems.box": ["box"], "application/vnd.proteus.magazine": ["mgz"], "application/vnd.publishare-delta-tree": ["qps"], "application/vnd.pvi.ptid1": ["ptid"], "application/vnd.quark.quarkxpress": ["qxd", "qxt", "qwd", "qwt", "qxl", "qxb"], "application/vnd.rar": ["rar"], "application/vnd.realvnc.bed": ["bed"], "application/vnd.recordare.musicxml": ["mxl"], "application/vnd.recordare.musicxml+xml": ["musicxml"], "application/vnd.rig.cryptonote": ["cryptonote"], "application/vnd.rim.cod": ["cod"], "application/vnd.rn-realmedia": ["rm"], "application/vnd.rn-realmedia-vbr": ["rmvb"], "application/vnd.route66.link66+xml": ["link66"], "application/vnd.sailingtracker.track": ["st"], "application/vnd.seemail": ["see"], "application/vnd.sema": ["sema"], "application/vnd.semd": ["semd"], "application/vnd.semf": ["semf"], "application/vnd.shana.informed.formdata": ["ifm"], "application/vnd.shana.informed.formtemplate": ["itp"], "application/vnd.shana.informed.interchange": ["iif"], "application/vnd.shana.informed.package": ["ipk"], "application/vnd.simtech-mindmapper": ["twd", "twds"], "application/vnd.smaf": ["mmf"], "application/vnd.smart.teacher": ["teacher"], "application/vnd.software602.filler.form+xml": ["fo"], "application/vnd.solent.sdkm+xml": ["sdkm", "sdkd"], "application/vnd.spotfire.dxp": ["dxp"], "application/vnd.spotfire.sfs": ["sfs"], "application/vnd.stardivision.calc": ["sdc"], "application/vnd.stardivision.draw": ["sda"], "application/vnd.stardivision.impress": ["sdd"], "application/vnd.stardivision.math": ["smf"], "application/vnd.stardivision.writer": ["sdw", "vor"], "application/vnd.stardivision.writer-global": ["sgl"], "application/vnd.stepmania.package": ["smzip"], "application/vnd.stepmania.stepchart": ["sm"], "application/vnd.sun.wadl+xml": ["wadl"], "application/vnd.sun.xml.calc": ["sxc"], "application/vnd.sun.xml.calc.template": ["stc"], "application/vnd.sun.xml.draw": ["sxd"], "application/vnd.sun.xml.draw.template": ["std"], "application/vnd.sun.xml.impress": ["sxi"], "application/vnd.sun.xml.impress.template": ["sti"], "application/vnd.sun.xml.math": ["sxm"], "application/vnd.sun.xml.writer": ["sxw"], "application/vnd.sun.xml.writer.global": ["sxg"], "application/vnd.sun.xml.writer.template": ["stw"], "application/vnd.sus-calendar": ["sus", "susp"], "application/vnd.svd": ["svd"], "application/vnd.symbian.install": ["sis", "sisx"], "application/vnd.syncml+xml": ["xsm"], "application/vnd.syncml.dm+wbxml": ["bdm"], "application/vnd.syncml.dm+xml": ["xdm"], "application/vnd.syncml.dmddf+xml": ["ddf"], "application/vnd.tao.intent-module-archive": ["tao"], "application/vnd.tcpdump.pcap": ["pcap", "cap", "dmp"], "application/vnd.tmobile-livetv": ["tmo"], "application/vnd.trid.tpt": ["tpt"], "application/vnd.triscape.mxs": ["mxs"], "application/vnd.trueapp": ["tra"], "application/vnd.ufdl": ["ufd", "ufdl"], "application/vnd.uiq.theme": ["utz"], "application/vnd.umajin": ["umj"], "application/vnd.unity": ["unityweb"], "application/vnd.uoml+xml": ["uoml"], "application/vnd.vcx": ["vcx"], "application/vnd.visio": ["vsd", "vst", "vss", "vsw"], "application/vnd.visionary": ["vis"], "application/vnd.vsf": ["vsf"], "application/vnd.wap.wbxml": ["wbxml"], "application/vnd.wap.wmlc": ["wmlc"], "application/vnd.wap.wmlscriptc": ["wmlsc"], "application/vnd.webturbo": ["wtb"], "application/vnd.wolfram.player": ["nbp"], "application/vnd.wordperfect": ["wpd"], "application/vnd.wqd": ["wqd"], "application/vnd.wt.stf": ["stf"], "application/vnd.xara": ["xar"], "application/vnd.xfdl": ["xfdl"], "application/vnd.yamaha.hv-dic": ["hvd"], "application/vnd.yamaha.hv-script": ["hvs"], "application/vnd.yamaha.hv-voice": ["hvp"], "application/vnd.yamaha.openscoreformat": ["osf"], "application/vnd.yamaha.openscoreformat.osfpvg+xml": ["osfpvg"], "application/vnd.yamaha.smaf-audio": ["saf"], "application/vnd.yamaha.smaf-phrase": ["spf"], "application/vnd.yellowriver-custom-menu": ["cmp"], "application/vnd.zul": ["zir", "zirz"], "application/vnd.zzazz.deck+xml": ["zaz"], "application/x-7z-compressed": ["7z"], "application/x-abiword": ["abw"], "application/x-ace-compressed": ["ace"], "application/x-apple-diskimage": ["*dmg"], "application/x-arj": ["arj"], "application/x-authorware-bin": ["aab", "x32", "u32", "vox"], "application/x-authorware-map": ["aam"], "application/x-authorware-seg": ["aas"], "application/x-bcpio": ["bcpio"], "application/x-bdoc": ["*bdoc"], "application/x-bittorrent": ["torrent"], "application/x-blorb": ["blb", "blorb"], "application/x-bzip": ["bz"], "application/x-bzip2": ["bz2", "boz"], "application/x-cbr": ["cbr", "cba", "cbt", "cbz", "cb7"], "application/x-cdlink": ["vcd"], "application/x-cfs-compressed": ["cfs"], "application/x-chat": ["chat"], "application/x-chess-pgn": ["pgn"], "application/x-chrome-extension": ["crx"], "application/x-cocoa": ["cco"], "application/x-conference": ["nsc"], "application/x-cpio": ["cpio"], "application/x-csh": ["csh"], "application/x-debian-package": ["*deb", "udeb"], "application/x-dgc-compressed": ["dgc"], "application/x-director": ["dir", "dcr", "dxr", "cst", "cct", "cxt", "w3d", "fgd", "swa"], "application/x-doom": ["wad"], "application/x-dtbncx+xml": ["ncx"], "application/x-dtbook+xml": ["dtb"], "application/x-dtbresource+xml": ["res"], "application/x-dvi": ["dvi"], "application/x-envoy": ["evy"], "application/x-eva": ["eva"], "application/x-font-bdf": ["bdf"], "application/x-font-ghostscript": ["gsf"], "application/x-font-linux-psf": ["psf"], "application/x-font-pcf": ["pcf"], "application/x-font-snf": ["snf"], "application/x-font-type1": ["pfa", "pfb", "pfm", "afm"], "application/x-freearc": ["arc"], "application/x-futuresplash": ["spl"], "application/x-gca-compressed": ["gca"], "application/x-glulx": ["ulx"], "application/x-gnumeric": ["gnumeric"], "application/x-gramps-xml": ["gramps"], "application/x-gtar": ["gtar"], "application/x-hdf": ["hdf"], "application/x-httpd-php": ["php"], "application/x-install-instructions": ["install"], "application/x-iso9660-image": ["*iso"], "application/x-iwork-keynote-sffkey": ["*key"], "application/x-iwork-numbers-sffnumbers": ["*numbers"], "application/x-iwork-pages-sffpages": ["*pages"], "application/x-java-archive-diff": ["jardiff"], "application/x-java-jnlp-file": ["jnlp"], "application/x-keepass2": ["kdbx"], "application/x-latex": ["latex"], "application/x-lua-bytecode": ["luac"], "application/x-lzh-compressed": ["lzh", "lha"], "application/x-makeself": ["run"], "application/x-mie": ["mie"], "application/x-mobipocket-ebook": ["prc", "mobi"], "application/x-ms-application": ["application"], "application/x-ms-shortcut": ["lnk"], "application/x-ms-wmd": ["wmd"], "application/x-ms-wmz": ["wmz"], "application/x-ms-xbap": ["xbap"], "application/x-msaccess": ["mdb"], "application/x-msbinder": ["obd"], "application/x-mscardfile": ["crd"], "application/x-msclip": ["clp"], "application/x-msdos-program": ["*exe"], "application/x-msdownload": ["*exe", "*dll", "com", "bat", "*msi"], "application/x-msmediaview": ["mvb", "m13", "m14"], "application/x-msmetafile": ["*wmf", "*wmz", "*emf", "emz"], "application/x-msmoney": ["mny"], "application/x-mspublisher": ["pub"], "application/x-msschedule": ["scd"], "application/x-msterminal": ["trm"], "application/x-mswrite": ["wri"], "application/x-netcdf": ["nc", "cdf"], "application/x-ns-proxy-autoconfig": ["pac"], "application/x-nzb": ["nzb"], "application/x-perl": ["pl", "pm"], "application/x-pilot": ["*prc", "*pdb"], "application/x-pkcs12": ["p12", "pfx"], "application/x-pkcs7-certificates": ["p7b", "spc"], "application/x-pkcs7-certreqresp": ["p7r"], "application/x-rar-compressed": ["*rar"], "application/x-redhat-package-manager": ["rpm"], "application/x-research-info-systems": ["ris"], "application/x-sea": ["sea"], "application/x-sh": ["sh"], "application/x-shar": ["shar"], "application/x-shockwave-flash": ["swf"], "application/x-silverlight-app": ["xap"], "application/x-sql": ["sql"], "application/x-stuffit": ["sit"], "application/x-stuffitx": ["sitx"], "application/x-subrip": ["srt"], "application/x-sv4cpio": ["sv4cpio"], "application/x-sv4crc": ["sv4crc"], "application/x-t3vm-image": ["t3"], "application/x-tads": ["gam"], "application/x-tar": ["tar"], "application/x-tcl": ["tcl", "tk"], "application/x-tex": ["tex"], "application/x-tex-tfm": ["tfm"], "application/x-texinfo": ["texinfo", "texi"], "application/x-tgif": ["*obj"], "application/x-ustar": ["ustar"], "application/x-virtualbox-hdd": ["hdd"], "application/x-virtualbox-ova": ["ova"], "application/x-virtualbox-ovf": ["ovf"], "application/x-virtualbox-vbox": ["vbox"], "application/x-virtualbox-vbox-extpack": ["vbox-extpack"], "application/x-virtualbox-vdi": ["vdi"], "application/x-virtualbox-vhd": ["vhd"], "application/x-virtualbox-vmdk": ["vmdk"], "application/x-wais-source": ["src"], "application/x-web-app-manifest+json": ["webapp"], "application/x-x509-ca-cert": ["der", "crt", "pem"], "application/x-xfig": ["fig"], "application/x-xliff+xml": ["*xlf"], "application/x-xpinstall": ["xpi"], "application/x-xz": ["xz"], "application/x-zmachine": ["z1", "z2", "z3", "z4", "z5", "z6", "z7", "z8"], "audio/vnd.dece.audio": ["uva", "uvva"], "audio/vnd.digital-winds": ["eol"], "audio/vnd.dra": ["dra"], "audio/vnd.dts": ["dts"], "audio/vnd.dts.hd": ["dtshd"], "audio/vnd.lucent.voice": ["lvp"], "audio/vnd.ms-playready.media.pya": ["pya"], "audio/vnd.nuera.ecelp4800": ["ecelp4800"], "audio/vnd.nuera.ecelp7470": ["ecelp7470"], "audio/vnd.nuera.ecelp9600": ["ecelp9600"], "audio/vnd.rip": ["rip"], "audio/x-aac": ["aac"], "audio/x-aiff": ["aif", "aiff", "aifc"], "audio/x-caf": ["caf"], "audio/x-flac": ["flac"], "audio/x-m4a": ["*m4a"], "audio/x-matroska": ["mka"], "audio/x-mpegurl": ["m3u"], "audio/x-ms-wax": ["wax"], "audio/x-ms-wma": ["wma"], "audio/x-pn-realaudio": ["ram", "ra"], "audio/x-pn-realaudio-plugin": ["rmp"], "audio/x-realaudio": ["*ra"], "audio/x-wav": ["*wav"], "chemical/x-cdx": ["cdx"], "chemical/x-cif": ["cif"], "chemical/x-cmdf": ["cmdf"], "chemical/x-cml": ["cml"], "chemical/x-csml": ["csml"], "chemical/x-xyz": ["xyz"], "image/prs.btif": ["btif"], "image/prs.pti": ["pti"], "image/vnd.adobe.photoshop": ["psd"], "image/vnd.airzip.accelerator.azv": ["azv"], "image/vnd.dece.graphic": ["uvi", "uvvi", "uvg", "uvvg"], "image/vnd.djvu": ["djvu", "djv"], "image/vnd.dvb.subtitle": ["*sub"], "image/vnd.dwg": ["dwg"], "image/vnd.dxf": ["dxf"], "image/vnd.fastbidsheet": ["fbs"], "image/vnd.fpx": ["fpx"], "image/vnd.fst": ["fst"], "image/vnd.fujixerox.edmics-mmr": ["mmr"], "image/vnd.fujixerox.edmics-rlc": ["rlc"], "image/vnd.microsoft.icon": ["ico"], "image/vnd.ms-dds": ["dds"], "image/vnd.ms-modi": ["mdi"], "image/vnd.ms-photo": ["wdp"], "image/vnd.net-fpx": ["npx"], "image/vnd.pco.b16": ["b16"], "image/vnd.tencent.tap": ["tap"], "image/vnd.valve.source.texture": ["vtf"], "image/vnd.wap.wbmp": ["wbmp"], "image/vnd.xiff": ["xif"], "image/vnd.zbrush.pcx": ["pcx"], "image/x-3ds": ["3ds"], "image/x-cmu-raster": ["ras"], "image/x-cmx": ["cmx"], "image/x-freehand": ["fh", "fhc", "fh4", "fh5", "fh7"], "image/x-icon": ["*ico"], "image/x-jng": ["jng"], "image/x-mrsid-image": ["sid"], "image/x-ms-bmp": ["*bmp"], "image/x-pcx": ["*pcx"], "image/x-pict": ["pic", "pct"], "image/x-portable-anymap": ["pnm"], "image/x-portable-bitmap": ["pbm"], "image/x-portable-graymap": ["pgm"], "image/x-portable-pixmap": ["ppm"], "image/x-rgb": ["rgb"], "image/x-tga": ["tga"], "image/x-xbitmap": ["xbm"], "image/x-xpixmap": ["xpm"], "image/x-xwindowdump": ["xwd"], "message/vnd.wfa.wsc": ["wsc"], "model/vnd.collada+xml": ["dae"], "model/vnd.dwf": ["dwf"], "model/vnd.gdl": ["gdl"], "model/vnd.gtw": ["gtw"], "model/vnd.mts": ["mts"], "model/vnd.opengex": ["ogex"], "model/vnd.parasolid.transmit.binary": ["x_b"], "model/vnd.parasolid.transmit.text": ["x_t"], "model/vnd.sap.vds": ["vds"], "model/vnd.usdz+zip": ["usdz"], "model/vnd.valve.source.compiled-map": ["bsp"], "model/vnd.vtu": ["vtu"], "text/prs.lines.tag": ["dsc"], "text/vnd.curl": ["curl"], "text/vnd.curl.dcurl": ["dcurl"], "text/vnd.curl.mcurl": ["mcurl"], "text/vnd.curl.scurl": ["scurl"], "text/vnd.dvb.subtitle": ["sub"], "text/vnd.fly": ["fly"], "text/vnd.fmi.flexstor": ["flx"], "text/vnd.graphviz": ["gv"], "text/vnd.in3d.3dml": ["3dml"], "text/vnd.in3d.spot": ["spot"], "text/vnd.sun.j2me.app-descriptor": ["jad"], "text/vnd.wap.wml": ["wml"], "text/vnd.wap.wmlscript": ["wmls"], "text/x-asm": ["s", "asm"], "text/x-c": ["c", "cc", "cxx", "cpp", "h", "hh", "dic"], "text/x-component": ["htc"], "text/x-fortran": ["f", "for", "f77", "f90"], "text/x-handlebars-template": ["hbs"], "text/x-java-source": ["java"], "text/x-lua": ["lua"], "text/x-markdown": ["mkd"], "text/x-nfo": ["nfo"], "text/x-opml": ["opml"], "text/x-org": ["*org"], "text/x-pascal": ["p", "pas"], "text/x-processing": ["pde"], "text/x-sass": ["sass"], "text/x-scss": ["scss"], "text/x-setext": ["etx"], "text/x-sfv": ["sfv"], "text/x-suse-ymp": ["ymp"], "text/x-uuencode": ["uu"], "text/x-vcalendar": ["vcs"], "text/x-vcard": ["vcf"], "video/vnd.dece.hd": ["uvh", "uvvh"], "video/vnd.dece.mobile": ["uvm", "uvvm"], "video/vnd.dece.pd": ["uvp", "uvvp"], "video/vnd.dece.sd": ["uvs", "uvvs"], "video/vnd.dece.video": ["uvv", "uvvv"], "video/vnd.dvb.file": ["dvb"], "video/vnd.fvt": ["fvt"], "video/vnd.mpegurl": ["mxu", "m4u"], "video/vnd.ms-playready.media.pyv": ["pyv"], "video/vnd.uvvu.mp4": ["uvu", "uvvu"], "video/vnd.vivo": ["viv"], "video/x-f4v": ["f4v"], "video/x-fli": ["fli"], "video/x-flv": ["flv"], "video/x-m4v": ["m4v"], "video/x-matroska": ["mkv", "mk3d", "mks"], "video/x-mng": ["mng"], "video/x-ms-asf": ["asf", "asx"], "video/x-ms-vob": ["vob"], "video/x-ms-wm": ["wm"], "video/x-ms-wmv": ["wmv"], "video/x-ms-wmx": ["wmx"], "video/x-ms-wvx": ["wvx"], "video/x-msvideo": ["avi"], "video/x-sgi-movie": ["movie"], "video/x-smv": ["smv"], "x-conference/x-cooltalk": ["ice"] };
+ }
+});
+
+// ../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js
+var require_mime2 = __commonJS({
+ "../../node_modules/.pnpm/mime@3.0.0/node_modules/mime/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var Mime = require_Mime();
+ module2.exports = new Mime(require_standard(), require_other());
+ }
+});
+
+// src/pages/hash.ts
+var import_node_fs7, import_node_path18, import_blake3_wasm, hashFile;
+var init_hash = __esm({
+ "src/pages/hash.ts"() {
+ init_import_meta_url();
+ import_node_fs7 = require("node:fs");
+ import_node_path18 = require("node:path");
+ import_blake3_wasm = require("blake3-wasm");
+ hashFile = /* @__PURE__ */ __name((filepath) => {
+ const contents = (0, import_node_fs7.readFileSync)(filepath);
+ const base64Contents = contents.toString("base64");
+ const extension = (0, import_node_path18.extname)(filepath).substring(1);
+ return (0, import_blake3_wasm.hash)(base64Contents + extension).toString("hex").slice(0, 32);
+ }, "hashFile");
+ }
+});
+
+// ../pages-shared/environment-polyfills/index.ts
+var polyfill;
+var init_environment_polyfills = __esm({
+ "../pages-shared/environment-polyfills/index.ts"() {
+ init_import_meta_url();
+ polyfill = /* @__PURE__ */ __name((environment) => {
+ Object.entries(environment).map(([name, value]) => {
+ Object.defineProperty(globalThis, name, {
+ value,
+ configurable: true,
+ enumerable: true,
+ writable: true
+ });
+ });
+ }, "polyfill");
+ }
+});
+
+// ../pages-shared/environment-polyfills/miniflare.ts
+var miniflare_exports = {};
+__export(miniflare_exports, {
+ default: () => miniflare_default
+});
+var miniflare_default;
+var init_miniflare = __esm({
+ "../pages-shared/environment-polyfills/miniflare.ts"() {
+ init_import_meta_url();
+ init_environment_polyfills();
+ miniflare_default = /* @__PURE__ */ __name(async () => {
+ const mf = await import("miniflare");
+ polyfill({
+ fetch: mf.fetch,
+ Headers: mf.Headers,
+ Request: mf.Request,
+ Response: mf.Response
+ });
+ }, "default");
+ }
+});
+
+// ../pages-shared/asset-server/responses.ts
+function mergeHeaders(base, extra) {
+ const baseHeaders = new Headers(base ?? {});
+ const extraHeaders = new Headers(extra ?? {});
+ return new Headers({
+ ...Object.fromEntries(baseHeaders.entries()),
+ ...Object.fromEntries(extraHeaders.entries())
+ });
+}
+function stripLeadingDoubleSlashes(location) {
+ return location.replace(/^(\/|%2F|%2f|%5C|%5c|%09|\s|\\)+(.*)/, "/$2");
+}
+var OkResponse, MovedPermanentlyResponse, FoundResponse, NotModifiedResponse, PermanentRedirectResponse, NotFoundResponse, MethodNotAllowedResponse, NotAcceptableResponse, InternalServerErrorResponse, SeeOtherResponse, TemporaryRedirectResponse;
+var init_responses = __esm({
+ "../pages-shared/asset-server/responses.ts"() {
+ init_import_meta_url();
+ __name(mergeHeaders, "mergeHeaders");
+ __name(stripLeadingDoubleSlashes, "stripLeadingDoubleSlashes");
+ OkResponse = class extends Response {
+ constructor(...[body, init]) {
+ super(body, {
+ ...init,
+ status: 200,
+ statusText: "OK"
+ });
+ }
+ };
+ __name(OkResponse, "OkResponse");
+ MovedPermanentlyResponse = class extends Response {
+ constructor(location, init, {
+ preventLeadingDoubleSlash = true
+ } = {
+ preventLeadingDoubleSlash: true
+ }) {
+ location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
+ super(`Redirecting to ${location}`, {
+ ...init,
+ status: 301,
+ statusText: "Moved Permanently",
+ headers: mergeHeaders(init?.headers, {
+ location
+ })
+ });
+ }
+ };
+ __name(MovedPermanentlyResponse, "MovedPermanentlyResponse");
+ FoundResponse = class extends Response {
+ constructor(location, init, {
+ preventLeadingDoubleSlash = true
+ } = {
+ preventLeadingDoubleSlash: true
+ }) {
+ location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
+ super(`Redirecting to ${location}`, {
+ ...init,
+ status: 302,
+ statusText: "Found",
+ headers: mergeHeaders(init?.headers, {
+ location
+ })
+ });
+ }
+ };
+ __name(FoundResponse, "FoundResponse");
+ NotModifiedResponse = class extends Response {
+ constructor(...[_body, _init]) {
+ super(void 0, {
+ status: 304,
+ statusText: "Not Modified"
+ });
+ }
+ };
+ __name(NotModifiedResponse, "NotModifiedResponse");
+ PermanentRedirectResponse = class extends Response {
+ constructor(location, init, {
+ preventLeadingDoubleSlash = true
+ } = {
+ preventLeadingDoubleSlash: true
+ }) {
+ location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
+ super(void 0, {
+ ...init,
+ status: 308,
+ statusText: "Permanent Redirect",
+ headers: mergeHeaders(init?.headers, {
+ location
+ })
+ });
+ }
+ };
+ __name(PermanentRedirectResponse, "PermanentRedirectResponse");
+ NotFoundResponse = class extends Response {
+ constructor(...[body, init]) {
+ super(body, {
+ ...init,
+ status: 404,
+ statusText: "Not Found"
+ });
+ }
+ };
+ __name(NotFoundResponse, "NotFoundResponse");
+ MethodNotAllowedResponse = class extends Response {
+ constructor(...[body, init]) {
+ super(body, {
+ ...init,
+ status: 405,
+ statusText: "Method Not Allowed"
+ });
+ }
+ };
+ __name(MethodNotAllowedResponse, "MethodNotAllowedResponse");
+ NotAcceptableResponse = class extends Response {
+ constructor(...[body, init]) {
+ super(body, {
+ ...init,
+ status: 406,
+ statusText: "Not Acceptable"
+ });
+ }
+ };
+ __name(NotAcceptableResponse, "NotAcceptableResponse");
+ InternalServerErrorResponse = class extends Response {
+ constructor(err, init) {
+ let body = void 0;
+ if (globalThis.DEBUG) {
+ body = `${err.message}
+
+${err.stack}`;
+ }
+ super(body, {
+ ...init,
+ status: 500,
+ statusText: "Internal Server Error"
+ });
+ }
+ };
+ __name(InternalServerErrorResponse, "InternalServerErrorResponse");
+ SeeOtherResponse = class extends Response {
+ constructor(location, init, {
+ preventLeadingDoubleSlash = true
+ } = {
+ preventLeadingDoubleSlash: true
+ }) {
+ location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
+ super(`Redirecting to ${location}`, {
+ ...init,
+ status: 303,
+ statusText: "See Other",
+ headers: mergeHeaders(init?.headers, { location })
+ });
+ }
+ };
+ __name(SeeOtherResponse, "SeeOtherResponse");
+ TemporaryRedirectResponse = class extends Response {
+ constructor(location, init, {
+ preventLeadingDoubleSlash = true
+ } = {
+ preventLeadingDoubleSlash: true
+ }) {
+ location = preventLeadingDoubleSlash ? stripLeadingDoubleSlashes(location) : location;
+ super(`Redirecting to ${location}`, {
+ ...init,
+ status: 307,
+ statusText: "Temporary Redirect",
+ headers: mergeHeaders(init?.headers, { location })
+ });
+ }
+ };
+ __name(TemporaryRedirectResponse, "TemporaryRedirectResponse");
+ }
+});
+
+// ../pages-shared/asset-server/rulesEngine.ts
+var ESCAPE_REGEX_CHARACTERS, escapeRegex, HOST_PLACEHOLDER_REGEX, PLACEHOLDER_REGEX2, replacer, generateRulesMatcher;
+var init_rulesEngine = __esm({
+ "../pages-shared/asset-server/rulesEngine.ts"() {
+ init_import_meta_url();
+ ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
+ escapeRegex = /* @__PURE__ */ __name((str) => {
+ return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&");
+ }, "escapeRegex");
+ HOST_PLACEHOLDER_REGEX = /(?<=^https:\\\/\\\/[^/]*?):([A-Za-z]\w*)(?=\\)/g;
+ PLACEHOLDER_REGEX2 = /:([A-Za-z]\w*)/g;
+ replacer = /* @__PURE__ */ __name((str, replacements) => {
+ for (const [replacement, value] of Object.entries(replacements)) {
+ str = str.replaceAll(`:${replacement}`, value);
+ }
+ return str;
+ }, "replacer");
+ generateRulesMatcher = /* @__PURE__ */ __name((rules, replacerFn = (match) => match) => {
+ if (!rules)
+ return () => [];
+ const compiledRules = Object.entries(rules).map(([rule, match]) => {
+ const crossHost = rule.startsWith("https://");
+ rule = rule.split("*").map(escapeRegex).join("(?.*)");
+ const host_matches = rule.matchAll(HOST_PLACEHOLDER_REGEX);
+ for (const host_match of host_matches) {
+ rule = rule.split(host_match[0]).join(`(?<${host_match[1]}>[^/.]+)`);
+ }
+ const path_matches = rule.matchAll(PLACEHOLDER_REGEX2);
+ for (const path_match of path_matches) {
+ rule = rule.split(path_match[0]).join(`(?<${path_match[1]}>[^/]+)`);
+ }
+ rule = "^" + rule + "$";
+ try {
+ const regExp = new RegExp(rule);
+ return [{ crossHost, regExp }, match];
+ } catch {
+ }
+ }).filter((value) => value !== void 0);
+ return ({ request }) => {
+ const { pathname, hostname } = new URL(request.url);
+ return compiledRules.map(([{ crossHost, regExp }, match]) => {
+ const test = crossHost ? `https://${hostname}${pathname}` : pathname;
+ const result = regExp.exec(test);
+ if (result) {
+ return replacerFn(match, result.groups || {});
+ }
+ }).filter((value) => value !== void 0);
+ };
+ }, "generateRulesMatcher");
+ }
+});
+
+// ../pages-shared/asset-server/handler.ts
+var handler_exports = {};
+__export(handler_exports, {
+ ANALYTICS_VERSION: () => ANALYTICS_VERSION2,
+ ASSET_PRESERVATION_CACHE: () => ASSET_PRESERVATION_CACHE,
+ CACHE_CONTROL_BROWSER: () => CACHE_CONTROL_BROWSER,
+ HEADERS_VERSION: () => HEADERS_VERSION2,
+ HEADERS_VERSION_V1: () => HEADERS_VERSION_V1,
+ REDIRECTS_VERSION: () => REDIRECTS_VERSION2,
+ generateHandler: () => generateHandler,
+ normaliseHeaders: () => normaliseHeaders,
+ parseQualityWeightedList: () => parseQualityWeightedList
+});
+function normaliseHeaders(headers) {
+ if (headers.version === HEADERS_VERSION2) {
+ return headers.rules;
+ } else if (headers.version === HEADERS_VERSION_V1) {
+ return Object.keys(headers.rules).reduce(
+ (acc, key) => {
+ acc[key] = {
+ set: headers.rules[key]
+ };
+ return acc;
+ },
+ {}
+ );
+ } else {
+ return {};
+ }
+}
+async function generateHandler({
+ request,
+ metadata,
+ xServerEnvHeader,
+ xDeploymentIdHeader,
+ logError,
+ findAssetEntryForPath,
+ getAssetKey,
+ negotiateContent,
+ fetchAsset,
+ generateNotFoundResponse = /* @__PURE__ */ __name(async (notFoundRequest, notFoundFindAssetEntryForPath, notFoundServeAsset) => {
+ let assetEntry;
+ if (assetEntry = await notFoundFindAssetEntryForPath("/index.html")) {
+ return notFoundServeAsset(assetEntry, { preserve: false });
+ }
+ return new NotFoundResponse();
+ }, "generateNotFoundResponse"),
+ attachAdditionalHeaders = /* @__PURE__ */ __name(() => {
+ }, "attachAdditionalHeaders"),
+ caches,
+ waitUntil
+}) {
+ const url3 = new URL(request.url);
+ const { protocol, host, search } = url3;
+ let { pathname } = url3;
+ const earlyHintsCache = metadata.deploymentId ? await caches?.open(`eh:${metadata.deploymentId}`) : void 0;
+ const headerRules = metadata.headers ? normaliseHeaders(metadata.headers) : {};
+ const staticRules = metadata.redirects?.version === REDIRECTS_VERSION2 ? metadata.redirects.staticRules || {} : {};
+ const staticRedirectsMatcher = /* @__PURE__ */ __name(() => {
+ const withHostMatch = staticRules[`https://${host}${pathname}`];
+ const withoutHostMatch = staticRules[pathname];
+ if (withHostMatch && withoutHostMatch) {
+ if (withHostMatch.lineNumber < withoutHostMatch.lineNumber) {
+ return withHostMatch;
+ } else {
+ return withoutHostMatch;
+ }
+ }
+ return withHostMatch || withoutHostMatch;
+ }, "staticRedirectsMatcher");
+ const generateRedirectsMatcher = /* @__PURE__ */ __name(() => generateRulesMatcher(
+ metadata.redirects?.version === REDIRECTS_VERSION2 ? metadata.redirects.rules : {},
+ ({ status, to }, replacements) => ({
+ status,
+ to: replacer(to, replacements)
+ })
+ ), "generateRedirectsMatcher");
+ let assetEntry;
+ async function generateResponse() {
+ const match = staticRedirectsMatcher() || generateRedirectsMatcher()({ request })[0];
+ if (match) {
+ if (match.status === 200) {
+ pathname = new URL(match.to, request.url).pathname;
+ } else {
+ const { status, to } = match;
+ const destination = new URL(to, request.url);
+ const location = destination.origin === new URL(request.url).origin ? `${destination.pathname}${destination.search || search}${destination.hash}` : `${destination.href}${destination.search ? "" : search}${destination.hash}`;
+ switch (status) {
+ case 301:
+ return new MovedPermanentlyResponse(location, void 0, {
+ preventLeadingDoubleSlash: false
+ });
+ case 303:
+ return new SeeOtherResponse(location, void 0, {
+ preventLeadingDoubleSlash: false
+ });
+ case 307:
+ return new TemporaryRedirectResponse(location, void 0, {
+ preventLeadingDoubleSlash: false
+ });
+ case 308:
+ return new PermanentRedirectResponse(location, void 0, {
+ preventLeadingDoubleSlash: false
+ });
+ case 302:
+ default:
+ return new FoundResponse(location, void 0, {
+ preventLeadingDoubleSlash: false
+ });
+ }
+ }
+ }
+ if (!request.method.match(/^(get|head)$/i)) {
+ return new MethodNotAllowedResponse();
+ }
+ try {
+ pathname = globalThis.decodeURIComponent(pathname);
+ } catch (err) {
+ }
+ if (pathname.endsWith("/")) {
+ if (assetEntry = await findAssetEntryForPath(`${pathname}index.html`)) {
+ return serveAsset(assetEntry);
+ } else if (pathname.endsWith("/index/")) {
+ return new PermanentRedirectResponse(
+ `/${pathname.slice(1, -"index/".length)}${search}`
+ );
+ } else if (assetEntry = await findAssetEntryForPath(
+ `${pathname.replace(/\/$/, ".html")}`
+ )) {
+ return new PermanentRedirectResponse(
+ `/${pathname.slice(1, -1)}${search}`
+ );
+ } else {
+ return notFound();
+ }
+ }
+ if (assetEntry = await findAssetEntryForPath(pathname)) {
+ if (pathname.endsWith(".html")) {
+ const extensionlessPath = pathname.slice(0, -".html".length);
+ if (extensionlessPath.endsWith("/index")) {
+ return new PermanentRedirectResponse(
+ `${extensionlessPath.replace(/\/index$/, "/")}${search}`
+ );
+ } else if (await findAssetEntryForPath(extensionlessPath) || extensionlessPath === "/") {
+ return serveAsset(assetEntry);
+ } else {
+ return new PermanentRedirectResponse(`${extensionlessPath}${search}`);
+ }
+ } else {
+ return serveAsset(assetEntry);
+ }
+ } else if (pathname.endsWith("/index")) {
+ return new PermanentRedirectResponse(
+ `/${pathname.slice(1, -"index".length)}${search}`
+ );
+ } else if (assetEntry = await findAssetEntryForPath(`${pathname}.html`)) {
+ return serveAsset(assetEntry);
+ } else if (hasFileExtension(pathname)) {
+ return notFound();
+ }
+ if (assetEntry = await findAssetEntryForPath(`${pathname}/index.html`)) {
+ return new PermanentRedirectResponse(`${pathname}/${search}`);
+ } else {
+ return notFound();
+ }
+ }
+ __name(generateResponse, "generateResponse");
+ async function attachHeaders(response) {
+ const existingHeaders = new Headers(response.headers);
+ const extraHeaders = new Headers({
+ "access-control-allow-origin": "*",
+ "referrer-policy": "strict-origin-when-cross-origin",
+ ...existingHeaders.has("content-type") ? { "x-content-type-options": "nosniff" } : {}
+ });
+ const headers = new Headers({
+ // But we intentionally override existing headers
+ ...Object.fromEntries(existingHeaders.entries()),
+ ...Object.fromEntries(extraHeaders.entries())
+ });
+ if (earlyHintsCache) {
+ const preEarlyHintsHeaders = new Headers(headers);
+ const earlyHintsCacheKey = `${protocol}//${host}${pathname}`;
+ const earlyHintsResponse = await earlyHintsCache.match(
+ earlyHintsCacheKey
+ );
+ if (earlyHintsResponse) {
+ const earlyHintsLinkHeader = earlyHintsResponse.headers.get("Link");
+ if (earlyHintsLinkHeader) {
+ headers.set("Link", earlyHintsLinkHeader);
+ }
+ }
+ const clonedResponse = response.clone();
+ if (waitUntil) {
+ waitUntil(
+ (async () => {
+ try {
+ const links = [];
+ const transformedResponse = new HTMLRewriter().on("link[rel~=preconnect],link[rel~=preload]", {
+ element(element) {
+ for (const [attributeName] of element.attributes) {
+ if (!ALLOWED_EARLY_HINT_LINK_ATTRIBUTES.includes(
+ attributeName.toLowerCase()
+ )) {
+ return;
+ }
+ }
+ const href = element.getAttribute("href") || void 0;
+ const rel = element.getAttribute("rel") || void 0;
+ const as = element.getAttribute("as") || void 0;
+ if (href && !href.startsWith("data:") && rel) {
+ links.push({ href, rel, as });
+ }
+ }
+ }).transform(clonedResponse);
+ await transformedResponse.text();
+ links.forEach(({ href, rel, as }) => {
+ let link = `<${href}>; rel="${rel}"`;
+ if (as) {
+ link += `; as=${as}`;
+ }
+ preEarlyHintsHeaders.append("Link", link);
+ });
+ const linkHeader = preEarlyHintsHeaders.get("Link");
+ if (linkHeader) {
+ await earlyHintsCache.put(
+ earlyHintsCacheKey,
+ new Response(null, { headers: { Link: linkHeader } })
+ );
+ }
+ } catch (err) {
+ }
+ })()
+ );
+ }
+ }
+ const headersMatcher = generateRulesMatcher(
+ headerRules,
+ ({ set = {}, unset = [] }, replacements) => {
+ const replacedSet = {};
+ Object.keys(set).forEach((key) => {
+ replacedSet[key] = replacer(set[key], replacements);
+ });
+ return {
+ set: replacedSet,
+ unset
+ };
+ }
+ );
+ const matches = headersMatcher({ request });
+ const setMap = /* @__PURE__ */ new Set();
+ matches.forEach(({ set = {}, unset = [] }) => {
+ unset.forEach((key) => {
+ headers.delete(key);
+ });
+ Object.keys(set).forEach((key) => {
+ if (setMap.has(key.toLowerCase())) {
+ headers.append(key, set[key]);
+ } else {
+ headers.set(key, set[key]);
+ setMap.add(key.toLowerCase());
+ }
+ });
+ });
+ return new Response(
+ [101, 204, 205, 304].includes(response.status) ? null : response.body,
+ {
+ headers,
+ status: response.status,
+ statusText: response.statusText
+ }
+ );
+ }
+ __name(attachHeaders, "attachHeaders");
+ return await attachHeaders(await generateResponse());
+ async function serveAsset(servingAssetEntry, options14 = { preserve: true }) {
+ let content;
+ try {
+ content = negotiateContent(request, servingAssetEntry);
+ } catch (err) {
+ return new NotAcceptableResponse();
+ }
+ const assetKey = getAssetKey(servingAssetEntry, content);
+ const etag = `"${assetKey}"`;
+ const weakEtag = `W/${etag}`;
+ const ifNoneMatch = request.headers.get("if-none-match");
+ if (ifNoneMatch === weakEtag || ifNoneMatch === etag) {
+ return new NotModifiedResponse();
+ }
+ try {
+ const asset = await fetchAsset(assetKey);
+ const headers = {
+ etag,
+ "content-type": asset.contentType
+ };
+ let encodeBody = "automatic";
+ if (xServerEnvHeader) {
+ headers["x-server-env"] = xServerEnvHeader;
+ }
+ if (xDeploymentIdHeader && metadata.deploymentId) {
+ headers["x-deployment-id"] = metadata.deploymentId;
+ }
+ if (content.encoding) {
+ encodeBody = "manual";
+ headers["cache-control"] = "no-transform";
+ headers["content-encoding"] = content.encoding;
+ }
+ const response = new OkResponse(
+ request.method === "HEAD" ? null : asset.body,
+ {
+ headers,
+ encodeBody
+ }
+ );
+ if (isCacheable(request)) {
+ response.headers.append("cache-control", CACHE_CONTROL_BROWSER);
+ }
+ attachAdditionalHeaders(response, content, servingAssetEntry, asset);
+ if (isPreview(new URL(request.url))) {
+ response.headers.set("x-robots-tag", "noindex");
+ }
+ if (options14.preserve) {
+ const preservedResponse = new Response(
+ [101, 204, 205, 304].includes(response.status) ? null : response.clone().body,
+ response
+ );
+ preservedResponse.headers.set(
+ "cache-control",
+ CACHE_CONTROL_PRESERVATION
+ );
+ preservedResponse.headers.set("x-robots-tag", "noindex");
+ if (waitUntil && caches) {
+ waitUntil(
+ caches.open(ASSET_PRESERVATION_CACHE).then(
+ (assetPreservationCache) => assetPreservationCache.put(request.url, preservedResponse)
+ ).catch((err) => {
+ logError(err);
+ })
+ );
+ }
+ }
+ if (asset.contentType.startsWith("text/html") && metadata.analytics?.version === ANALYTICS_VERSION2) {
+ return new HTMLRewriter().on("body", {
+ element(e2) {
+ e2.append(
+ ``,
+ { html: true }
+ );
+ }
+ }).transform(response);
+ }
+ return response;
+ } catch (err) {
+ logError(err);
+ return new InternalServerErrorResponse(err);
+ }
+ }
+ __name(serveAsset, "serveAsset");
+ async function notFound() {
+ if (caches) {
+ const assetPreservationCache = await caches.open(
+ ASSET_PRESERVATION_CACHE
+ );
+ const preservedResponse = await assetPreservationCache.match(request.url);
+ if (preservedResponse) {
+ return preservedResponse;
+ }
+ }
+ let cwd2 = pathname;
+ while (cwd2) {
+ cwd2 = cwd2.slice(0, cwd2.lastIndexOf("/"));
+ if (assetEntry = await findAssetEntryForPath(`${cwd2}/404.html`)) {
+ let content;
+ try {
+ content = negotiateContent(request, assetEntry);
+ } catch (err) {
+ return new NotAcceptableResponse();
+ }
+ const assetKey = getAssetKey(assetEntry, content);
+ try {
+ const { body, contentType } = await fetchAsset(assetKey);
+ const response = new NotFoundResponse(body);
+ response.headers.set("content-type", contentType);
+ return response;
+ } catch (err) {
+ logError(err);
+ return new InternalServerErrorResponse(err);
+ }
+ }
+ }
+ return await generateNotFoundResponse(
+ request,
+ findAssetEntryForPath,
+ serveAsset
+ );
+ }
+ __name(notFound, "notFound");
+}
+function parseQualityWeightedList(list = "") {
+ const items = {};
+ list.replace(/\s/g, "").split(",").forEach((el) => {
+ const [item, weight] = el.split(";q=");
+ items[item] = weight ? parseFloat(weight) : 1;
+ });
+ return items;
+}
+function isCacheable(request) {
+ return !request.headers.has("authorization") && !request.headers.has("range");
+}
+function hasFileExtension(path45) {
+ return /\/.+\.[a-z0-9]+$/i.test(path45);
+}
+function isPreview(url3) {
+ if (url3.hostname.endsWith(".pages.dev")) {
+ return url3.hostname.split(".").length > 3 ? true : false;
+ }
+ return false;
+}
+var ASSET_PRESERVATION_CACHE, CACHE_CONTROL_PRESERVATION, CACHE_CONTROL_BROWSER, REDIRECTS_VERSION2, HEADERS_VERSION2, HEADERS_VERSION_V1, ANALYTICS_VERSION2, ALLOWED_EARLY_HINT_LINK_ATTRIBUTES;
+var init_handler = __esm({
+ "../pages-shared/asset-server/handler.ts"() {
+ init_import_meta_url();
+ init_responses();
+ init_rulesEngine();
+ ASSET_PRESERVATION_CACHE = "assetPreservationCache";
+ CACHE_CONTROL_PRESERVATION = "public, s-maxage=604800";
+ CACHE_CONTROL_BROWSER = "public, max-age=0, must-revalidate";
+ REDIRECTS_VERSION2 = 1;
+ HEADERS_VERSION2 = 2;
+ HEADERS_VERSION_V1 = 1;
+ ANALYTICS_VERSION2 = 1;
+ ALLOWED_EARLY_HINT_LINK_ATTRIBUTES = ["rel", "as", "href"];
+ __name(normaliseHeaders, "normaliseHeaders");
+ __name(generateHandler, "generateHandler");
+ __name(parseQualityWeightedList, "parseQualityWeightedList");
+ __name(isCacheable, "isCacheable");
+ __name(hasFileExtension, "hasFileExtension");
+ __name(isPreview, "isPreview");
+ }
+});
+
+// src/miniflare-cli/assets.ts
+var assets_exports = {};
+__export(assets_exports, {
+ default: () => generateASSETSBinding
+});
+async function generateASSETSBinding(options14) {
+ const assetsFetch = options14.directory !== void 0 ? await generateAssetsFetch(options14.directory, options14.log) : invalidAssetsFetch;
+ return async function(miniflareRequest) {
+ if (options14.proxyPort) {
+ try {
+ const url3 = new URL(miniflareRequest.url);
+ url3.host = `localhost:${options14.proxyPort}`;
+ const proxyRequest = new import_miniflare2.Request(url3, miniflareRequest);
+ if (proxyRequest.headers.get("Upgrade") === "websocket") {
+ proxyRequest.headers.delete("Sec-WebSocket-Accept");
+ proxyRequest.headers.delete("Sec-WebSocket-Key");
+ }
+ return await (0, import_miniflare2.fetch)(proxyRequest);
+ } catch (thrown) {
+ options14.log.error(new Error(`Could not proxy request: ${thrown}`));
+ return new import_miniflare2.Response(`[wrangler] Could not proxy request: ${thrown}`, {
+ status: 502
+ });
+ }
+ } else {
+ try {
+ return await assetsFetch(miniflareRequest);
+ } catch (thrown) {
+ options14.log.error(new Error(`Could not serve static asset: ${thrown}`));
+ return new import_miniflare2.Response(
+ `[wrangler] Could not serve static asset: ${thrown}`,
+ { status: 502 }
+ );
+ }
+ }
+ };
+}
+async function generateAssetsFetch(directory, log) {
+ directory = (0, import_node_path19.resolve)(directory);
+ const polyfill2 = (await Promise.resolve().then(() => (init_miniflare(), miniflare_exports))).default;
+ await polyfill2();
+ const { generateHandler: generateHandler3, parseQualityWeightedList: parseQualityWeightedList2 } = await Promise.resolve().then(() => (init_handler(), handler_exports));
+ const headersFile = (0, import_node_path19.join)(directory, "_headers");
+ const redirectsFile = (0, import_node_path19.join)(directory, "_redirects");
+ const workerFile = (0, import_node_path19.join)(directory, "_worker.js");
+ const ignoredFiles = [headersFile, redirectsFile, workerFile];
+ let redirects;
+ if ((0, import_node_fs8.existsSync)(redirectsFile)) {
+ const contents = (0, import_node_fs8.readFileSync)(redirectsFile, "utf-8");
+ redirects = parseRedirects(contents);
+ }
+ let headers;
+ if ((0, import_node_fs8.existsSync)(headersFile)) {
+ const contents = (0, import_node_fs8.readFileSync)(headersFile, "utf-8");
+ headers = parseHeaders(contents);
+ }
+ let metadata = createMetadataObject({
+ redirects,
+ headers,
+ logger: log.warn.bind(log)
+ });
+ (0, import_chokidar.watch)([headersFile, redirectsFile], { persistent: true }).on(
+ "change",
+ (path45) => {
+ switch (path45) {
+ case headersFile: {
+ log.log("_headers modified. Re-evaluating...");
+ const contents = (0, import_node_fs8.readFileSync)(headersFile).toString();
+ headers = parseHeaders(contents);
+ break;
+ }
+ case redirectsFile: {
+ log.log("_redirects modified. Re-evaluating...");
+ const contents = (0, import_node_fs8.readFileSync)(redirectsFile).toString();
+ redirects = parseRedirects(contents);
+ break;
+ }
+ }
+ metadata = createMetadataObject({
+ redirects,
+ headers,
+ logger: log.warn
+ });
+ }
+ );
+ const generateResponse = /* @__PURE__ */ __name(async (request) => {
+ const assetKeyEntryMap = /* @__PURE__ */ new Map();
+ return await generateHandler3({
+ request,
+ metadata,
+ xServerEnvHeader: "dev",
+ logError: console.error,
+ findAssetEntryForPath: async (path45) => {
+ const filepath = (0, import_node_path19.resolve)((0, import_node_path19.join)(directory, path45));
+ if (!filepath.startsWith(directory)) {
+ return null;
+ }
+ if ((0, import_node_fs8.existsSync)(filepath) && (0, import_node_fs8.lstatSync)(filepath).isFile() && !ignoredFiles.includes(filepath)) {
+ const hash = hashFile(filepath);
+ assetKeyEntryMap.set(hash, filepath);
+ return hash;
+ }
+ return null;
+ },
+ getAssetKey: (assetEntry) => {
+ return assetEntry;
+ },
+ negotiateContent: (contentRequest) => {
+ let rawAcceptEncoding;
+ if (contentRequest.cf && "clientAcceptEncoding" in contentRequest.cf && contentRequest.cf.clientAcceptEncoding) {
+ rawAcceptEncoding = contentRequest.cf.clientAcceptEncoding;
+ } else {
+ rawAcceptEncoding = contentRequest.headers.get("Accept-Encoding") || void 0;
+ }
+ const acceptEncoding = parseQualityWeightedList2(rawAcceptEncoding);
+ if (acceptEncoding["identity"] === 0 || acceptEncoding["*"] === 0 && acceptEncoding["identity"] === void 0) {
+ throw new Error("No acceptable encodings available");
+ }
+ return { encoding: null };
+ },
+ fetchAsset: async (assetKey) => {
+ const filepath = assetKeyEntryMap.get(assetKey);
+ if (!filepath) {
+ throw new Error(
+ "Could not fetch asset. Please file an issue on GitHub (https://github.com/cloudflare/workers-sdk/issues/new/choose) with reproduction steps."
+ );
+ }
+ const body = (0, import_node_fs8.readFileSync)(filepath);
+ let contentType = (0, import_mime.getType)(filepath) || "application/octet-stream";
+ if (contentType.startsWith("text/") && !contentType.includes("charset")) {
+ contentType = `${contentType}; charset=utf-8`;
+ }
+ return { body, contentType };
+ }
+ });
+ }, "generateResponse");
+ return async (input, init) => {
+ const request = new import_miniflare2.Request(input, init);
+ return await generateResponse(request);
+ };
+}
+var import_node_fs8, import_node_path19, import_chokidar, import_mime, import_miniflare2, invalidAssetsFetch;
+var init_assets = __esm({
+ "src/miniflare-cli/assets.ts"() {
+ init_import_meta_url();
+ import_node_fs8 = require("node:fs");
+ import_node_path19 = require("node:path");
+ init_createMetadataObject();
+ init_parseHeaders();
+ init_parseRedirects();
+ import_chokidar = require("chokidar");
+ import_mime = __toESM(require_mime2());
+ import_miniflare2 = require("miniflare");
+ init_hash();
+ __name(generateASSETSBinding, "generateASSETSBinding");
+ __name(generateAssetsFetch, "generateAssetsFetch");
+ invalidAssetsFetch = /* @__PURE__ */ __name(() => {
+ throw new Error(
+ "Trying to fetch assets directly when there is no `directory` option specified."
+ );
+ }, "invalidAssetsFetch");
+ }
+});
+
+// ../../node_modules/.pnpm/lodash.isequal@4.5.0/node_modules/lodash.isequal/index.js
+var require_lodash2 = __commonJS({
+ "../../node_modules/.pnpm/lodash.isequal@4.5.0/node_modules/lodash.isequal/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var LARGE_ARRAY_SIZE = 200;
+ var HASH_UNDEFINED = "__lodash_hash_undefined__";
+ var COMPARE_PARTIAL_FLAG = 1;
+ var COMPARE_UNORDERED_FLAG = 2;
+ var MAX_SAFE_INTEGER = 9007199254740991;
+ var argsTag = "[object Arguments]";
+ var arrayTag = "[object Array]";
+ var asyncTag = "[object AsyncFunction]";
+ var boolTag = "[object Boolean]";
+ var dateTag = "[object Date]";
+ var errorTag = "[object Error]";
+ var funcTag = "[object Function]";
+ var genTag = "[object GeneratorFunction]";
+ var mapTag = "[object Map]";
+ var numberTag = "[object Number]";
+ var nullTag = "[object Null]";
+ var objectTag = "[object Object]";
+ var promiseTag = "[object Promise]";
+ var proxyTag = "[object Proxy]";
+ var regexpTag = "[object RegExp]";
+ var setTag = "[object Set]";
+ var stringTag = "[object String]";
+ var symbolTag = "[object Symbol]";
+ var undefinedTag = "[object Undefined]";
+ var weakMapTag = "[object WeakMap]";
+ var arrayBufferTag = "[object ArrayBuffer]";
+ var dataViewTag = "[object DataView]";
+ var float32Tag = "[object Float32Array]";
+ var float64Tag = "[object Float64Array]";
+ var int8Tag = "[object Int8Array]";
+ var int16Tag = "[object Int16Array]";
+ var int32Tag = "[object Int32Array]";
+ var uint8Tag = "[object Uint8Array]";
+ var uint8ClampedTag = "[object Uint8ClampedArray]";
+ var uint16Tag = "[object Uint16Array]";
+ var uint32Tag = "[object Uint32Array]";
+ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g;
+ var reIsHostCtor = /^\[object .+?Constructor\]$/;
+ var reIsUint = /^(?:0|[1-9]\d*)$/;
+ var typedArrayTags = {};
+ typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true;
+ typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false;
+ var freeGlobal = typeof global == "object" && global && global.Object === Object && global;
+ var freeSelf = typeof self == "object" && self && self.Object === Object && self;
+ var root = freeGlobal || freeSelf || Function("return this")();
+ var freeExports = typeof exports2 == "object" && exports2 && !exports2.nodeType && exports2;
+ var freeModule = freeExports && typeof module2 == "object" && module2 && !module2.nodeType && module2;
+ var moduleExports = freeModule && freeModule.exports === freeExports;
+ var freeProcess = moduleExports && freeGlobal.process;
+ var nodeUtil = function() {
+ try {
+ return freeProcess && freeProcess.binding && freeProcess.binding("util");
+ } catch (e2) {
+ }
+ }();
+ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
+ function arrayFilter(array, predicate) {
+ var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = [];
+ while (++index < length) {
+ var value = array[index];
+ if (predicate(value, index, array)) {
+ result[resIndex++] = value;
+ }
+ }
+ return result;
+ }
+ __name(arrayFilter, "arrayFilter");
+ function arrayPush(array, values) {
+ var index = -1, length = values.length, offset = array.length;
+ while (++index < length) {
+ array[offset + index] = values[index];
+ }
+ return array;
+ }
+ __name(arrayPush, "arrayPush");
+ function arraySome(array, predicate) {
+ var index = -1, length = array == null ? 0 : array.length;
+ while (++index < length) {
+ if (predicate(array[index], index, array)) {
+ return true;
+ }
+ }
+ return false;
+ }
+ __name(arraySome, "arraySome");
+ function baseTimes(n, iteratee) {
+ var index = -1, result = Array(n);
+ while (++index < n) {
+ result[index] = iteratee(index);
+ }
+ return result;
+ }
+ __name(baseTimes, "baseTimes");
+ function baseUnary(func) {
+ return function(value) {
+ return func(value);
+ };
+ }
+ __name(baseUnary, "baseUnary");
+ function cacheHas(cache2, key) {
+ return cache2.has(key);
+ }
+ __name(cacheHas, "cacheHas");
+ function getValue(object, key) {
+ return object == null ? void 0 : object[key];
+ }
+ __name(getValue, "getValue");
+ function mapToArray(map) {
+ var index = -1, result = Array(map.size);
+ map.forEach(function(value, key) {
+ result[++index] = [key, value];
+ });
+ return result;
+ }
+ __name(mapToArray, "mapToArray");
+ function overArg(func, transform) {
+ return function(arg) {
+ return func(transform(arg));
+ };
+ }
+ __name(overArg, "overArg");
+ function setToArray(set) {
+ var index = -1, result = Array(set.size);
+ set.forEach(function(value) {
+ result[++index] = value;
+ });
+ return result;
+ }
+ __name(setToArray, "setToArray");
+ var arrayProto = Array.prototype;
+ var funcProto = Function.prototype;
+ var objectProto = Object.prototype;
+ var coreJsData = root["__core-js_shared__"];
+ var funcToString = funcProto.toString;
+ var hasOwnProperty2 = objectProto.hasOwnProperty;
+ var maskSrcKey = function() {
+ var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || "");
+ return uid ? "Symbol(src)_1." + uid : "";
+ }();
+ var nativeObjectToString = objectProto.toString;
+ var reIsNative = RegExp(
+ "^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$"
+ );
+ var Buffer3 = moduleExports ? root.Buffer : void 0;
+ var Symbol2 = root.Symbol;
+ var Uint8Array2 = root.Uint8Array;
+ var propertyIsEnumerable = objectProto.propertyIsEnumerable;
+ var splice = arrayProto.splice;
+ var symToStringTag = Symbol2 ? Symbol2.toStringTag : void 0;
+ var nativeGetSymbols = Object.getOwnPropertySymbols;
+ var nativeIsBuffer = Buffer3 ? Buffer3.isBuffer : void 0;
+ var nativeKeys = overArg(Object.keys, Object);
+ var DataView2 = getNative(root, "DataView");
+ var Map2 = getNative(root, "Map");
+ var Promise2 = getNative(root, "Promise");
+ var Set2 = getNative(root, "Set");
+ var WeakMap2 = getNative(root, "WeakMap");
+ var nativeCreate = getNative(Object, "create");
+ var dataViewCtorString = toSource(DataView2);
+ var mapCtorString = toSource(Map2);
+ var promiseCtorString = toSource(Promise2);
+ var setCtorString = toSource(Set2);
+ var weakMapCtorString = toSource(WeakMap2);
+ var symbolProto = Symbol2 ? Symbol2.prototype : void 0;
+ var symbolValueOf = symbolProto ? symbolProto.valueOf : void 0;
+ function Hash(entries) {
+ var index = -1, length = entries == null ? 0 : entries.length;
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+ }
+ __name(Hash, "Hash");
+ function hashClear() {
+ this.__data__ = nativeCreate ? nativeCreate(null) : {};
+ this.size = 0;
+ }
+ __name(hashClear, "hashClear");
+ function hashDelete(key) {
+ var result = this.has(key) && delete this.__data__[key];
+ this.size -= result ? 1 : 0;
+ return result;
+ }
+ __name(hashDelete, "hashDelete");
+ function hashGet(key) {
+ var data = this.__data__;
+ if (nativeCreate) {
+ var result = data[key];
+ return result === HASH_UNDEFINED ? void 0 : result;
+ }
+ return hasOwnProperty2.call(data, key) ? data[key] : void 0;
+ }
+ __name(hashGet, "hashGet");
+ function hashHas(key) {
+ var data = this.__data__;
+ return nativeCreate ? data[key] !== void 0 : hasOwnProperty2.call(data, key);
+ }
+ __name(hashHas, "hashHas");
+ function hashSet(key, value) {
+ var data = this.__data__;
+ this.size += this.has(key) ? 0 : 1;
+ data[key] = nativeCreate && value === void 0 ? HASH_UNDEFINED : value;
+ return this;
+ }
+ __name(hashSet, "hashSet");
+ Hash.prototype.clear = hashClear;
+ Hash.prototype["delete"] = hashDelete;
+ Hash.prototype.get = hashGet;
+ Hash.prototype.has = hashHas;
+ Hash.prototype.set = hashSet;
+ function ListCache(entries) {
+ var index = -1, length = entries == null ? 0 : entries.length;
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+ }
+ __name(ListCache, "ListCache");
+ function listCacheClear() {
+ this.__data__ = [];
+ this.size = 0;
+ }
+ __name(listCacheClear, "listCacheClear");
+ function listCacheDelete(key) {
+ var data = this.__data__, index = assocIndexOf(data, key);
+ if (index < 0) {
+ return false;
+ }
+ var lastIndex = data.length - 1;
+ if (index == lastIndex) {
+ data.pop();
+ } else {
+ splice.call(data, index, 1);
+ }
+ --this.size;
+ return true;
+ }
+ __name(listCacheDelete, "listCacheDelete");
+ function listCacheGet(key) {
+ var data = this.__data__, index = assocIndexOf(data, key);
+ return index < 0 ? void 0 : data[index][1];
+ }
+ __name(listCacheGet, "listCacheGet");
+ function listCacheHas(key) {
+ return assocIndexOf(this.__data__, key) > -1;
+ }
+ __name(listCacheHas, "listCacheHas");
+ function listCacheSet(key, value) {
+ var data = this.__data__, index = assocIndexOf(data, key);
+ if (index < 0) {
+ ++this.size;
+ data.push([key, value]);
+ } else {
+ data[index][1] = value;
+ }
+ return this;
+ }
+ __name(listCacheSet, "listCacheSet");
+ ListCache.prototype.clear = listCacheClear;
+ ListCache.prototype["delete"] = listCacheDelete;
+ ListCache.prototype.get = listCacheGet;
+ ListCache.prototype.has = listCacheHas;
+ ListCache.prototype.set = listCacheSet;
+ function MapCache(entries) {
+ var index = -1, length = entries == null ? 0 : entries.length;
+ this.clear();
+ while (++index < length) {
+ var entry = entries[index];
+ this.set(entry[0], entry[1]);
+ }
+ }
+ __name(MapCache, "MapCache");
+ function mapCacheClear() {
+ this.size = 0;
+ this.__data__ = {
+ "hash": new Hash(),
+ "map": new (Map2 || ListCache)(),
+ "string": new Hash()
+ };
+ }
+ __name(mapCacheClear, "mapCacheClear");
+ function mapCacheDelete(key) {
+ var result = getMapData(this, key)["delete"](key);
+ this.size -= result ? 1 : 0;
+ return result;
+ }
+ __name(mapCacheDelete, "mapCacheDelete");
+ function mapCacheGet(key) {
+ return getMapData(this, key).get(key);
+ }
+ __name(mapCacheGet, "mapCacheGet");
+ function mapCacheHas(key) {
+ return getMapData(this, key).has(key);
+ }
+ __name(mapCacheHas, "mapCacheHas");
+ function mapCacheSet(key, value) {
+ var data = getMapData(this, key), size = data.size;
+ data.set(key, value);
+ this.size += data.size == size ? 0 : 1;
+ return this;
+ }
+ __name(mapCacheSet, "mapCacheSet");
+ MapCache.prototype.clear = mapCacheClear;
+ MapCache.prototype["delete"] = mapCacheDelete;
+ MapCache.prototype.get = mapCacheGet;
+ MapCache.prototype.has = mapCacheHas;
+ MapCache.prototype.set = mapCacheSet;
+ function SetCache(values) {
+ var index = -1, length = values == null ? 0 : values.length;
+ this.__data__ = new MapCache();
+ while (++index < length) {
+ this.add(values[index]);
+ }
+ }
+ __name(SetCache, "SetCache");
+ function setCacheAdd(value) {
+ this.__data__.set(value, HASH_UNDEFINED);
+ return this;
+ }
+ __name(setCacheAdd, "setCacheAdd");
+ function setCacheHas(value) {
+ return this.__data__.has(value);
+ }
+ __name(setCacheHas, "setCacheHas");
+ SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
+ SetCache.prototype.has = setCacheHas;
+ function Stack(entries) {
+ var data = this.__data__ = new ListCache(entries);
+ this.size = data.size;
+ }
+ __name(Stack, "Stack");
+ function stackClear() {
+ this.__data__ = new ListCache();
+ this.size = 0;
+ }
+ __name(stackClear, "stackClear");
+ function stackDelete(key) {
+ var data = this.__data__, result = data["delete"](key);
+ this.size = data.size;
+ return result;
+ }
+ __name(stackDelete, "stackDelete");
+ function stackGet(key) {
+ return this.__data__.get(key);
+ }
+ __name(stackGet, "stackGet");
+ function stackHas(key) {
+ return this.__data__.has(key);
+ }
+ __name(stackHas, "stackHas");
+ function stackSet(key, value) {
+ var data = this.__data__;
+ if (data instanceof ListCache) {
+ var pairs = data.__data__;
+ if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) {
+ pairs.push([key, value]);
+ this.size = ++data.size;
+ return this;
+ }
+ data = this.__data__ = new MapCache(pairs);
+ }
+ data.set(key, value);
+ this.size = data.size;
+ return this;
+ }
+ __name(stackSet, "stackSet");
+ Stack.prototype.clear = stackClear;
+ Stack.prototype["delete"] = stackDelete;
+ Stack.prototype.get = stackGet;
+ Stack.prototype.has = stackHas;
+ Stack.prototype.set = stackSet;
+ function arrayLikeKeys(value, inherited) {
+ var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length;
+ for (var key in value) {
+ if ((inherited || hasOwnProperty2.call(value, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode.
+ (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers.
+ isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays.
+ isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties.
+ isIndex(key, length)))) {
+ result.push(key);
+ }
+ }
+ return result;
+ }
+ __name(arrayLikeKeys, "arrayLikeKeys");
+ function assocIndexOf(array, key) {
+ var length = array.length;
+ while (length--) {
+ if (eq(array[length][0], key)) {
+ return length;
+ }
+ }
+ return -1;
+ }
+ __name(assocIndexOf, "assocIndexOf");
+ function baseGetAllKeys(object, keysFunc, symbolsFunc) {
+ var result = keysFunc(object);
+ return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
+ }
+ __name(baseGetAllKeys, "baseGetAllKeys");
+ function baseGetTag(value) {
+ if (value == null) {
+ return value === void 0 ? undefinedTag : nullTag;
+ }
+ return symToStringTag && symToStringTag in Object(value) ? getRawTag(value) : objectToString(value);
+ }
+ __name(baseGetTag, "baseGetTag");
+ function baseIsArguments(value) {
+ return isObjectLike(value) && baseGetTag(value) == argsTag;
+ }
+ __name(baseIsArguments, "baseIsArguments");
+ function baseIsEqual(value, other, bitmask, customizer, stack) {
+ if (value === other) {
+ return true;
+ }
+ if (value == null || other == null || !isObjectLike(value) && !isObjectLike(other)) {
+ return value !== value && other !== other;
+ }
+ return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
+ }
+ __name(baseIsEqual, "baseIsEqual");
+ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
+ var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other);
+ objTag = objTag == argsTag ? objectTag : objTag;
+ othTag = othTag == argsTag ? objectTag : othTag;
+ var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag;
+ if (isSameTag && isBuffer(object)) {
+ if (!isBuffer(other)) {
+ return false;
+ }
+ objIsArr = true;
+ objIsObj = false;
+ }
+ if (isSameTag && !objIsObj) {
+ stack || (stack = new Stack());
+ return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
+ }
+ if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
+ var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__");
+ if (objIsWrapped || othIsWrapped) {
+ var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other;
+ stack || (stack = new Stack());
+ return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
+ }
+ }
+ if (!isSameTag) {
+ return false;
+ }
+ stack || (stack = new Stack());
+ return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
+ }
+ __name(baseIsEqualDeep, "baseIsEqualDeep");
+ function baseIsNative(value) {
+ if (!isObject2(value) || isMasked(value)) {
+ return false;
+ }
+ var pattern = isFunction2(value) ? reIsNative : reIsHostCtor;
+ return pattern.test(toSource(value));
+ }
+ __name(baseIsNative, "baseIsNative");
+ function baseIsTypedArray(value) {
+ return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
+ }
+ __name(baseIsTypedArray, "baseIsTypedArray");
+ function baseKeys(object) {
+ if (!isPrototype(object)) {
+ return nativeKeys(object);
+ }
+ var result = [];
+ for (var key in Object(object)) {
+ if (hasOwnProperty2.call(object, key) && key != "constructor") {
+ result.push(key);
+ }
+ }
+ return result;
+ }
+ __name(baseKeys, "baseKeys");
+ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length;
+ if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
+ return false;
+ }
+ var stacked = stack.get(array);
+ if (stacked && stack.get(other)) {
+ return stacked == other;
+ }
+ var index = -1, result = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : void 0;
+ stack.set(array, other);
+ stack.set(other, array);
+ while (++index < arrLength) {
+ var arrValue = array[index], othValue = other[index];
+ if (customizer) {
+ var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack);
+ }
+ if (compared !== void 0) {
+ if (compared) {
+ continue;
+ }
+ result = false;
+ break;
+ }
+ if (seen) {
+ if (!arraySome(other, function(othValue2, othIndex) {
+ if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) {
+ return seen.push(othIndex);
+ }
+ })) {
+ result = false;
+ break;
+ }
+ } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
+ result = false;
+ break;
+ }
+ }
+ stack["delete"](array);
+ stack["delete"](other);
+ return result;
+ }
+ __name(equalArrays, "equalArrays");
+ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
+ switch (tag) {
+ case dataViewTag:
+ if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) {
+ return false;
+ }
+ object = object.buffer;
+ other = other.buffer;
+ case arrayBufferTag:
+ if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array2(object), new Uint8Array2(other))) {
+ return false;
+ }
+ return true;
+ case boolTag:
+ case dateTag:
+ case numberTag:
+ return eq(+object, +other);
+ case errorTag:
+ return object.name == other.name && object.message == other.message;
+ case regexpTag:
+ case stringTag:
+ return object == other + "";
+ case mapTag:
+ var convert = mapToArray;
+ case setTag:
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
+ convert || (convert = setToArray);
+ if (object.size != other.size && !isPartial) {
+ return false;
+ }
+ var stacked = stack.get(object);
+ if (stacked) {
+ return stacked == other;
+ }
+ bitmask |= COMPARE_UNORDERED_FLAG;
+ stack.set(object, other);
+ var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
+ stack["delete"](object);
+ return result;
+ case symbolTag:
+ if (symbolValueOf) {
+ return symbolValueOf.call(object) == symbolValueOf.call(other);
+ }
+ }
+ return false;
+ }
+ __name(equalByTag, "equalByTag");
+ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
+ var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length;
+ if (objLength != othLength && !isPartial) {
+ return false;
+ }
+ var index = objLength;
+ while (index--) {
+ var key = objProps[index];
+ if (!(isPartial ? key in other : hasOwnProperty2.call(other, key))) {
+ return false;
+ }
+ }
+ var stacked = stack.get(object);
+ if (stacked && stack.get(other)) {
+ return stacked == other;
+ }
+ var result = true;
+ stack.set(object, other);
+ stack.set(other, object);
+ var skipCtor = isPartial;
+ while (++index < objLength) {
+ key = objProps[index];
+ var objValue = object[key], othValue = other[key];
+ if (customizer) {
+ var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack);
+ }
+ if (!(compared === void 0 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) {
+ result = false;
+ break;
+ }
+ skipCtor || (skipCtor = key == "constructor");
+ }
+ if (result && !skipCtor) {
+ var objCtor = object.constructor, othCtor = other.constructor;
+ if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) {
+ result = false;
+ }
+ }
+ stack["delete"](object);
+ stack["delete"](other);
+ return result;
+ }
+ __name(equalObjects, "equalObjects");
+ function getAllKeys(object) {
+ return baseGetAllKeys(object, keys, getSymbols);
+ }
+ __name(getAllKeys, "getAllKeys");
+ function getMapData(map, key) {
+ var data = map.__data__;
+ return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map;
+ }
+ __name(getMapData, "getMapData");
+ function getNative(object, key) {
+ var value = getValue(object, key);
+ return baseIsNative(value) ? value : void 0;
+ }
+ __name(getNative, "getNative");
+ function getRawTag(value) {
+ var isOwn = hasOwnProperty2.call(value, symToStringTag), tag = value[symToStringTag];
+ try {
+ value[symToStringTag] = void 0;
+ var unmasked = true;
+ } catch (e2) {
+ }
+ var result = nativeObjectToString.call(value);
+ if (unmasked) {
+ if (isOwn) {
+ value[symToStringTag] = tag;
+ } else {
+ delete value[symToStringTag];
+ }
+ }
+ return result;
+ }
+ __name(getRawTag, "getRawTag");
+ var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
+ if (object == null) {
+ return [];
+ }
+ object = Object(object);
+ return arrayFilter(nativeGetSymbols(object), function(symbol) {
+ return propertyIsEnumerable.call(object, symbol);
+ });
+ };
+ var getTag = baseGetTag;
+ if (DataView2 && getTag(new DataView2(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap2 && getTag(new WeakMap2()) != weakMapTag) {
+ getTag = /* @__PURE__ */ __name(function(value) {
+ var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : void 0, ctorString = Ctor ? toSource(Ctor) : "";
+ if (ctorString) {
+ switch (ctorString) {
+ case dataViewCtorString:
+ return dataViewTag;
+ case mapCtorString:
+ return mapTag;
+ case promiseCtorString:
+ return promiseTag;
+ case setCtorString:
+ return setTag;
+ case weakMapCtorString:
+ return weakMapTag;
+ }
+ }
+ return result;
+ }, "getTag");
+ }
+ function isIndex(value, length) {
+ length = length == null ? MAX_SAFE_INTEGER : length;
+ return !!length && (typeof value == "number" || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length);
+ }
+ __name(isIndex, "isIndex");
+ function isKeyable(value) {
+ var type = typeof value;
+ return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value !== "__proto__" : value === null;
+ }
+ __name(isKeyable, "isKeyable");
+ function isMasked(func) {
+ return !!maskSrcKey && maskSrcKey in func;
+ }
+ __name(isMasked, "isMasked");
+ function isPrototype(value) {
+ var Ctor = value && value.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto;
+ return value === proto;
+ }
+ __name(isPrototype, "isPrototype");
+ function objectToString(value) {
+ return nativeObjectToString.call(value);
+ }
+ __name(objectToString, "objectToString");
+ function toSource(func) {
+ if (func != null) {
+ try {
+ return funcToString.call(func);
+ } catch (e2) {
+ }
+ try {
+ return func + "";
+ } catch (e2) {
+ }
+ }
+ return "";
+ }
+ __name(toSource, "toSource");
+ function eq(value, other) {
+ return value === other || value !== value && other !== other;
+ }
+ __name(eq, "eq");
+ var isArguments = baseIsArguments(function() {
+ return arguments;
+ }()) ? baseIsArguments : function(value) {
+ return isObjectLike(value) && hasOwnProperty2.call(value, "callee") && !propertyIsEnumerable.call(value, "callee");
+ };
+ var isArray = Array.isArray;
+ function isArrayLike(value) {
+ return value != null && isLength(value.length) && !isFunction2(value);
+ }
+ __name(isArrayLike, "isArrayLike");
+ var isBuffer = nativeIsBuffer || stubFalse;
+ function isEqual(value, other) {
+ return baseIsEqual(value, other);
+ }
+ __name(isEqual, "isEqual");
+ function isFunction2(value) {
+ if (!isObject2(value)) {
+ return false;
+ }
+ var tag = baseGetTag(value);
+ return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
+ }
+ __name(isFunction2, "isFunction");
+ function isLength(value) {
+ return typeof value == "number" && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
+ }
+ __name(isLength, "isLength");
+ function isObject2(value) {
+ var type = typeof value;
+ return value != null && (type == "object" || type == "function");
+ }
+ __name(isObject2, "isObject");
+ function isObjectLike(value) {
+ return value != null && typeof value == "object";
+ }
+ __name(isObjectLike, "isObjectLike");
+ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
+ function keys(object) {
+ return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
+ }
+ __name(keys, "keys");
+ function stubArray() {
+ return [];
+ }
+ __name(stubArray, "stubArray");
+ function stubFalse() {
+ return false;
+ }
+ __name(stubFalse, "stubFalse");
+ module2.exports = isEqual;
+ }
+});
+
+// ../../node_modules/.pnpm/arr-rotate@1.0.0/node_modules/arr-rotate/index.js
+var require_arr_rotate = __commonJS({
+ "../../node_modules/.pnpm/arr-rotate@1.0.0/node_modules/arr-rotate/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = (input, n) => {
+ if (!Array.isArray(input)) {
+ throw new TypeError(`Expected an array, got ${typeof input}`);
+ }
+ const x = input.slice();
+ const num = typeof n === "number" ? n : 0;
+ return x.splice(-num % x.length).concat(x);
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/figures@3.2.0/node_modules/figures/index.js
+var require_figures3 = __commonJS({
+ "../../node_modules/.pnpm/figures@3.2.0/node_modules/figures/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var escapeStringRegexp = require_escape_string_regexp();
+ var { platform } = process;
+ var main2 = {
+ tick: "\u2714",
+ cross: "\u2716",
+ star: "\u2605",
+ square: "\u2587",
+ squareSmall: "\u25FB",
+ squareSmallFilled: "\u25FC",
+ play: "\u25B6",
+ circle: "\u25EF",
+ circleFilled: "\u25C9",
+ circleDotted: "\u25CC",
+ circleDouble: "\u25CE",
+ circleCircle: "\u24DE",
+ circleCross: "\u24E7",
+ circlePipe: "\u24BE",
+ circleQuestionMark: "?\u20DD",
+ bullet: "\u25CF",
+ dot: "\u2024",
+ line: "\u2500",
+ ellipsis: "\u2026",
+ pointer: "\u276F",
+ pointerSmall: "\u203A",
+ info: "\u2139",
+ warning: "\u26A0",
+ hamburger: "\u2630",
+ smiley: "\u32E1",
+ mustache: "\u0DF4",
+ heart: "\u2665",
+ nodejs: "\u2B22",
+ arrowUp: "\u2191",
+ arrowDown: "\u2193",
+ arrowLeft: "\u2190",
+ arrowRight: "\u2192",
+ radioOn: "\u25C9",
+ radioOff: "\u25EF",
+ checkboxOn: "\u2612",
+ checkboxOff: "\u2610",
+ checkboxCircleOn: "\u24E7",
+ checkboxCircleOff: "\u24BE",
+ questionMarkPrefix: "?\u20DD",
+ oneHalf: "\xBD",
+ oneThird: "\u2153",
+ oneQuarter: "\xBC",
+ oneFifth: "\u2155",
+ oneSixth: "\u2159",
+ oneSeventh: "\u2150",
+ oneEighth: "\u215B",
+ oneNinth: "\u2151",
+ oneTenth: "\u2152",
+ twoThirds: "\u2154",
+ twoFifths: "\u2156",
+ threeQuarters: "\xBE",
+ threeFifths: "\u2157",
+ threeEighths: "\u215C",
+ fourFifths: "\u2158",
+ fiveSixths: "\u215A",
+ fiveEighths: "\u215D",
+ sevenEighths: "\u215E"
+ };
+ var windows = {
+ tick: "\u221A",
+ cross: "\xD7",
+ star: "*",
+ square: "\u2588",
+ squareSmall: "[ ]",
+ squareSmallFilled: "[\u2588]",
+ play: "\u25BA",
+ circle: "( )",
+ circleFilled: "(*)",
+ circleDotted: "( )",
+ circleDouble: "( )",
+ circleCircle: "(\u25CB)",
+ circleCross: "(\xD7)",
+ circlePipe: "(\u2502)",
+ circleQuestionMark: "(?)",
+ bullet: "*",
+ dot: ".",
+ line: "\u2500",
+ ellipsis: "...",
+ pointer: ">",
+ pointerSmall: "\xBB",
+ info: "i",
+ warning: "\u203C",
+ hamburger: "\u2261",
+ smiley: "\u263A",
+ mustache: "\u250C\u2500\u2510",
+ heart: main2.heart,
+ nodejs: "\u2666",
+ arrowUp: main2.arrowUp,
+ arrowDown: main2.arrowDown,
+ arrowLeft: main2.arrowLeft,
+ arrowRight: main2.arrowRight,
+ radioOn: "(*)",
+ radioOff: "( )",
+ checkboxOn: "[\xD7]",
+ checkboxOff: "[ ]",
+ checkboxCircleOn: "(\xD7)",
+ checkboxCircleOff: "( )",
+ questionMarkPrefix: "\uFF1F",
+ oneHalf: "1/2",
+ oneThird: "1/3",
+ oneQuarter: "1/4",
+ oneFifth: "1/5",
+ oneSixth: "1/6",
+ oneSeventh: "1/7",
+ oneEighth: "1/8",
+ oneNinth: "1/9",
+ oneTenth: "1/10",
+ twoThirds: "2/3",
+ twoFifths: "2/5",
+ threeQuarters: "3/4",
+ threeFifths: "3/5",
+ threeEighths: "3/8",
+ fourFifths: "4/5",
+ fiveSixths: "5/6",
+ fiveEighths: "5/8",
+ sevenEighths: "7/8"
+ };
+ if (platform === "linux") {
+ main2.questionMarkPrefix = "?";
+ }
+ var figures = platform === "win32" ? windows : main2;
+ var fn2 = /* @__PURE__ */ __name((string) => {
+ if (figures === main2) {
+ return string;
+ }
+ for (const [key, value] of Object.entries(main2)) {
+ if (value === figures[key]) {
+ continue;
+ }
+ string = string.replace(new RegExp(escapeStringRegexp(value), "g"), figures[key]);
+ }
+ return string;
+ }, "fn");
+ module2.exports = Object.assign(fn2, figures);
+ module2.exports.main = main2;
+ module2.exports.windows = windows;
+ }
+});
+
+// ../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/Indicator.js
+var require_Indicator = __commonJS({
+ "../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/Indicator.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ var React18 = require_react();
+ var ink_1 = require_build2();
+ var figures = require_figures3();
+ var Indicator = /* @__PURE__ */ __name(({ isSelected = false }) => React18.createElement(ink_1.Box, { marginRight: 1 }, isSelected ? React18.createElement(ink_1.Text, { color: "blue" }, figures.pointer) : React18.createElement(ink_1.Text, null, " ")), "Indicator");
+ exports2.default = Indicator;
+ }
+});
+
+// ../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/Item.js
+var require_Item = __commonJS({
+ "../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/Item.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ var React18 = require_react();
+ var ink_1 = require_build2();
+ var Item = /* @__PURE__ */ __name(({ isSelected = false, label }) => React18.createElement(ink_1.Text, { color: isSelected ? "blue" : void 0 }, label), "Item");
+ exports2.default = Item;
+ }
+});
+
+// ../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/SelectInput.js
+var require_SelectInput = __commonJS({
+ "../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/SelectInput.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ var React18 = require_react();
+ var react_1 = require_react();
+ var isEqual = require_lodash2();
+ var arrayRotate = require_arr_rotate();
+ var ink_1 = require_build2();
+ var Indicator_1 = require_Indicator();
+ var Item_1 = require_Item();
+ function SelectInput4({ items = [], isFocused = true, initialIndex = 0, indicatorComponent = Indicator_1.default, itemComponent = Item_1.default, limit: customLimit, onSelect, onHighlight }) {
+ const [rotateIndex, setRotateIndex] = react_1.useState(0);
+ const [selectedIndex, setSelectedIndex] = react_1.useState(initialIndex);
+ const hasLimit = typeof customLimit === "number" && items.length > customLimit;
+ const limit = hasLimit ? Math.min(customLimit, items.length) : items.length;
+ const previousItems = react_1.useRef(items);
+ react_1.useEffect(() => {
+ if (!isEqual(previousItems.current.map((item) => item.value), items.map((item) => item.value))) {
+ setRotateIndex(0);
+ setSelectedIndex(0);
+ }
+ previousItems.current = items;
+ }, [items]);
+ ink_1.useInput(react_1.useCallback((input, key) => {
+ if (input === "k" || key.upArrow) {
+ const lastIndex = (hasLimit ? limit : items.length) - 1;
+ const atFirstIndex = selectedIndex === 0;
+ const nextIndex = hasLimit ? selectedIndex : lastIndex;
+ const nextRotateIndex = atFirstIndex ? rotateIndex + 1 : rotateIndex;
+ const nextSelectedIndex = atFirstIndex ? nextIndex : selectedIndex - 1;
+ setRotateIndex(nextRotateIndex);
+ setSelectedIndex(nextSelectedIndex);
+ const slicedItems2 = hasLimit ? arrayRotate(items, nextRotateIndex).slice(0, limit) : items;
+ if (typeof onHighlight === "function") {
+ onHighlight(slicedItems2[nextSelectedIndex]);
+ }
+ }
+ if (input === "j" || key.downArrow) {
+ const atLastIndex = selectedIndex === (hasLimit ? limit : items.length) - 1;
+ const nextIndex = hasLimit ? selectedIndex : 0;
+ const nextRotateIndex = atLastIndex ? rotateIndex - 1 : rotateIndex;
+ const nextSelectedIndex = atLastIndex ? nextIndex : selectedIndex + 1;
+ setRotateIndex(nextRotateIndex);
+ setSelectedIndex(nextSelectedIndex);
+ const slicedItems2 = hasLimit ? arrayRotate(items, nextRotateIndex).slice(0, limit) : items;
+ if (typeof onHighlight === "function") {
+ onHighlight(slicedItems2[nextSelectedIndex]);
+ }
+ }
+ if (key.return) {
+ const slicedItems2 = hasLimit ? arrayRotate(items, rotateIndex).slice(0, limit) : items;
+ if (typeof onSelect === "function") {
+ onSelect(slicedItems2[selectedIndex]);
+ }
+ }
+ }, [
+ hasLimit,
+ limit,
+ rotateIndex,
+ selectedIndex,
+ items,
+ onSelect,
+ onHighlight
+ ]), { isActive: isFocused });
+ const slicedItems = hasLimit ? arrayRotate(items, rotateIndex).slice(0, limit) : items;
+ return React18.createElement(ink_1.Box, { flexDirection: "column" }, slicedItems.map((item, index) => {
+ var _a2;
+ const isSelected = index === selectedIndex;
+ return React18.createElement(
+ ink_1.Box,
+ { key: (_a2 = item.key) !== null && _a2 !== void 0 ? _a2 : item.value },
+ React18.createElement(indicatorComponent, { isSelected }),
+ React18.createElement(itemComponent, { ...item, isSelected })
+ );
+ }));
+ }
+ __name(SelectInput4, "SelectInput");
+ exports2.default = SelectInput4;
+ }
+});
+
+// ../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/index.js
+var require_build3 = __commonJS({
+ "../../node_modules/.pnpm/ink-select-input@4.2.1_ink@3.2.0_react@17.0.2/node_modules/ink-select-input/build/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ var SelectInput_1 = require_SelectInput();
+ exports2.default = SelectInput_1.default;
+ var Indicator_1 = require_Indicator();
+ Object.defineProperty(exports2, "Indicator", { enumerable: true, get: function() {
+ return Indicator_1.default;
+ } });
+ var Item_1 = require_Item();
+ Object.defineProperty(exports2, "Item", { enumerable: true, get: function() {
+ return Item_1.default;
+ } });
+ }
+});
+
+// ../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js
+var require_object_hash = __commonJS({
+ "../../node_modules/.pnpm/object-hash@2.2.0/node_modules/object-hash/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var crypto6 = require("crypto");
+ exports2 = module2.exports = objectHash;
+ function objectHash(object, options14) {
+ options14 = applyDefaults(object, options14);
+ return hash(object, options14);
+ }
+ __name(objectHash, "objectHash");
+ exports2.sha1 = function(object) {
+ return objectHash(object);
+ };
+ exports2.keys = function(object) {
+ return objectHash(object, { excludeValues: true, algorithm: "sha1", encoding: "hex" });
+ };
+ exports2.MD5 = function(object) {
+ return objectHash(object, { algorithm: "md5", encoding: "hex" });
+ };
+ exports2.keysMD5 = function(object) {
+ return objectHash(object, { algorithm: "md5", encoding: "hex", excludeValues: true });
+ };
+ var hashes = crypto6.getHashes ? crypto6.getHashes().slice() : ["sha1", "md5"];
+ hashes.push("passthrough");
+ var encodings = ["buffer", "hex", "binary", "base64"];
+ function applyDefaults(object, sourceOptions) {
+ sourceOptions = sourceOptions || {};
+ var options14 = {};
+ options14.algorithm = sourceOptions.algorithm || "sha1";
+ options14.encoding = sourceOptions.encoding || "hex";
+ options14.excludeValues = sourceOptions.excludeValues ? true : false;
+ options14.algorithm = options14.algorithm.toLowerCase();
+ options14.encoding = options14.encoding.toLowerCase();
+ options14.ignoreUnknown = sourceOptions.ignoreUnknown !== true ? false : true;
+ options14.respectType = sourceOptions.respectType === false ? false : true;
+ options14.respectFunctionNames = sourceOptions.respectFunctionNames === false ? false : true;
+ options14.respectFunctionProperties = sourceOptions.respectFunctionProperties === false ? false : true;
+ options14.unorderedArrays = sourceOptions.unorderedArrays !== true ? false : true;
+ options14.unorderedSets = sourceOptions.unorderedSets === false ? false : true;
+ options14.unorderedObjects = sourceOptions.unorderedObjects === false ? false : true;
+ options14.replacer = sourceOptions.replacer || void 0;
+ options14.excludeKeys = sourceOptions.excludeKeys || void 0;
+ if (typeof object === "undefined") {
+ throw new Error("Object argument required.");
+ }
+ for (var i = 0; i < hashes.length; ++i) {
+ if (hashes[i].toLowerCase() === options14.algorithm.toLowerCase()) {
+ options14.algorithm = hashes[i];
+ }
+ }
+ if (hashes.indexOf(options14.algorithm) === -1) {
+ throw new Error('Algorithm "' + options14.algorithm + '" not supported. supported values: ' + hashes.join(", "));
+ }
+ if (encodings.indexOf(options14.encoding) === -1 && options14.algorithm !== "passthrough") {
+ throw new Error('Encoding "' + options14.encoding + '" not supported. supported values: ' + encodings.join(", "));
+ }
+ return options14;
+ }
+ __name(applyDefaults, "applyDefaults");
+ function isNativeFunction(f) {
+ if (typeof f !== "function") {
+ return false;
+ }
+ var exp = /^function\s+\w*\s*\(\s*\)\s*{\s+\[native code\]\s+}$/i;
+ return exp.exec(Function.prototype.toString.call(f)) != null;
+ }
+ __name(isNativeFunction, "isNativeFunction");
+ function hash(object, options14) {
+ var hashingStream;
+ if (options14.algorithm !== "passthrough") {
+ hashingStream = crypto6.createHash(options14.algorithm);
+ } else {
+ hashingStream = new PassThrough();
+ }
+ if (typeof hashingStream.write === "undefined") {
+ hashingStream.write = hashingStream.update;
+ hashingStream.end = hashingStream.update;
+ }
+ var hasher = typeHasher(options14, hashingStream);
+ hasher.dispatch(object);
+ if (!hashingStream.update) {
+ hashingStream.end("");
+ }
+ if (hashingStream.digest) {
+ return hashingStream.digest(options14.encoding === "buffer" ? void 0 : options14.encoding);
+ }
+ var buf = hashingStream.read();
+ if (options14.encoding === "buffer") {
+ return buf;
+ }
+ return buf.toString(options14.encoding);
+ }
+ __name(hash, "hash");
+ exports2.writeToStream = function(object, options14, stream2) {
+ if (typeof stream2 === "undefined") {
+ stream2 = options14;
+ options14 = {};
+ }
+ options14 = applyDefaults(object, options14);
+ return typeHasher(options14, stream2).dispatch(object);
+ };
+ function typeHasher(options14, writeTo, context2) {
+ context2 = context2 || [];
+ var write = /* @__PURE__ */ __name(function(str) {
+ if (writeTo.update) {
+ return writeTo.update(str, "utf8");
+ } else {
+ return writeTo.write(str, "utf8");
+ }
+ }, "write");
+ return {
+ dispatch: function(value) {
+ if (options14.replacer) {
+ value = options14.replacer(value);
+ }
+ var type = typeof value;
+ if (value === null) {
+ type = "null";
+ }
+ return this["_" + type](value);
+ },
+ _object: function(object) {
+ var pattern = /\[object (.*)\]/i;
+ var objString = Object.prototype.toString.call(object);
+ var objType = pattern.exec(objString);
+ if (!objType) {
+ objType = "unknown:[" + objString + "]";
+ } else {
+ objType = objType[1];
+ }
+ objType = objType.toLowerCase();
+ var objectNumber = null;
+ if ((objectNumber = context2.indexOf(object)) >= 0) {
+ return this.dispatch("[CIRCULAR:" + objectNumber + "]");
+ } else {
+ context2.push(object);
+ }
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer && Buffer.isBuffer(object)) {
+ write("buffer:");
+ return write(object);
+ }
+ if (objType !== "object" && objType !== "function" && objType !== "asyncfunction") {
+ if (this["_" + objType]) {
+ this["_" + objType](object);
+ } else if (options14.ignoreUnknown) {
+ return write("[" + objType + "]");
+ } else {
+ throw new Error('Unknown object type "' + objType + '"');
+ }
+ } else {
+ var keys = Object.keys(object);
+ if (options14.unorderedObjects) {
+ keys = keys.sort();
+ }
+ if (options14.respectType !== false && !isNativeFunction(object)) {
+ keys.splice(0, 0, "prototype", "__proto__", "constructor");
+ }
+ if (options14.excludeKeys) {
+ keys = keys.filter(function(key) {
+ return !options14.excludeKeys(key);
+ });
+ }
+ write("object:" + keys.length + ":");
+ var self2 = this;
+ return keys.forEach(function(key) {
+ self2.dispatch(key);
+ write(":");
+ if (!options14.excludeValues) {
+ self2.dispatch(object[key]);
+ }
+ write(",");
+ });
+ }
+ },
+ _array: function(arr, unordered) {
+ unordered = typeof unordered !== "undefined" ? unordered : options14.unorderedArrays !== false;
+ var self2 = this;
+ write("array:" + arr.length + ":");
+ if (!unordered || arr.length <= 1) {
+ return arr.forEach(function(entry) {
+ return self2.dispatch(entry);
+ });
+ }
+ var contextAdditions = [];
+ var entries = arr.map(function(entry) {
+ var strm = new PassThrough();
+ var localContext = context2.slice();
+ var hasher = typeHasher(options14, strm, localContext);
+ hasher.dispatch(entry);
+ contextAdditions = contextAdditions.concat(localContext.slice(context2.length));
+ return strm.read().toString();
+ });
+ context2 = context2.concat(contextAdditions);
+ entries.sort();
+ return this._array(entries, false);
+ },
+ _date: function(date) {
+ return write("date:" + date.toJSON());
+ },
+ _symbol: function(sym) {
+ return write("symbol:" + sym.toString());
+ },
+ _error: function(err) {
+ return write("error:" + err.toString());
+ },
+ _boolean: function(bool) {
+ return write("bool:" + bool.toString());
+ },
+ _string: function(string) {
+ write("string:" + string.length + ":");
+ write(string.toString());
+ },
+ _function: function(fn2) {
+ write("fn:");
+ if (isNativeFunction(fn2)) {
+ this.dispatch("[native]");
+ } else {
+ this.dispatch(fn2.toString());
+ }
+ if (options14.respectFunctionNames !== false) {
+ this.dispatch("function-name:" + String(fn2.name));
+ }
+ if (options14.respectFunctionProperties) {
+ this._object(fn2);
+ }
+ },
+ _number: function(number) {
+ return write("number:" + number.toString());
+ },
+ _xml: function(xml) {
+ return write("xml:" + xml.toString());
+ },
+ _null: function() {
+ return write("Null");
+ },
+ _undefined: function() {
+ return write("Undefined");
+ },
+ _regexp: function(regex) {
+ return write("regex:" + regex.toString());
+ },
+ _uint8array: function(arr) {
+ write("uint8array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _uint8clampedarray: function(arr) {
+ write("uint8clampedarray:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _int8array: function(arr) {
+ write("uint8array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _uint16array: function(arr) {
+ write("uint16array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _int16array: function(arr) {
+ write("uint16array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _uint32array: function(arr) {
+ write("uint32array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _int32array: function(arr) {
+ write("uint32array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _float32array: function(arr) {
+ write("float32array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _float64array: function(arr) {
+ write("float64array:");
+ return this.dispatch(Array.prototype.slice.call(arr));
+ },
+ _arraybuffer: function(arr) {
+ write("arraybuffer:");
+ return this.dispatch(new Uint8Array(arr));
+ },
+ _url: function(url3) {
+ return write("url:" + url3.toString(), "utf8");
+ },
+ _map: function(map) {
+ write("map:");
+ var arr = Array.from(map);
+ return this._array(arr, options14.unorderedSets !== false);
+ },
+ _set: function(set) {
+ write("set:");
+ var arr = Array.from(set);
+ return this._array(arr, options14.unorderedSets !== false);
+ },
+ _file: function(file) {
+ write("file:");
+ return this.dispatch([file.name, file.size, file.type, file.lastModfied]);
+ },
+ _blob: function() {
+ if (options14.ignoreUnknown) {
+ return write("[blob]");
+ }
+ throw Error('Hashing Blob objects is currently not supported\n(see https://github.com/puleos/object-hash/issues/26)\nUse "options.replacer" or "options.ignoreUnknown"\n');
+ },
+ _domwindow: function() {
+ return write("domwindow");
+ },
+ _bigint: function(number) {
+ return write("bigint:" + number.toString());
+ },
+ /* Node.js standard native objects */
+ _process: function() {
+ return write("process");
+ },
+ _timer: function() {
+ return write("timer");
+ },
+ _pipe: function() {
+ return write("pipe");
+ },
+ _tcp: function() {
+ return write("tcp");
+ },
+ _udp: function() {
+ return write("udp");
+ },
+ _tty: function() {
+ return write("tty");
+ },
+ _statwatcher: function() {
+ return write("statwatcher");
+ },
+ _securecontext: function() {
+ return write("securecontext");
+ },
+ _connection: function() {
+ return write("connection");
+ },
+ _zlib: function() {
+ return write("zlib");
+ },
+ _context: function() {
+ return write("context");
+ },
+ _nodescript: function() {
+ return write("nodescript");
+ },
+ _httpparser: function() {
+ return write("httpparser");
+ },
+ _dataview: function() {
+ return write("dataview");
+ },
+ _signal: function() {
+ return write("signal");
+ },
+ _fsevent: function() {
+ return write("fsevent");
+ },
+ _tlswrap: function() {
+ return write("tlswrap");
+ }
+ };
+ }
+ __name(typeHasher, "typeHasher");
+ function PassThrough() {
+ return {
+ buf: "",
+ write: function(b) {
+ this.buf += b;
+ },
+ end: function(b) {
+ this.buf += b;
+ },
+ read: function() {
+ return this.buf;
+ }
+ };
+ }
+ __name(PassThrough, "PassThrough");
+ }
+});
+
+// ../../node_modules/.pnpm/ink-table@3.0.0_ink@3.2.0_react@17.0.2/node_modules/ink-table/dist/index.js
+var require_dist3 = __commonJS({
+ "../../node_modules/.pnpm/ink-table@3.0.0_ink@3.2.0_react@17.0.2/node_modules/ink-table/dist/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var __importDefault = exports2 && exports2.__importDefault || function(mod) {
+ return mod && mod.__esModule ? mod : { "default": mod };
+ };
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ exports2.Skeleton = exports2.Cell = exports2.Header = void 0;
+ var react_1 = __importDefault(require_react());
+ var ink_1 = require_build2();
+ var object_hash_1 = require_object_hash();
+ var Table10 = class extends react_1.default.Component {
+ constructor() {
+ super(...arguments);
+ this.header = row({
+ cell: this.getConfig().skeleton,
+ padding: this.getConfig().padding,
+ skeleton: {
+ component: this.getConfig().skeleton,
+ // chars
+ line: "\u2500",
+ left: "\u250C",
+ right: "\u2510",
+ cross: "\u252C"
+ }
+ });
+ this.heading = row({
+ cell: this.getConfig().header,
+ padding: this.getConfig().padding,
+ skeleton: {
+ component: this.getConfig().skeleton,
+ // chars
+ line: " ",
+ left: "\u2502",
+ right: "\u2502",
+ cross: "\u2502"
+ }
+ });
+ this.separator = row({
+ cell: this.getConfig().skeleton,
+ padding: this.getConfig().padding,
+ skeleton: {
+ component: this.getConfig().skeleton,
+ // chars
+ line: "\u2500",
+ left: "\u251C",
+ right: "\u2524",
+ cross: "\u253C"
+ }
+ });
+ this.data = row({
+ cell: this.getConfig().cell,
+ padding: this.getConfig().padding,
+ skeleton: {
+ component: this.getConfig().skeleton,
+ // chars
+ line: " ",
+ left: "\u2502",
+ right: "\u2502",
+ cross: "\u2502"
+ }
+ });
+ this.footer = row({
+ cell: this.getConfig().skeleton,
+ padding: this.getConfig().padding,
+ skeleton: {
+ component: this.getConfig().skeleton,
+ // chars
+ line: "\u2500",
+ left: "\u2514",
+ right: "\u2518",
+ cross: "\u2534"
+ }
+ });
+ }
+ /**
+ * Merges provided configuration with defaults.
+ */
+ getConfig() {
+ return {
+ data: this.props.data,
+ columns: this.props.columns || this.getDataKeys(),
+ padding: this.props.padding || 1,
+ header: this.props.header || Header,
+ cell: this.props.cell || Cell,
+ skeleton: this.props.skeleton || Skeleton
+ };
+ }
+ /**
+ * Gets all keyes used in data by traversing through the data.
+ */
+ getDataKeys() {
+ let keys = /* @__PURE__ */ new Set();
+ for (const data of this.props.data) {
+ for (const key in data) {
+ keys.add(key);
+ }
+ }
+ return Array.from(keys);
+ }
+ /**
+ * Calculates the width of each column by finding
+ * the longest value in a cell of a particular column.
+ *
+ * Returns a list of column names and their widths.
+ */
+ getColumns() {
+ const { columns, padding } = this.getConfig();
+ const widths = columns.map((key) => {
+ const header = String(key).length;
+ const data = this.props.data.map((data2) => {
+ const value = data2[key];
+ if (value == void 0 || value == null)
+ return 0;
+ return String(value).length;
+ });
+ const width = Math.max(...data, header) + padding * 2;
+ return {
+ column: key,
+ width,
+ key: String(key)
+ };
+ });
+ return widths;
+ }
+ /**
+ * Returns a (data) row representing the headings.
+ */
+ getHeadings() {
+ const { columns } = this.getConfig();
+ const headings = columns.reduce((acc, column) => ({ ...acc, [column]: column }), {});
+ return headings;
+ }
+ /* Render */
+ render() {
+ const columns = this.getColumns();
+ const headings = this.getHeadings();
+ return react_1.default.createElement(
+ ink_1.Box,
+ { flexDirection: "column" },
+ this.header({ key: "header", columns, data: {} }),
+ this.heading({ key: "heading", columns, data: headings }),
+ this.props.data.map((row2, index) => {
+ const key = `row-${object_hash_1.sha1(row2)}-${index}`;
+ return react_1.default.createElement(
+ ink_1.Box,
+ { flexDirection: "column", key },
+ this.separator({ key: `separator-${key}`, columns, data: {} }),
+ this.data({ key: `data-${key}`, columns, data: row2 })
+ );
+ }),
+ this.footer({ key: "footer", columns, data: {} })
+ );
+ }
+ };
+ __name(Table10, "Table");
+ exports2.default = Table10;
+ function row(config) {
+ const skeleton = config.skeleton;
+ return (props) => react_1.default.createElement(
+ ink_1.Box,
+ { flexDirection: "row" },
+ react_1.default.createElement(skeleton.component, null, skeleton.left),
+ intersperse(
+ (i) => {
+ const key = `${props.key}-hseparator-${i}`;
+ return react_1.default.createElement(skeleton.component, { key }, skeleton.cross);
+ },
+ // Values.
+ props.columns.map((column) => {
+ const value = props.data[column.column];
+ if (value == void 0 || value == null) {
+ const key = `${props.key}-empty-${column.key}`;
+ return react_1.default.createElement(config.cell, { key }, skeleton.line.repeat(column.width));
+ } else {
+ const key = `${props.key}-cell-${column.key}`;
+ const ml = config.padding;
+ const mr = column.width - String(value).length - config.padding;
+ return (
+ /* prettier-ignore */
+ react_1.default.createElement(config.cell, { key }, `${skeleton.line.repeat(ml)}${String(value)}${skeleton.line.repeat(mr)}`)
+ );
+ }
+ })
+ ),
+ react_1.default.createElement(skeleton.component, null, skeleton.right)
+ );
+ }
+ __name(row, "row");
+ function Header(props) {
+ return react_1.default.createElement(ink_1.Text, { bold: true, color: "blue" }, props.children);
+ }
+ __name(Header, "Header");
+ exports2.Header = Header;
+ function Cell(props) {
+ return react_1.default.createElement(ink_1.Text, null, props.children);
+ }
+ __name(Cell, "Cell");
+ exports2.Cell = Cell;
+ function Skeleton(props) {
+ return react_1.default.createElement(ink_1.Text, { bold: true }, props.children);
+ }
+ __name(Skeleton, "Skeleton");
+ exports2.Skeleton = Skeleton;
+ function intersperse(intersperser, elements) {
+ let interspersed = elements.reduce((acc, element, index) => {
+ if (acc.length === 0)
+ return [element];
+ return [...acc, intersperser(index), element];
+ }, []);
+ return interspersed;
+ }
+ __name(intersperse, "intersperse");
+ }
+});
+
+// ../../node_modules/.pnpm/ignore@5.2.0/node_modules/ignore/index.js
+var require_ignore = __commonJS({
+ "../../node_modules/.pnpm/ignore@5.2.0/node_modules/ignore/index.js"(exports2, module2) {
+ init_import_meta_url();
+ function makeArray(subject) {
+ return Array.isArray(subject) ? subject : [subject];
+ }
+ __name(makeArray, "makeArray");
+ var EMPTY = "";
+ var SPACE = " ";
+ var ESCAPE = "\\";
+ var REGEX_TEST_BLANK_LINE = /^\s+$/;
+ var REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/;
+ var REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/;
+ var REGEX_SPLITALL_CRLF = /\r?\n/g;
+ var REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/;
+ var SLASH = "/";
+ var KEY_IGNORE = typeof Symbol !== "undefined" ? Symbol.for("node-ignore") : "node-ignore";
+ var define2 = /* @__PURE__ */ __name((object, key, value) => Object.defineProperty(object, key, { value }), "define");
+ var REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g;
+ var RETURN_FALSE = /* @__PURE__ */ __name(() => false, "RETURN_FALSE");
+ var sanitizeRange = /* @__PURE__ */ __name((range) => range.replace(
+ REGEX_REGEXP_RANGE,
+ (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) ? match : EMPTY
+ ), "sanitizeRange");
+ var cleanRangeBackSlash = /* @__PURE__ */ __name((slashes) => {
+ const { length } = slashes;
+ return slashes.slice(0, length - length % 2);
+ }, "cleanRangeBackSlash");
+ var REPLACERS = [
+ // > Trailing spaces are ignored unless they are quoted with backslash ("\")
+ [
+ // (a\ ) -> (a )
+ // (a ) -> (a)
+ // (a \ ) -> (a )
+ /\\?\s+$/,
+ (match) => match.indexOf("\\") === 0 ? SPACE : EMPTY
+ ],
+ // replace (\ ) with ' '
+ [
+ /\\\s/g,
+ () => SPACE
+ ],
+ // Escape metacharacters
+ // which is written down by users but means special for regular expressions.
+ // > There are 12 characters with special meanings:
+ // > - the backslash \,
+ // > - the caret ^,
+ // > - the dollar sign $,
+ // > - the period or dot .,
+ // > - the vertical bar or pipe symbol |,
+ // > - the question mark ?,
+ // > - the asterisk or star *,
+ // > - the plus sign +,
+ // > - the opening parenthesis (,
+ // > - the closing parenthesis ),
+ // > - and the opening square bracket [,
+ // > - the opening curly brace {,
+ // > These special characters are often called "metacharacters".
+ [
+ /[\\$.|*+(){^]/g,
+ (match) => `\\${match}`
+ ],
+ [
+ // > a question mark (?) matches a single character
+ /(?!\\)\?/g,
+ () => "[^/]"
+ ],
+ // leading slash
+ [
+ // > A leading slash matches the beginning of the pathname.
+ // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".
+ // A leading slash matches the beginning of the pathname
+ /^\//,
+ () => "^"
+ ],
+ // replace special metacharacter slash after the leading slash
+ [
+ /\//g,
+ () => "\\/"
+ ],
+ [
+ // > A leading "**" followed by a slash means match in all directories.
+ // > For example, "**/foo" matches file or directory "foo" anywhere,
+ // > the same as pattern "foo".
+ // > "**/foo/bar" matches file or directory "bar" anywhere that is directly
+ // > under directory "foo".
+ // Notice that the '*'s have been replaced as '\\*'
+ /^\^*\\\*\\\*\\\//,
+ // '**/foo' <-> 'foo'
+ () => "^(?:.*\\/)?"
+ ],
+ // starting
+ [
+ // there will be no leading '/'
+ // (which has been replaced by section "leading slash")
+ // If starts with '**', adding a '^' to the regular expression also works
+ /^(?=[^^])/,
+ /* @__PURE__ */ __name(function startingReplacer() {
+ return !/\/(?!$)/.test(this) ? "(?:^|\\/)" : "^";
+ }, "startingReplacer")
+ ],
+ // two globstars
+ [
+ // Use lookahead assertions so that we could match more than one `'/**'`
+ /\\\/\\\*\\\*(?=\\\/|$)/g,
+ // Zero, one or several directories
+ // should not use '*', or it will be replaced by the next replacer
+ // Check if it is not the last `'/**'`
+ (_2, index, str) => index + 6 < str.length ? "(?:\\/[^\\/]+)*" : "\\/.+"
+ ],
+ // intermediate wildcards
+ [
+ // Never replace escaped '*'
+ // ignore rule '\*' will match the path '*'
+ // 'abc.*/' -> go
+ // 'abc.*' -> skip this rule
+ /(^|[^\\]+)\\\*(?=.+)/g,
+ // '*.js' matches '.js'
+ // '*.js' doesn't match 'abc'
+ (_2, p1) => `${p1}[^\\/]*`
+ ],
+ [
+ // unescape, revert step 3 except for back slash
+ // For example, if a user escape a '\\*',
+ // after step 3, the result will be '\\\\\\*'
+ /\\\\\\(?=[$.|*+(){^])/g,
+ () => ESCAPE
+ ],
+ [
+ // '\\\\' -> '\\'
+ /\\\\/g,
+ () => ESCAPE
+ ],
+ [
+ // > The range notation, e.g. [a-zA-Z],
+ // > can be used to match one of the characters in a range.
+ // `\` is escaped by step 3
+ /(\\)?\[([^\]/]*?)(\\*)($|\])/g,
+ (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` : close === "]" ? endEscape.length % 2 === 0 ? `[${sanitizeRange(range)}${endEscape}]` : "[]" : "[]"
+ ],
+ // ending
+ [
+ // 'js' will not match 'js.'
+ // 'ab' will not match 'abc'
+ /(?:[^*])$/,
+ // WTF!
+ // https://git-scm.com/docs/gitignore
+ // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)
+ // which re-fixes #24, #38
+ // > If there is a separator at the end of the pattern then the pattern
+ // > will only match directories, otherwise the pattern can match both
+ // > files and directories.
+ // 'js*' will not match 'a.js'
+ // 'js/' will not match 'a.js'
+ // 'js' will match 'a.js' and 'a.js/'
+ (match) => /\/$/.test(match) ? `${match}$` : `${match}(?=$|\\/$)`
+ ],
+ // trailing wildcard
+ [
+ /(\^|\\\/)?\\\*$/,
+ (_2, p1) => {
+ const prefix = p1 ? `${p1}[^/]+` : "[^/]*";
+ return `${prefix}(?=$|\\/$)`;
+ }
+ ]
+ ];
+ var regexCache = /* @__PURE__ */ Object.create(null);
+ var makeRegex = /* @__PURE__ */ __name((pattern, ignoreCase) => {
+ let source = regexCache[pattern];
+ if (!source) {
+ source = REPLACERS.reduce(
+ (prev, current) => prev.replace(current[0], current[1].bind(pattern)),
+ pattern
+ );
+ regexCache[pattern] = source;
+ }
+ return ignoreCase ? new RegExp(source, "i") : new RegExp(source);
+ }, "makeRegex");
+ var isString2 = /* @__PURE__ */ __name((subject) => typeof subject === "string", "isString");
+ var checkPattern = /* @__PURE__ */ __name((pattern) => pattern && isString2(pattern) && !REGEX_TEST_BLANK_LINE.test(pattern) && pattern.indexOf("#") !== 0, "checkPattern");
+ var splitPattern = /* @__PURE__ */ __name((pattern) => pattern.split(REGEX_SPLITALL_CRLF), "splitPattern");
+ var IgnoreRule = class {
+ constructor(origin, pattern, negative, regex) {
+ this.origin = origin;
+ this.pattern = pattern;
+ this.negative = negative;
+ this.regex = regex;
+ }
+ };
+ __name(IgnoreRule, "IgnoreRule");
+ var createRule = /* @__PURE__ */ __name((pattern, ignoreCase) => {
+ const origin = pattern;
+ let negative = false;
+ if (pattern.indexOf("!") === 0) {
+ negative = true;
+ pattern = pattern.substr(1);
+ }
+ pattern = pattern.replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, "!").replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, "#");
+ const regex = makeRegex(pattern, ignoreCase);
+ return new IgnoreRule(
+ origin,
+ pattern,
+ negative,
+ regex
+ );
+ }, "createRule");
+ var throwError = /* @__PURE__ */ __name((message, Ctor) => {
+ throw new Ctor(message);
+ }, "throwError");
+ var checkPath = /* @__PURE__ */ __name((path45, originalPath, doThrow) => {
+ if (!isString2(path45)) {
+ return doThrow(
+ `path must be a string, but got \`${originalPath}\``,
+ TypeError
+ );
+ }
+ if (!path45) {
+ return doThrow(`path must not be empty`, TypeError);
+ }
+ if (checkPath.isNotRelative(path45)) {
+ const r = "`path.relative()`d";
+ return doThrow(
+ `path should be a ${r} string, but got "${originalPath}"`,
+ RangeError
+ );
+ }
+ return true;
+ }, "checkPath");
+ var isNotRelative = /* @__PURE__ */ __name((path45) => REGEX_TEST_INVALID_PATH.test(path45), "isNotRelative");
+ checkPath.isNotRelative = isNotRelative;
+ checkPath.convert = (p) => p;
+ var Ignore = class {
+ constructor({
+ ignorecase = true,
+ ignoreCase = ignorecase,
+ allowRelativePaths = false
+ } = {}) {
+ define2(this, KEY_IGNORE, true);
+ this._rules = [];
+ this._ignoreCase = ignoreCase;
+ this._allowRelativePaths = allowRelativePaths;
+ this._initCache();
+ }
+ _initCache() {
+ this._ignoreCache = /* @__PURE__ */ Object.create(null);
+ this._testCache = /* @__PURE__ */ Object.create(null);
+ }
+ _addPattern(pattern) {
+ if (pattern && pattern[KEY_IGNORE]) {
+ this._rules = this._rules.concat(pattern._rules);
+ this._added = true;
+ return;
+ }
+ if (checkPattern(pattern)) {
+ const rule = createRule(pattern, this._ignoreCase);
+ this._added = true;
+ this._rules.push(rule);
+ }
+ }
+ // @param {Array | string | Ignore} pattern
+ add(pattern) {
+ this._added = false;
+ makeArray(
+ isString2(pattern) ? splitPattern(pattern) : pattern
+ ).forEach(this._addPattern, this);
+ if (this._added) {
+ this._initCache();
+ }
+ return this;
+ }
+ // legacy
+ addPattern(pattern) {
+ return this.add(pattern);
+ }
+ // | ignored : unignored
+ // negative | 0:0 | 0:1 | 1:0 | 1:1
+ // -------- | ------- | ------- | ------- | --------
+ // 0 | TEST | TEST | SKIP | X
+ // 1 | TESTIF | SKIP | TEST | X
+ // - SKIP: always skip
+ // - TEST: always test
+ // - TESTIF: only test if checkUnignored
+ // - X: that never happen
+ // @param {boolean} whether should check if the path is unignored,
+ // setting `checkUnignored` to `false` could reduce additional
+ // path matching.
+ // @returns {TestResult} true if a file is ignored
+ _testOne(path45, checkUnignored) {
+ let ignored = false;
+ let unignored = false;
+ this._rules.forEach((rule) => {
+ const { negative } = rule;
+ if (unignored === negative && ignored !== unignored || negative && !ignored && !unignored && !checkUnignored) {
+ return;
+ }
+ const matched = rule.regex.test(path45);
+ if (matched) {
+ ignored = !negative;
+ unignored = negative;
+ }
+ });
+ return {
+ ignored,
+ unignored
+ };
+ }
+ // @returns {TestResult}
+ _test(originalPath, cache2, checkUnignored, slices) {
+ const path45 = originalPath && checkPath.convert(originalPath);
+ checkPath(
+ path45,
+ originalPath,
+ this._allowRelativePaths ? RETURN_FALSE : throwError
+ );
+ return this._t(path45, cache2, checkUnignored, slices);
+ }
+ _t(path45, cache2, checkUnignored, slices) {
+ if (path45 in cache2) {
+ return cache2[path45];
+ }
+ if (!slices) {
+ slices = path45.split(SLASH);
+ }
+ slices.pop();
+ if (!slices.length) {
+ return cache2[path45] = this._testOne(path45, checkUnignored);
+ }
+ const parent = this._t(
+ slices.join(SLASH) + SLASH,
+ cache2,
+ checkUnignored,
+ slices
+ );
+ return cache2[path45] = parent.ignored ? parent : this._testOne(path45, checkUnignored);
+ }
+ ignores(path45) {
+ return this._test(path45, this._ignoreCache, false).ignored;
+ }
+ createFilter() {
+ return (path45) => !this.ignores(path45);
+ }
+ filter(paths) {
+ return makeArray(paths).filter(this.createFilter());
+ }
+ // @returns {TestResult}
+ test(path45) {
+ return this._test(path45, this._testCache, true);
+ }
+ };
+ __name(Ignore, "Ignore");
+ var factory = /* @__PURE__ */ __name((options14) => new Ignore(options14), "factory");
+ var isPathValid = /* @__PURE__ */ __name((path45) => checkPath(path45 && checkPath.convert(path45), path45, RETURN_FALSE), "isPathValid");
+ factory.isPathValid = isPathValid;
+ factory.default = factory;
+ module2.exports = factory;
+ if (
+ // Detect `process` so that it can run in browsers.
+ typeof process !== "undefined" && (process.env && process.env.IGNORE_TEST_WIN32 || process.platform === "win32")
+ ) {
+ const makePosix = /* @__PURE__ */ __name((str) => /^\\\\\?\\/.test(str) || /["<>|\u0000-\u001F]+/u.test(str) ? str : str.replace(/\\/g, "/"), "makePosix");
+ checkPath.convert = makePosix;
+ const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i;
+ checkPath.isNotRelative = (path45) => REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path45) || isNotRelative(path45);
+ }
+ }
+});
+
+// ../../node_modules/.pnpm/cli-spinners@2.6.1/node_modules/cli-spinners/spinners.json
+var require_spinners = __commonJS({
+ "../../node_modules/.pnpm/cli-spinners@2.6.1/node_modules/cli-spinners/spinners.json"(exports2, module2) {
+ module2.exports = {
+ dots: {
+ interval: 80,
+ frames: [
+ "\u280B",
+ "\u2819",
+ "\u2839",
+ "\u2838",
+ "\u283C",
+ "\u2834",
+ "\u2826",
+ "\u2827",
+ "\u2807",
+ "\u280F"
+ ]
+ },
+ dots2: {
+ interval: 80,
+ frames: [
+ "\u28FE",
+ "\u28FD",
+ "\u28FB",
+ "\u28BF",
+ "\u287F",
+ "\u28DF",
+ "\u28EF",
+ "\u28F7"
+ ]
+ },
+ dots3: {
+ interval: 80,
+ frames: [
+ "\u280B",
+ "\u2819",
+ "\u281A",
+ "\u281E",
+ "\u2816",
+ "\u2826",
+ "\u2834",
+ "\u2832",
+ "\u2833",
+ "\u2813"
+ ]
+ },
+ dots4: {
+ interval: 80,
+ frames: [
+ "\u2804",
+ "\u2806",
+ "\u2807",
+ "\u280B",
+ "\u2819",
+ "\u2838",
+ "\u2830",
+ "\u2820",
+ "\u2830",
+ "\u2838",
+ "\u2819",
+ "\u280B",
+ "\u2807",
+ "\u2806"
+ ]
+ },
+ dots5: {
+ interval: 80,
+ frames: [
+ "\u280B",
+ "\u2819",
+ "\u281A",
+ "\u2812",
+ "\u2802",
+ "\u2802",
+ "\u2812",
+ "\u2832",
+ "\u2834",
+ "\u2826",
+ "\u2816",
+ "\u2812",
+ "\u2810",
+ "\u2810",
+ "\u2812",
+ "\u2813",
+ "\u280B"
+ ]
+ },
+ dots6: {
+ interval: 80,
+ frames: [
+ "\u2801",
+ "\u2809",
+ "\u2819",
+ "\u281A",
+ "\u2812",
+ "\u2802",
+ "\u2802",
+ "\u2812",
+ "\u2832",
+ "\u2834",
+ "\u2824",
+ "\u2804",
+ "\u2804",
+ "\u2824",
+ "\u2834",
+ "\u2832",
+ "\u2812",
+ "\u2802",
+ "\u2802",
+ "\u2812",
+ "\u281A",
+ "\u2819",
+ "\u2809",
+ "\u2801"
+ ]
+ },
+ dots7: {
+ interval: 80,
+ frames: [
+ "\u2808",
+ "\u2809",
+ "\u280B",
+ "\u2813",
+ "\u2812",
+ "\u2810",
+ "\u2810",
+ "\u2812",
+ "\u2816",
+ "\u2826",
+ "\u2824",
+ "\u2820",
+ "\u2820",
+ "\u2824",
+ "\u2826",
+ "\u2816",
+ "\u2812",
+ "\u2810",
+ "\u2810",
+ "\u2812",
+ "\u2813",
+ "\u280B",
+ "\u2809",
+ "\u2808"
+ ]
+ },
+ dots8: {
+ interval: 80,
+ frames: [
+ "\u2801",
+ "\u2801",
+ "\u2809",
+ "\u2819",
+ "\u281A",
+ "\u2812",
+ "\u2802",
+ "\u2802",
+ "\u2812",
+ "\u2832",
+ "\u2834",
+ "\u2824",
+ "\u2804",
+ "\u2804",
+ "\u2824",
+ "\u2820",
+ "\u2820",
+ "\u2824",
+ "\u2826",
+ "\u2816",
+ "\u2812",
+ "\u2810",
+ "\u2810",
+ "\u2812",
+ "\u2813",
+ "\u280B",
+ "\u2809",
+ "\u2808",
+ "\u2808"
+ ]
+ },
+ dots9: {
+ interval: 80,
+ frames: [
+ "\u28B9",
+ "\u28BA",
+ "\u28BC",
+ "\u28F8",
+ "\u28C7",
+ "\u2867",
+ "\u2857",
+ "\u284F"
+ ]
+ },
+ dots10: {
+ interval: 80,
+ frames: [
+ "\u2884",
+ "\u2882",
+ "\u2881",
+ "\u2841",
+ "\u2848",
+ "\u2850",
+ "\u2860"
+ ]
+ },
+ dots11: {
+ interval: 100,
+ frames: [
+ "\u2801",
+ "\u2802",
+ "\u2804",
+ "\u2840",
+ "\u2880",
+ "\u2820",
+ "\u2810",
+ "\u2808"
+ ]
+ },
+ dots12: {
+ interval: 80,
+ frames: [
+ "\u2880\u2800",
+ "\u2840\u2800",
+ "\u2804\u2800",
+ "\u2882\u2800",
+ "\u2842\u2800",
+ "\u2805\u2800",
+ "\u2883\u2800",
+ "\u2843\u2800",
+ "\u280D\u2800",
+ "\u288B\u2800",
+ "\u284B\u2800",
+ "\u280D\u2801",
+ "\u288B\u2801",
+ "\u284B\u2801",
+ "\u280D\u2809",
+ "\u280B\u2809",
+ "\u280B\u2809",
+ "\u2809\u2819",
+ "\u2809\u2819",
+ "\u2809\u2829",
+ "\u2808\u2899",
+ "\u2808\u2859",
+ "\u2888\u2829",
+ "\u2840\u2899",
+ "\u2804\u2859",
+ "\u2882\u2829",
+ "\u2842\u2898",
+ "\u2805\u2858",
+ "\u2883\u2828",
+ "\u2843\u2890",
+ "\u280D\u2850",
+ "\u288B\u2820",
+ "\u284B\u2880",
+ "\u280D\u2841",
+ "\u288B\u2801",
+ "\u284B\u2801",
+ "\u280D\u2809",
+ "\u280B\u2809",
+ "\u280B\u2809",
+ "\u2809\u2819",
+ "\u2809\u2819",
+ "\u2809\u2829",
+ "\u2808\u2899",
+ "\u2808\u2859",
+ "\u2808\u2829",
+ "\u2800\u2899",
+ "\u2800\u2859",
+ "\u2800\u2829",
+ "\u2800\u2898",
+ "\u2800\u2858",
+ "\u2800\u2828",
+ "\u2800\u2890",
+ "\u2800\u2850",
+ "\u2800\u2820",
+ "\u2800\u2880",
+ "\u2800\u2840"
+ ]
+ },
+ dots8Bit: {
+ interval: 80,
+ frames: [
+ "\u2800",
+ "\u2801",
+ "\u2802",
+ "\u2803",
+ "\u2804",
+ "\u2805",
+ "\u2806",
+ "\u2807",
+ "\u2840",
+ "\u2841",
+ "\u2842",
+ "\u2843",
+ "\u2844",
+ "\u2845",
+ "\u2846",
+ "\u2847",
+ "\u2808",
+ "\u2809",
+ "\u280A",
+ "\u280B",
+ "\u280C",
+ "\u280D",
+ "\u280E",
+ "\u280F",
+ "\u2848",
+ "\u2849",
+ "\u284A",
+ "\u284B",
+ "\u284C",
+ "\u284D",
+ "\u284E",
+ "\u284F",
+ "\u2810",
+ "\u2811",
+ "\u2812",
+ "\u2813",
+ "\u2814",
+ "\u2815",
+ "\u2816",
+ "\u2817",
+ "\u2850",
+ "\u2851",
+ "\u2852",
+ "\u2853",
+ "\u2854",
+ "\u2855",
+ "\u2856",
+ "\u2857",
+ "\u2818",
+ "\u2819",
+ "\u281A",
+ "\u281B",
+ "\u281C",
+ "\u281D",
+ "\u281E",
+ "\u281F",
+ "\u2858",
+ "\u2859",
+ "\u285A",
+ "\u285B",
+ "\u285C",
+ "\u285D",
+ "\u285E",
+ "\u285F",
+ "\u2820",
+ "\u2821",
+ "\u2822",
+ "\u2823",
+ "\u2824",
+ "\u2825",
+ "\u2826",
+ "\u2827",
+ "\u2860",
+ "\u2861",
+ "\u2862",
+ "\u2863",
+ "\u2864",
+ "\u2865",
+ "\u2866",
+ "\u2867",
+ "\u2828",
+ "\u2829",
+ "\u282A",
+ "\u282B",
+ "\u282C",
+ "\u282D",
+ "\u282E",
+ "\u282F",
+ "\u2868",
+ "\u2869",
+ "\u286A",
+ "\u286B",
+ "\u286C",
+ "\u286D",
+ "\u286E",
+ "\u286F",
+ "\u2830",
+ "\u2831",
+ "\u2832",
+ "\u2833",
+ "\u2834",
+ "\u2835",
+ "\u2836",
+ "\u2837",
+ "\u2870",
+ "\u2871",
+ "\u2872",
+ "\u2873",
+ "\u2874",
+ "\u2875",
+ "\u2876",
+ "\u2877",
+ "\u2838",
+ "\u2839",
+ "\u283A",
+ "\u283B",
+ "\u283C",
+ "\u283D",
+ "\u283E",
+ "\u283F",
+ "\u2878",
+ "\u2879",
+ "\u287A",
+ "\u287B",
+ "\u287C",
+ "\u287D",
+ "\u287E",
+ "\u287F",
+ "\u2880",
+ "\u2881",
+ "\u2882",
+ "\u2883",
+ "\u2884",
+ "\u2885",
+ "\u2886",
+ "\u2887",
+ "\u28C0",
+ "\u28C1",
+ "\u28C2",
+ "\u28C3",
+ "\u28C4",
+ "\u28C5",
+ "\u28C6",
+ "\u28C7",
+ "\u2888",
+ "\u2889",
+ "\u288A",
+ "\u288B",
+ "\u288C",
+ "\u288D",
+ "\u288E",
+ "\u288F",
+ "\u28C8",
+ "\u28C9",
+ "\u28CA",
+ "\u28CB",
+ "\u28CC",
+ "\u28CD",
+ "\u28CE",
+ "\u28CF",
+ "\u2890",
+ "\u2891",
+ "\u2892",
+ "\u2893",
+ "\u2894",
+ "\u2895",
+ "\u2896",
+ "\u2897",
+ "\u28D0",
+ "\u28D1",
+ "\u28D2",
+ "\u28D3",
+ "\u28D4",
+ "\u28D5",
+ "\u28D6",
+ "\u28D7",
+ "\u2898",
+ "\u2899",
+ "\u289A",
+ "\u289B",
+ "\u289C",
+ "\u289D",
+ "\u289E",
+ "\u289F",
+ "\u28D8",
+ "\u28D9",
+ "\u28DA",
+ "\u28DB",
+ "\u28DC",
+ "\u28DD",
+ "\u28DE",
+ "\u28DF",
+ "\u28A0",
+ "\u28A1",
+ "\u28A2",
+ "\u28A3",
+ "\u28A4",
+ "\u28A5",
+ "\u28A6",
+ "\u28A7",
+ "\u28E0",
+ "\u28E1",
+ "\u28E2",
+ "\u28E3",
+ "\u28E4",
+ "\u28E5",
+ "\u28E6",
+ "\u28E7",
+ "\u28A8",
+ "\u28A9",
+ "\u28AA",
+ "\u28AB",
+ "\u28AC",
+ "\u28AD",
+ "\u28AE",
+ "\u28AF",
+ "\u28E8",
+ "\u28E9",
+ "\u28EA",
+ "\u28EB",
+ "\u28EC",
+ "\u28ED",
+ "\u28EE",
+ "\u28EF",
+ "\u28B0",
+ "\u28B1",
+ "\u28B2",
+ "\u28B3",
+ "\u28B4",
+ "\u28B5",
+ "\u28B6",
+ "\u28B7",
+ "\u28F0",
+ "\u28F1",
+ "\u28F2",
+ "\u28F3",
+ "\u28F4",
+ "\u28F5",
+ "\u28F6",
+ "\u28F7",
+ "\u28B8",
+ "\u28B9",
+ "\u28BA",
+ "\u28BB",
+ "\u28BC",
+ "\u28BD",
+ "\u28BE",
+ "\u28BF",
+ "\u28F8",
+ "\u28F9",
+ "\u28FA",
+ "\u28FB",
+ "\u28FC",
+ "\u28FD",
+ "\u28FE",
+ "\u28FF"
+ ]
+ },
+ line: {
+ interval: 130,
+ frames: [
+ "-",
+ "\\",
+ "|",
+ "/"
+ ]
+ },
+ line2: {
+ interval: 100,
+ frames: [
+ "\u2802",
+ "-",
+ "\u2013",
+ "\u2014",
+ "\u2013",
+ "-"
+ ]
+ },
+ pipe: {
+ interval: 100,
+ frames: [
+ "\u2524",
+ "\u2518",
+ "\u2534",
+ "\u2514",
+ "\u251C",
+ "\u250C",
+ "\u252C",
+ "\u2510"
+ ]
+ },
+ simpleDots: {
+ interval: 400,
+ frames: [
+ ". ",
+ ".. ",
+ "...",
+ " "
+ ]
+ },
+ simpleDotsScrolling: {
+ interval: 200,
+ frames: [
+ ". ",
+ ".. ",
+ "...",
+ " ..",
+ " .",
+ " "
+ ]
+ },
+ star: {
+ interval: 70,
+ frames: [
+ "\u2736",
+ "\u2738",
+ "\u2739",
+ "\u273A",
+ "\u2739",
+ "\u2737"
+ ]
+ },
+ star2: {
+ interval: 80,
+ frames: [
+ "+",
+ "x",
+ "*"
+ ]
+ },
+ flip: {
+ interval: 70,
+ frames: [
+ "_",
+ "_",
+ "_",
+ "-",
+ "`",
+ "`",
+ "'",
+ "\xB4",
+ "-",
+ "_",
+ "_",
+ "_"
+ ]
+ },
+ hamburger: {
+ interval: 100,
+ frames: [
+ "\u2631",
+ "\u2632",
+ "\u2634"
+ ]
+ },
+ growVertical: {
+ interval: 120,
+ frames: [
+ "\u2581",
+ "\u2583",
+ "\u2584",
+ "\u2585",
+ "\u2586",
+ "\u2587",
+ "\u2586",
+ "\u2585",
+ "\u2584",
+ "\u2583"
+ ]
+ },
+ growHorizontal: {
+ interval: 120,
+ frames: [
+ "\u258F",
+ "\u258E",
+ "\u258D",
+ "\u258C",
+ "\u258B",
+ "\u258A",
+ "\u2589",
+ "\u258A",
+ "\u258B",
+ "\u258C",
+ "\u258D",
+ "\u258E"
+ ]
+ },
+ balloon: {
+ interval: 140,
+ frames: [
+ " ",
+ ".",
+ "o",
+ "O",
+ "@",
+ "*",
+ " "
+ ]
+ },
+ balloon2: {
+ interval: 120,
+ frames: [
+ ".",
+ "o",
+ "O",
+ "\xB0",
+ "O",
+ "o",
+ "."
+ ]
+ },
+ noise: {
+ interval: 100,
+ frames: [
+ "\u2593",
+ "\u2592",
+ "\u2591"
+ ]
+ },
+ bounce: {
+ interval: 120,
+ frames: [
+ "\u2801",
+ "\u2802",
+ "\u2804",
+ "\u2802"
+ ]
+ },
+ boxBounce: {
+ interval: 120,
+ frames: [
+ "\u2596",
+ "\u2598",
+ "\u259D",
+ "\u2597"
+ ]
+ },
+ boxBounce2: {
+ interval: 100,
+ frames: [
+ "\u258C",
+ "\u2580",
+ "\u2590",
+ "\u2584"
+ ]
+ },
+ triangle: {
+ interval: 50,
+ frames: [
+ "\u25E2",
+ "\u25E3",
+ "\u25E4",
+ "\u25E5"
+ ]
+ },
+ arc: {
+ interval: 100,
+ frames: [
+ "\u25DC",
+ "\u25E0",
+ "\u25DD",
+ "\u25DE",
+ "\u25E1",
+ "\u25DF"
+ ]
+ },
+ circle: {
+ interval: 120,
+ frames: [
+ "\u25E1",
+ "\u2299",
+ "\u25E0"
+ ]
+ },
+ squareCorners: {
+ interval: 180,
+ frames: [
+ "\u25F0",
+ "\u25F3",
+ "\u25F2",
+ "\u25F1"
+ ]
+ },
+ circleQuarters: {
+ interval: 120,
+ frames: [
+ "\u25F4",
+ "\u25F7",
+ "\u25F6",
+ "\u25F5"
+ ]
+ },
+ circleHalves: {
+ interval: 50,
+ frames: [
+ "\u25D0",
+ "\u25D3",
+ "\u25D1",
+ "\u25D2"
+ ]
+ },
+ squish: {
+ interval: 100,
+ frames: [
+ "\u256B",
+ "\u256A"
+ ]
+ },
+ toggle: {
+ interval: 250,
+ frames: [
+ "\u22B6",
+ "\u22B7"
+ ]
+ },
+ toggle2: {
+ interval: 80,
+ frames: [
+ "\u25AB",
+ "\u25AA"
+ ]
+ },
+ toggle3: {
+ interval: 120,
+ frames: [
+ "\u25A1",
+ "\u25A0"
+ ]
+ },
+ toggle4: {
+ interval: 100,
+ frames: [
+ "\u25A0",
+ "\u25A1",
+ "\u25AA",
+ "\u25AB"
+ ]
+ },
+ toggle5: {
+ interval: 100,
+ frames: [
+ "\u25AE",
+ "\u25AF"
+ ]
+ },
+ toggle6: {
+ interval: 300,
+ frames: [
+ "\u101D",
+ "\u1040"
+ ]
+ },
+ toggle7: {
+ interval: 80,
+ frames: [
+ "\u29BE",
+ "\u29BF"
+ ]
+ },
+ toggle8: {
+ interval: 100,
+ frames: [
+ "\u25CD",
+ "\u25CC"
+ ]
+ },
+ toggle9: {
+ interval: 100,
+ frames: [
+ "\u25C9",
+ "\u25CE"
+ ]
+ },
+ toggle10: {
+ interval: 100,
+ frames: [
+ "\u3282",
+ "\u3280",
+ "\u3281"
+ ]
+ },
+ toggle11: {
+ interval: 50,
+ frames: [
+ "\u29C7",
+ "\u29C6"
+ ]
+ },
+ toggle12: {
+ interval: 120,
+ frames: [
+ "\u2617",
+ "\u2616"
+ ]
+ },
+ toggle13: {
+ interval: 80,
+ frames: [
+ "=",
+ "*",
+ "-"
+ ]
+ },
+ arrow: {
+ interval: 100,
+ frames: [
+ "\u2190",
+ "\u2196",
+ "\u2191",
+ "\u2197",
+ "\u2192",
+ "\u2198",
+ "\u2193",
+ "\u2199"
+ ]
+ },
+ arrow2: {
+ interval: 80,
+ frames: [
+ "\u2B06\uFE0F ",
+ "\u2197\uFE0F ",
+ "\u27A1\uFE0F ",
+ "\u2198\uFE0F ",
+ "\u2B07\uFE0F ",
+ "\u2199\uFE0F ",
+ "\u2B05\uFE0F ",
+ "\u2196\uFE0F "
+ ]
+ },
+ arrow3: {
+ interval: 120,
+ frames: [
+ "\u25B9\u25B9\u25B9\u25B9\u25B9",
+ "\u25B8\u25B9\u25B9\u25B9\u25B9",
+ "\u25B9\u25B8\u25B9\u25B9\u25B9",
+ "\u25B9\u25B9\u25B8\u25B9\u25B9",
+ "\u25B9\u25B9\u25B9\u25B8\u25B9",
+ "\u25B9\u25B9\u25B9\u25B9\u25B8"
+ ]
+ },
+ bouncingBar: {
+ interval: 80,
+ frames: [
+ "[ ]",
+ "[= ]",
+ "[== ]",
+ "[=== ]",
+ "[ ===]",
+ "[ ==]",
+ "[ =]",
+ "[ ]",
+ "[ =]",
+ "[ ==]",
+ "[ ===]",
+ "[====]",
+ "[=== ]",
+ "[== ]",
+ "[= ]"
+ ]
+ },
+ bouncingBall: {
+ interval: 80,
+ frames: [
+ "( \u25CF )",
+ "( \u25CF )",
+ "( \u25CF )",
+ "( \u25CF )",
+ "( \u25CF)",
+ "( \u25CF )",
+ "( \u25CF )",
+ "( \u25CF )",
+ "( \u25CF )",
+ "(\u25CF )"
+ ]
+ },
+ smiley: {
+ interval: 200,
+ frames: [
+ "\u{1F604} ",
+ "\u{1F61D} "
+ ]
+ },
+ monkey: {
+ interval: 300,
+ frames: [
+ "\u{1F648} ",
+ "\u{1F648} ",
+ "\u{1F649} ",
+ "\u{1F64A} "
+ ]
+ },
+ hearts: {
+ interval: 100,
+ frames: [
+ "\u{1F49B} ",
+ "\u{1F499} ",
+ "\u{1F49C} ",
+ "\u{1F49A} ",
+ "\u2764\uFE0F "
+ ]
+ },
+ clock: {
+ interval: 100,
+ frames: [
+ "\u{1F55B} ",
+ "\u{1F550} ",
+ "\u{1F551} ",
+ "\u{1F552} ",
+ "\u{1F553} ",
+ "\u{1F554} ",
+ "\u{1F555} ",
+ "\u{1F556} ",
+ "\u{1F557} ",
+ "\u{1F558} ",
+ "\u{1F559} ",
+ "\u{1F55A} "
+ ]
+ },
+ earth: {
+ interval: 180,
+ frames: [
+ "\u{1F30D} ",
+ "\u{1F30E} ",
+ "\u{1F30F} "
+ ]
+ },
+ material: {
+ interval: 17,
+ frames: [
+ "\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
+ "\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
+ "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
+ "\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
+ "\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
+ "\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
+ "\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
+ "\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2588",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581",
+ "\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581\u2581"
+ ]
+ },
+ moon: {
+ interval: 80,
+ frames: [
+ "\u{1F311} ",
+ "\u{1F312} ",
+ "\u{1F313} ",
+ "\u{1F314} ",
+ "\u{1F315} ",
+ "\u{1F316} ",
+ "\u{1F317} ",
+ "\u{1F318} "
+ ]
+ },
+ runner: {
+ interval: 140,
+ frames: [
+ "\u{1F6B6} ",
+ "\u{1F3C3} "
+ ]
+ },
+ pong: {
+ interval: 80,
+ frames: [
+ "\u2590\u2802 \u258C",
+ "\u2590\u2808 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2840 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2808 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2840 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2808 \u258C",
+ "\u2590 \u2802\u258C",
+ "\u2590 \u2820\u258C",
+ "\u2590 \u2840\u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2808 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2840 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2808 \u258C",
+ "\u2590 \u2802 \u258C",
+ "\u2590 \u2820 \u258C",
+ "\u2590 \u2840 \u258C",
+ "\u2590\u2820 \u258C"
+ ]
+ },
+ shark: {
+ interval: 120,
+ frames: [
+ "\u2590|\\____________\u258C",
+ "\u2590_|\\___________\u258C",
+ "\u2590__|\\__________\u258C",
+ "\u2590___|\\_________\u258C",
+ "\u2590____|\\________\u258C",
+ "\u2590_____|\\_______\u258C",
+ "\u2590______|\\______\u258C",
+ "\u2590_______|\\_____\u258C",
+ "\u2590________|\\____\u258C",
+ "\u2590_________|\\___\u258C",
+ "\u2590__________|\\__\u258C",
+ "\u2590___________|\\_\u258C",
+ "\u2590____________|\\\u258C",
+ "\u2590____________/|\u258C",
+ "\u2590___________/|_\u258C",
+ "\u2590__________/|__\u258C",
+ "\u2590_________/|___\u258C",
+ "\u2590________/|____\u258C",
+ "\u2590_______/|_____\u258C",
+ "\u2590______/|______\u258C",
+ "\u2590_____/|_______\u258C",
+ "\u2590____/|________\u258C",
+ "\u2590___/|_________\u258C",
+ "\u2590__/|__________\u258C",
+ "\u2590_/|___________\u258C",
+ "\u2590/|____________\u258C"
+ ]
+ },
+ dqpb: {
+ interval: 100,
+ frames: [
+ "d",
+ "q",
+ "p",
+ "b"
+ ]
+ },
+ weather: {
+ interval: 100,
+ frames: [
+ "\u2600\uFE0F ",
+ "\u2600\uFE0F ",
+ "\u2600\uFE0F ",
+ "\u{1F324} ",
+ "\u26C5\uFE0F ",
+ "\u{1F325} ",
+ "\u2601\uFE0F ",
+ "\u{1F327} ",
+ "\u{1F328} ",
+ "\u{1F327} ",
+ "\u{1F328} ",
+ "\u{1F327} ",
+ "\u{1F328} ",
+ "\u26C8 ",
+ "\u{1F328} ",
+ "\u{1F327} ",
+ "\u{1F328} ",
+ "\u2601\uFE0F ",
+ "\u{1F325} ",
+ "\u26C5\uFE0F ",
+ "\u{1F324} ",
+ "\u2600\uFE0F ",
+ "\u2600\uFE0F "
+ ]
+ },
+ christmas: {
+ interval: 400,
+ frames: [
+ "\u{1F332}",
+ "\u{1F384}"
+ ]
+ },
+ grenade: {
+ interval: 80,
+ frames: [
+ "\u060C ",
+ "\u2032 ",
+ " \xB4 ",
+ " \u203E ",
+ " \u2E0C",
+ " \u2E0A",
+ " |",
+ " \u204E",
+ " \u2055",
+ " \u0DF4 ",
+ " \u2053",
+ " ",
+ " ",
+ " "
+ ]
+ },
+ point: {
+ interval: 125,
+ frames: [
+ "\u2219\u2219\u2219",
+ "\u25CF\u2219\u2219",
+ "\u2219\u25CF\u2219",
+ "\u2219\u2219\u25CF",
+ "\u2219\u2219\u2219"
+ ]
+ },
+ layer: {
+ interval: 150,
+ frames: [
+ "-",
+ "=",
+ "\u2261"
+ ]
+ },
+ betaWave: {
+ interval: 80,
+ frames: [
+ "\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2",
+ "\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2\u03B2",
+ "\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2\u03B2",
+ "\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2\u03B2",
+ "\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2\u03B2",
+ "\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1\u03B2",
+ "\u03B2\u03B2\u03B2\u03B2\u03B2\u03B2\u03C1"
+ ]
+ },
+ fingerDance: {
+ interval: 160,
+ frames: [
+ "\u{1F918} ",
+ "\u{1F91F} ",
+ "\u{1F596} ",
+ "\u270B ",
+ "\u{1F91A} ",
+ "\u{1F446} "
+ ]
+ },
+ fistBump: {
+ interval: 80,
+ frames: [
+ "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
+ "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
+ "\u{1F91C}\u3000\u3000\u3000\u3000\u{1F91B} ",
+ "\u3000\u{1F91C}\u3000\u3000\u{1F91B}\u3000 ",
+ "\u3000\u3000\u{1F91C}\u{1F91B}\u3000\u3000 ",
+ "\u3000\u{1F91C}\u2728\u{1F91B}\u3000\u3000 ",
+ "\u{1F91C}\u3000\u2728\u3000\u{1F91B}\u3000 "
+ ]
+ },
+ soccerHeader: {
+ interval: 80,
+ frames: [
+ " \u{1F9D1}\u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F\u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} ",
+ "\u{1F9D1} \u26BD\uFE0F \u{1F9D1} "
+ ]
+ },
+ mindblown: {
+ interval: 160,
+ frames: [
+ "\u{1F610} ",
+ "\u{1F610} ",
+ "\u{1F62E} ",
+ "\u{1F62E} ",
+ "\u{1F626} ",
+ "\u{1F626} ",
+ "\u{1F627} ",
+ "\u{1F627} ",
+ "\u{1F92F} ",
+ "\u{1F4A5} ",
+ "\u2728 ",
+ "\u3000 ",
+ "\u3000 ",
+ "\u3000 "
+ ]
+ },
+ speaker: {
+ interval: 160,
+ frames: [
+ "\u{1F508} ",
+ "\u{1F509} ",
+ "\u{1F50A} ",
+ "\u{1F509} "
+ ]
+ },
+ orangePulse: {
+ interval: 100,
+ frames: [
+ "\u{1F538} ",
+ "\u{1F536} ",
+ "\u{1F7E0} ",
+ "\u{1F7E0} ",
+ "\u{1F536} "
+ ]
+ },
+ bluePulse: {
+ interval: 100,
+ frames: [
+ "\u{1F539} ",
+ "\u{1F537} ",
+ "\u{1F535} ",
+ "\u{1F535} ",
+ "\u{1F537} "
+ ]
+ },
+ orangeBluePulse: {
+ interval: 100,
+ frames: [
+ "\u{1F538} ",
+ "\u{1F536} ",
+ "\u{1F7E0} ",
+ "\u{1F7E0} ",
+ "\u{1F536} ",
+ "\u{1F539} ",
+ "\u{1F537} ",
+ "\u{1F535} ",
+ "\u{1F535} ",
+ "\u{1F537} "
+ ]
+ },
+ timeTravel: {
+ interval: 100,
+ frames: [
+ "\u{1F55B} ",
+ "\u{1F55A} ",
+ "\u{1F559} ",
+ "\u{1F558} ",
+ "\u{1F557} ",
+ "\u{1F556} ",
+ "\u{1F555} ",
+ "\u{1F554} ",
+ "\u{1F553} ",
+ "\u{1F552} ",
+ "\u{1F551} ",
+ "\u{1F550} "
+ ]
+ },
+ aesthetic: {
+ interval: 80,
+ frames: [
+ "\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1",
+ "\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1",
+ "\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1\u25B1",
+ "\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1\u25B1",
+ "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1\u25B1",
+ "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B1",
+ "\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0\u25B0",
+ "\u25B0\u25B1\u25B1\u25B1\u25B1\u25B1\u25B1"
+ ]
+ }
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/cli-spinners@2.6.1/node_modules/cli-spinners/index.js
+var require_cli_spinners = __commonJS({
+ "../../node_modules/.pnpm/cli-spinners@2.6.1/node_modules/cli-spinners/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var spinners = Object.assign({}, require_spinners());
+ var spinnersList = Object.keys(spinners);
+ Object.defineProperty(spinners, "random", {
+ get() {
+ const randomIndex = Math.floor(Math.random() * spinnersList.length);
+ const spinnerName = spinnersList[randomIndex];
+ return spinners[spinnerName];
+ }
+ });
+ module2.exports = spinners;
+ }
+});
+
+// ../../node_modules/.pnpm/ink-spinner@4.0.3_ink@3.2.0_react@17.0.2/node_modules/ink-spinner/build/index.js
+var require_build4 = __commonJS({
+ "../../node_modules/.pnpm/ink-spinner@4.0.3_ink@3.2.0_react@17.0.2/node_modules/ink-spinner/build/index.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ Object.defineProperty(exports2, "__esModule", { value: true });
+ var React18 = require_react();
+ var react_1 = require_react();
+ var ink_1 = require_build2();
+ var spinners = require_cli_spinners();
+ var Spinner2 = /* @__PURE__ */ __name(({ type = "dots" }) => {
+ const [frame, setFrame] = react_1.useState(0);
+ const spinner = spinners[type];
+ react_1.useEffect(() => {
+ const timer = setInterval(() => {
+ setFrame((previousFrame) => {
+ const isLastFrame = previousFrame === spinner.frames.length - 1;
+ return isLastFrame ? 0 : previousFrame + 1;
+ });
+ }, spinner.interval);
+ return () => {
+ clearInterval(timer);
+ };
+ }, [spinner]);
+ return React18.createElement(ink_1.Text, null, spinner.frames[frame]);
+ }, "Spinner");
+ exports2.default = Spinner2;
+ }
+});
+
+// ../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js
+var require_eventemitter3 = __commonJS({
+ "../../node_modules/.pnpm/eventemitter3@4.0.7/node_modules/eventemitter3/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var has = Object.prototype.hasOwnProperty;
+ var prefix = "~";
+ function Events() {
+ }
+ __name(Events, "Events");
+ if (Object.create) {
+ Events.prototype = /* @__PURE__ */ Object.create(null);
+ if (!new Events().__proto__)
+ prefix = false;
+ }
+ function EE(fn2, context2, once) {
+ this.fn = fn2;
+ this.context = context2;
+ this.once = once || false;
+ }
+ __name(EE, "EE");
+ function addListener(emitter, event, fn2, context2, once) {
+ if (typeof fn2 !== "function") {
+ throw new TypeError("The listener must be a function");
+ }
+ var listener = new EE(fn2, context2 || emitter, once), evt = prefix ? prefix + event : event;
+ if (!emitter._events[evt])
+ emitter._events[evt] = listener, emitter._eventsCount++;
+ else if (!emitter._events[evt].fn)
+ emitter._events[evt].push(listener);
+ else
+ emitter._events[evt] = [emitter._events[evt], listener];
+ return emitter;
+ }
+ __name(addListener, "addListener");
+ function clearEvent(emitter, evt) {
+ if (--emitter._eventsCount === 0)
+ emitter._events = new Events();
+ else
+ delete emitter._events[evt];
+ }
+ __name(clearEvent, "clearEvent");
+ function EventEmitter3() {
+ this._events = new Events();
+ this._eventsCount = 0;
+ }
+ __name(EventEmitter3, "EventEmitter");
+ EventEmitter3.prototype.eventNames = /* @__PURE__ */ __name(function eventNames() {
+ var names = [], events, name;
+ if (this._eventsCount === 0)
+ return names;
+ for (name in events = this._events) {
+ if (has.call(events, name))
+ names.push(prefix ? name.slice(1) : name);
+ }
+ if (Object.getOwnPropertySymbols) {
+ return names.concat(Object.getOwnPropertySymbols(events));
+ }
+ return names;
+ }, "eventNames");
+ EventEmitter3.prototype.listeners = /* @__PURE__ */ __name(function listeners(event) {
+ var evt = prefix ? prefix + event : event, handlers = this._events[evt];
+ if (!handlers)
+ return [];
+ if (handlers.fn)
+ return [handlers.fn];
+ for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) {
+ ee[i] = handlers[i].fn;
+ }
+ return ee;
+ }, "listeners");
+ EventEmitter3.prototype.listenerCount = /* @__PURE__ */ __name(function listenerCount(event) {
+ var evt = prefix ? prefix + event : event, listeners = this._events[evt];
+ if (!listeners)
+ return 0;
+ if (listeners.fn)
+ return 1;
+ return listeners.length;
+ }, "listenerCount");
+ EventEmitter3.prototype.emit = /* @__PURE__ */ __name(function emit(event, a1, a2, a3, a4, a5) {
+ var evt = prefix ? prefix + event : event;
+ if (!this._events[evt])
+ return false;
+ var listeners = this._events[evt], len = arguments.length, args, i;
+ if (listeners.fn) {
+ if (listeners.once)
+ this.removeListener(event, listeners.fn, void 0, true);
+ switch (len) {
+ case 1:
+ return listeners.fn.call(listeners.context), true;
+ case 2:
+ return listeners.fn.call(listeners.context, a1), true;
+ case 3:
+ return listeners.fn.call(listeners.context, a1, a2), true;
+ case 4:
+ return listeners.fn.call(listeners.context, a1, a2, a3), true;
+ case 5:
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4), true;
+ case 6:
+ return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true;
+ }
+ for (i = 1, args = new Array(len - 1); i < len; i++) {
+ args[i - 1] = arguments[i];
+ }
+ listeners.fn.apply(listeners.context, args);
+ } else {
+ var length = listeners.length, j;
+ for (i = 0; i < length; i++) {
+ if (listeners[i].once)
+ this.removeListener(event, listeners[i].fn, void 0, true);
+ switch (len) {
+ case 1:
+ listeners[i].fn.call(listeners[i].context);
+ break;
+ case 2:
+ listeners[i].fn.call(listeners[i].context, a1);
+ break;
+ case 3:
+ listeners[i].fn.call(listeners[i].context, a1, a2);
+ break;
+ case 4:
+ listeners[i].fn.call(listeners[i].context, a1, a2, a3);
+ break;
+ default:
+ if (!args)
+ for (j = 1, args = new Array(len - 1); j < len; j++) {
+ args[j - 1] = arguments[j];
+ }
+ listeners[i].fn.apply(listeners[i].context, args);
+ }
+ }
+ }
+ return true;
+ }, "emit");
+ EventEmitter3.prototype.on = /* @__PURE__ */ __name(function on(event, fn2, context2) {
+ return addListener(this, event, fn2, context2, false);
+ }, "on");
+ EventEmitter3.prototype.once = /* @__PURE__ */ __name(function once(event, fn2, context2) {
+ return addListener(this, event, fn2, context2, true);
+ }, "once");
+ EventEmitter3.prototype.removeListener = /* @__PURE__ */ __name(function removeListener(event, fn2, context2, once) {
+ var evt = prefix ? prefix + event : event;
+ if (!this._events[evt])
+ return this;
+ if (!fn2) {
+ clearEvent(this, evt);
+ return this;
+ }
+ var listeners = this._events[evt];
+ if (listeners.fn) {
+ if (listeners.fn === fn2 && (!once || listeners.once) && (!context2 || listeners.context === context2)) {
+ clearEvent(this, evt);
+ }
+ } else {
+ for (var i = 0, events = [], length = listeners.length; i < length; i++) {
+ if (listeners[i].fn !== fn2 || once && !listeners[i].once || context2 && listeners[i].context !== context2) {
+ events.push(listeners[i]);
+ }
+ }
+ if (events.length)
+ this._events[evt] = events.length === 1 ? events[0] : events;
+ else
+ clearEvent(this, evt);
+ }
+ return this;
+ }, "removeListener");
+ EventEmitter3.prototype.removeAllListeners = /* @__PURE__ */ __name(function removeAllListeners(event) {
+ var evt;
+ if (event) {
+ evt = prefix ? prefix + event : event;
+ if (this._events[evt])
+ clearEvent(this, evt);
+ } else {
+ this._events = new Events();
+ this._eventsCount = 0;
+ }
+ return this;
+ }, "removeAllListeners");
+ EventEmitter3.prototype.off = EventEmitter3.prototype.removeListener;
+ EventEmitter3.prototype.addListener = EventEmitter3.prototype.on;
+ EventEmitter3.prefixed = prefix;
+ EventEmitter3.EventEmitter = EventEmitter3;
+ if ("undefined" !== typeof module2) {
+ module2.exports = EventEmitter3;
+ }
+ }
+});
+
+// ../../node_modules/.pnpm/minimatch@5.1.0/node_modules/minimatch/lib/path.js
+var require_path = __commonJS({
+ "../../node_modules/.pnpm/minimatch@5.1.0/node_modules/minimatch/lib/path.js"(exports2, module2) {
+ init_import_meta_url();
+ var isWindows2 = typeof process === "object" && process && process.platform === "win32";
+ module2.exports = isWindows2 ? { sep: "\\" } : { sep: "/" };
+ }
+});
+
+// ../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js
+var require_brace_expansion2 = __commonJS({
+ "../../node_modules/.pnpm/brace-expansion@2.0.1/node_modules/brace-expansion/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var balanced = require_balanced_match();
+ module2.exports = expandTop;
+ var escSlash = "\0SLASH" + Math.random() + "\0";
+ var escOpen = "\0OPEN" + Math.random() + "\0";
+ var escClose = "\0CLOSE" + Math.random() + "\0";
+ var escComma = "\0COMMA" + Math.random() + "\0";
+ var escPeriod = "\0PERIOD" + Math.random() + "\0";
+ function numeric(str) {
+ return parseInt(str, 10) == str ? parseInt(str, 10) : str.charCodeAt(0);
+ }
+ __name(numeric, "numeric");
+ function escapeBraces(str) {
+ return str.split("\\\\").join(escSlash).split("\\{").join(escOpen).split("\\}").join(escClose).split("\\,").join(escComma).split("\\.").join(escPeriod);
+ }
+ __name(escapeBraces, "escapeBraces");
+ function unescapeBraces(str) {
+ return str.split(escSlash).join("\\").split(escOpen).join("{").split(escClose).join("}").split(escComma).join(",").split(escPeriod).join(".");
+ }
+ __name(unescapeBraces, "unescapeBraces");
+ function parseCommaParts(str) {
+ if (!str)
+ return [""];
+ var parts = [];
+ var m = balanced("{", "}", str);
+ if (!m)
+ return str.split(",");
+ var pre = m.pre;
+ var body = m.body;
+ var post = m.post;
+ var p = pre.split(",");
+ p[p.length - 1] += "{" + body + "}";
+ var postParts = parseCommaParts(post);
+ if (post.length) {
+ p[p.length - 1] += postParts.shift();
+ p.push.apply(p, postParts);
+ }
+ parts.push.apply(parts, p);
+ return parts;
+ }
+ __name(parseCommaParts, "parseCommaParts");
+ function expandTop(str) {
+ if (!str)
+ return [];
+ if (str.substr(0, 2) === "{}") {
+ str = "\\{\\}" + str.substr(2);
+ }
+ return expand(escapeBraces(str), true).map(unescapeBraces);
+ }
+ __name(expandTop, "expandTop");
+ function embrace(str) {
+ return "{" + str + "}";
+ }
+ __name(embrace, "embrace");
+ function isPadded(el) {
+ return /^-?0\d/.test(el);
+ }
+ __name(isPadded, "isPadded");
+ function lte(i, y) {
+ return i <= y;
+ }
+ __name(lte, "lte");
+ function gte(i, y) {
+ return i >= y;
+ }
+ __name(gte, "gte");
+ function expand(str, isTop) {
+ var expansions = [];
+ var m = balanced("{", "}", str);
+ if (!m)
+ return [str];
+ var pre = m.pre;
+ var post = m.post.length ? expand(m.post, false) : [""];
+ if (/\$$/.test(m.pre)) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + "{" + m.body + "}" + post[k];
+ expansions.push(expansion);
+ }
+ } else {
+ var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
+ var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
+ var isSequence = isNumericSequence || isAlphaSequence;
+ var isOptions = m.body.indexOf(",") >= 0;
+ if (!isSequence && !isOptions) {
+ if (m.post.match(/,.*\}/)) {
+ str = m.pre + "{" + m.body + escClose + m.post;
+ return expand(str);
+ }
+ return [str];
+ }
+ var n;
+ if (isSequence) {
+ n = m.body.split(/\.\./);
+ } else {
+ n = parseCommaParts(m.body);
+ if (n.length === 1) {
+ n = expand(n[0], false).map(embrace);
+ if (n.length === 1) {
+ return post.map(function(p) {
+ return m.pre + n[0] + p;
+ });
+ }
+ }
+ }
+ var N;
+ if (isSequence) {
+ var x = numeric(n[0]);
+ var y = numeric(n[1]);
+ var width = Math.max(n[0].length, n[1].length);
+ var incr = n.length == 3 ? Math.abs(numeric(n[2])) : 1;
+ var test = lte;
+ var reverse = y < x;
+ if (reverse) {
+ incr *= -1;
+ test = gte;
+ }
+ var pad2 = n.some(isPadded);
+ N = [];
+ for (var i = x; test(i, y); i += incr) {
+ var c;
+ if (isAlphaSequence) {
+ c = String.fromCharCode(i);
+ if (c === "\\")
+ c = "";
+ } else {
+ c = String(i);
+ if (pad2) {
+ var need = width - c.length;
+ if (need > 0) {
+ var z = new Array(need + 1).join("0");
+ if (i < 0)
+ c = "-" + z + c.slice(1);
+ else
+ c = z + c;
+ }
+ }
+ }
+ N.push(c);
+ }
+ } else {
+ N = [];
+ for (var j = 0; j < n.length; j++) {
+ N.push.apply(N, expand(n[j], false));
+ }
+ }
+ for (var j = 0; j < N.length; j++) {
+ for (var k = 0; k < post.length; k++) {
+ var expansion = pre + N[j] + post[k];
+ if (!isTop || isSequence || expansion)
+ expansions.push(expansion);
+ }
+ }
+ }
+ return expansions;
+ }
+ __name(expand, "expand");
+ }
+});
+
+// ../../node_modules/.pnpm/minimatch@5.1.0/node_modules/minimatch/minimatch.js
+var require_minimatch2 = __commonJS({
+ "../../node_modules/.pnpm/minimatch@5.1.0/node_modules/minimatch/minimatch.js"(exports2, module2) {
+ init_import_meta_url();
+ var minimatch = module2.exports = (p, pattern, options14 = {}) => {
+ assertValidPattern(pattern);
+ if (!options14.nocomment && pattern.charAt(0) === "#") {
+ return false;
+ }
+ return new Minimatch2(pattern, options14).match(p);
+ };
+ module2.exports = minimatch;
+ var path45 = require_path();
+ minimatch.sep = path45.sep;
+ var GLOBSTAR = Symbol("globstar **");
+ minimatch.GLOBSTAR = GLOBSTAR;
+ var expand = require_brace_expansion2();
+ var plTypes = {
+ "!": { open: "(?:(?!(?:", close: "))[^/]*?)" },
+ "?": { open: "(?:", close: ")?" },
+ "+": { open: "(?:", close: ")+" },
+ "*": { open: "(?:", close: ")*" },
+ "@": { open: "(?:", close: ")" }
+ };
+ var qmark = "[^/]";
+ var star = qmark + "*?";
+ var twoStarDot = "(?:(?!(?:\\/|^)(?:\\.{1,2})($|\\/)).)*?";
+ var twoStarNoDot = "(?:(?!(?:\\/|^)\\.).)*?";
+ var charSet = /* @__PURE__ */ __name((s) => s.split("").reduce((set, c) => {
+ set[c] = true;
+ return set;
+ }, {}), "charSet");
+ var reSpecials = charSet("().*{}+?[]^$\\!");
+ var addPatternStartSet = charSet("[.(");
+ var slashSplit = /\/+/;
+ minimatch.filter = (pattern, options14 = {}) => (p, i, list) => minimatch(p, pattern, options14);
+ var ext = /* @__PURE__ */ __name((a, b = {}) => {
+ const t2 = {};
+ Object.keys(a).forEach((k) => t2[k] = a[k]);
+ Object.keys(b).forEach((k) => t2[k] = b[k]);
+ return t2;
+ }, "ext");
+ minimatch.defaults = (def) => {
+ if (!def || typeof def !== "object" || !Object.keys(def).length) {
+ return minimatch;
+ }
+ const orig = minimatch;
+ const m = /* @__PURE__ */ __name((p, pattern, options14) => orig(p, pattern, ext(def, options14)), "m");
+ m.Minimatch = /* @__PURE__ */ __name(class Minimatch extends orig.Minimatch {
+ constructor(pattern, options14) {
+ super(pattern, ext(def, options14));
+ }
+ }, "Minimatch");
+ m.Minimatch.defaults = (options14) => orig.defaults(ext(def, options14)).Minimatch;
+ m.filter = (pattern, options14) => orig.filter(pattern, ext(def, options14));
+ m.defaults = (options14) => orig.defaults(ext(def, options14));
+ m.makeRe = (pattern, options14) => orig.makeRe(pattern, ext(def, options14));
+ m.braceExpand = (pattern, options14) => orig.braceExpand(pattern, ext(def, options14));
+ m.match = (list, pattern, options14) => orig.match(list, pattern, ext(def, options14));
+ return m;
+ };
+ minimatch.braceExpand = (pattern, options14) => braceExpand(pattern, options14);
+ var braceExpand = /* @__PURE__ */ __name((pattern, options14 = {}) => {
+ assertValidPattern(pattern);
+ if (options14.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) {
+ return [pattern];
+ }
+ return expand(pattern);
+ }, "braceExpand");
+ var MAX_PATTERN_LENGTH = 1024 * 64;
+ var assertValidPattern = /* @__PURE__ */ __name((pattern) => {
+ if (typeof pattern !== "string") {
+ throw new TypeError("invalid pattern");
+ }
+ if (pattern.length > MAX_PATTERN_LENGTH) {
+ throw new TypeError("pattern is too long");
+ }
+ }, "assertValidPattern");
+ var SUBPARSE = Symbol("subparse");
+ minimatch.makeRe = (pattern, options14) => new Minimatch2(pattern, options14 || {}).makeRe();
+ minimatch.match = (list, pattern, options14 = {}) => {
+ const mm = new Minimatch2(pattern, options14);
+ list = list.filter((f) => mm.match(f));
+ if (mm.options.nonull && !list.length) {
+ list.push(pattern);
+ }
+ return list;
+ };
+ var globUnescape = /* @__PURE__ */ __name((s) => s.replace(/\\(.)/g, "$1"), "globUnescape");
+ var regExpEscape = /* @__PURE__ */ __name((s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "regExpEscape");
+ var Minimatch2 = class {
+ constructor(pattern, options14) {
+ assertValidPattern(pattern);
+ if (!options14)
+ options14 = {};
+ this.options = options14;
+ this.set = [];
+ this.pattern = pattern;
+ this.windowsPathsNoEscape = !!options14.windowsPathsNoEscape || options14.allowWindowsEscape === false;
+ if (this.windowsPathsNoEscape) {
+ this.pattern = this.pattern.replace(/\\/g, "/");
+ }
+ this.regexp = null;
+ this.negate = false;
+ this.comment = false;
+ this.empty = false;
+ this.partial = !!options14.partial;
+ this.make();
+ }
+ debug() {
+ }
+ make() {
+ const pattern = this.pattern;
+ const options14 = this.options;
+ if (!options14.nocomment && pattern.charAt(0) === "#") {
+ this.comment = true;
+ return;
+ }
+ if (!pattern) {
+ this.empty = true;
+ return;
+ }
+ this.parseNegate();
+ let set = this.globSet = this.braceExpand();
+ if (options14.debug)
+ this.debug = (...args) => console.error(...args);
+ this.debug(this.pattern, set);
+ set = this.globParts = set.map((s) => s.split(slashSplit));
+ this.debug(this.pattern, set);
+ set = set.map((s, si2, set2) => s.map(this.parse, this));
+ this.debug(this.pattern, set);
+ set = set.filter((s) => s.indexOf(false) === -1);
+ this.debug(this.pattern, set);
+ this.set = set;
+ }
+ parseNegate() {
+ if (this.options.nonegate)
+ return;
+ const pattern = this.pattern;
+ let negate = false;
+ let negateOffset = 0;
+ for (let i = 0; i < pattern.length && pattern.charAt(i) === "!"; i++) {
+ negate = !negate;
+ negateOffset++;
+ }
+ if (negateOffset)
+ this.pattern = pattern.substr(negateOffset);
+ this.negate = negate;
+ }
+ // set partial to true to test if, for example,
+ // "/a/b" matches the start of "/*/b/*/d"
+ // Partial means, if you run out of file before you run
+ // out of pattern, then that's fine, as long as all
+ // the parts match.
+ matchOne(file, pattern, partial) {
+ var options14 = this.options;
+ this.debug(
+ "matchOne",
+ { "this": this, file, pattern }
+ );
+ this.debug("matchOne", file.length, pattern.length);
+ for (var fi = 0, pi = 0, fl = file.length, pl2 = pattern.length; fi < fl && pi < pl2; fi++, pi++) {
+ this.debug("matchOne loop");
+ var p = pattern[pi];
+ var f = file[fi];
+ this.debug(pattern, p, f);
+ if (p === false)
+ return false;
+ if (p === GLOBSTAR) {
+ this.debug("GLOBSTAR", [pattern, p, f]);
+ var fr2 = fi;
+ var pr = pi + 1;
+ if (pr === pl2) {
+ this.debug("** at the end");
+ for (; fi < fl; fi++) {
+ if (file[fi] === "." || file[fi] === ".." || !options14.dot && file[fi].charAt(0) === ".")
+ return false;
+ }
+ return true;
+ }
+ while (fr2 < fl) {
+ var swallowee = file[fr2];
+ this.debug("\nglobstar while", file, fr2, pattern, pr, swallowee);
+ if (this.matchOne(file.slice(fr2), pattern.slice(pr), partial)) {
+ this.debug("globstar found match!", fr2, fl, swallowee);
+ return true;
+ } else {
+ if (swallowee === "." || swallowee === ".." || !options14.dot && swallowee.charAt(0) === ".") {
+ this.debug("dot detected!", file, fr2, pattern, pr);
+ break;
+ }
+ this.debug("globstar swallow a segment, and continue");
+ fr2++;
+ }
+ }
+ if (partial) {
+ this.debug("\n>>> no match, partial?", file, fr2, pattern, pr);
+ if (fr2 === fl)
+ return true;
+ }
+ return false;
+ }
+ var hit;
+ if (typeof p === "string") {
+ hit = f === p;
+ this.debug("string match", p, f, hit);
+ } else {
+ hit = f.match(p);
+ this.debug("pattern match", p, f, hit);
+ }
+ if (!hit)
+ return false;
+ }
+ if (fi === fl && pi === pl2) {
+ return true;
+ } else if (fi === fl) {
+ return partial;
+ } else if (pi === pl2) {
+ return fi === fl - 1 && file[fi] === "";
+ }
+ throw new Error("wtf?");
+ }
+ braceExpand() {
+ return braceExpand(this.pattern, this.options);
+ }
+ parse(pattern, isSub) {
+ assertValidPattern(pattern);
+ const options14 = this.options;
+ if (pattern === "**") {
+ if (!options14.noglobstar)
+ return GLOBSTAR;
+ else
+ pattern = "*";
+ }
+ if (pattern === "")
+ return "";
+ let re = "";
+ let hasMagic = !!options14.nocase;
+ let escaping = false;
+ const patternListStack = [];
+ const negativeLists = [];
+ let stateChar;
+ let inClass = false;
+ let reClassStart = -1;
+ let classStart = -1;
+ let cs2;
+ let pl2;
+ let sp;
+ const patternStart = pattern.charAt(0) === "." ? "" : options14.dot ? "(?!(?:^|\\/)\\.{1,2}(?:$|\\/))" : "(?!\\.)";
+ const clearStateChar = /* @__PURE__ */ __name(() => {
+ if (stateChar) {
+ switch (stateChar) {
+ case "*":
+ re += star;
+ hasMagic = true;
+ break;
+ case "?":
+ re += qmark;
+ hasMagic = true;
+ break;
+ default:
+ re += "\\" + stateChar;
+ break;
+ }
+ this.debug("clearStateChar %j %j", stateChar, re);
+ stateChar = false;
+ }
+ }, "clearStateChar");
+ for (let i = 0, c; i < pattern.length && (c = pattern.charAt(i)); i++) {
+ this.debug("%s %s %s %j", pattern, i, re, c);
+ if (escaping) {
+ if (c === "/") {
+ return false;
+ }
+ if (reSpecials[c]) {
+ re += "\\";
+ }
+ re += c;
+ escaping = false;
+ continue;
+ }
+ switch (c) {
+ case "/": {
+ return false;
+ }
+ case "\\":
+ clearStateChar();
+ escaping = true;
+ continue;
+ case "?":
+ case "*":
+ case "+":
+ case "@":
+ case "!":
+ this.debug("%s %s %s %j <-- stateChar", pattern, i, re, c);
+ if (inClass) {
+ this.debug(" in class");
+ if (c === "!" && i === classStart + 1)
+ c = "^";
+ re += c;
+ continue;
+ }
+ this.debug("call clearStateChar %j", stateChar);
+ clearStateChar();
+ stateChar = c;
+ if (options14.noext)
+ clearStateChar();
+ continue;
+ case "(":
+ if (inClass) {
+ re += "(";
+ continue;
+ }
+ if (!stateChar) {
+ re += "\\(";
+ continue;
+ }
+ patternListStack.push({
+ type: stateChar,
+ start: i - 1,
+ reStart: re.length,
+ open: plTypes[stateChar].open,
+ close: plTypes[stateChar].close
+ });
+ re += stateChar === "!" ? "(?:(?!(?:" : "(?:";
+ this.debug("plType %j %j", stateChar, re);
+ stateChar = false;
+ continue;
+ case ")":
+ if (inClass || !patternListStack.length) {
+ re += "\\)";
+ continue;
+ }
+ clearStateChar();
+ hasMagic = true;
+ pl2 = patternListStack.pop();
+ re += pl2.close;
+ if (pl2.type === "!") {
+ negativeLists.push(pl2);
+ }
+ pl2.reEnd = re.length;
+ continue;
+ case "|":
+ if (inClass || !patternListStack.length) {
+ re += "\\|";
+ continue;
+ }
+ clearStateChar();
+ re += "|";
+ continue;
+ case "[":
+ clearStateChar();
+ if (inClass) {
+ re += "\\" + c;
+ continue;
+ }
+ inClass = true;
+ classStart = i;
+ reClassStart = re.length;
+ re += c;
+ continue;
+ case "]":
+ if (i === classStart + 1 || !inClass) {
+ re += "\\" + c;
+ continue;
+ }
+ cs2 = pattern.substring(classStart + 1, i);
+ try {
+ RegExp("[" + cs2 + "]");
+ } catch (er) {
+ sp = this.parse(cs2, SUBPARSE);
+ re = re.substr(0, reClassStart) + "\\[" + sp[0] + "\\]";
+ hasMagic = hasMagic || sp[1];
+ inClass = false;
+ continue;
+ }
+ hasMagic = true;
+ inClass = false;
+ re += c;
+ continue;
+ default:
+ clearStateChar();
+ if (reSpecials[c] && !(c === "^" && inClass)) {
+ re += "\\";
+ }
+ re += c;
+ break;
+ }
+ }
+ if (inClass) {
+ cs2 = pattern.substr(classStart + 1);
+ sp = this.parse(cs2, SUBPARSE);
+ re = re.substr(0, reClassStart) + "\\[" + sp[0];
+ hasMagic = hasMagic || sp[1];
+ }
+ for (pl2 = patternListStack.pop(); pl2; pl2 = patternListStack.pop()) {
+ let tail;
+ tail = re.slice(pl2.reStart + pl2.open.length);
+ this.debug("setting tail", re, pl2);
+ tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_2, $1, $2) => {
+ if (!$2) {
+ $2 = "\\";
+ }
+ return $1 + $1 + $2 + "|";
+ });
+ this.debug("tail=%j\n %s", tail, tail, pl2, re);
+ const t2 = pl2.type === "*" ? star : pl2.type === "?" ? qmark : "\\" + pl2.type;
+ hasMagic = true;
+ re = re.slice(0, pl2.reStart) + t2 + "\\(" + tail;
+ }
+ clearStateChar();
+ if (escaping) {
+ re += "\\\\";
+ }
+ const addPatternStart = addPatternStartSet[re.charAt(0)];
+ for (let n = negativeLists.length - 1; n > -1; n--) {
+ const nl = negativeLists[n];
+ const nlBefore = re.slice(0, nl.reStart);
+ const nlFirst = re.slice(nl.reStart, nl.reEnd - 8);
+ let nlAfter = re.slice(nl.reEnd);
+ const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter;
+ const openParensBefore = nlBefore.split("(").length - 1;
+ let cleanAfter = nlAfter;
+ for (let i = 0; i < openParensBefore; i++) {
+ cleanAfter = cleanAfter.replace(/\)[+*?]?/, "");
+ }
+ nlAfter = cleanAfter;
+ const dollar = nlAfter === "" && isSub !== SUBPARSE ? "$" : "";
+ re = nlBefore + nlFirst + nlAfter + dollar + nlLast;
+ }
+ if (re !== "" && hasMagic) {
+ re = "(?=.)" + re;
+ }
+ if (addPatternStart) {
+ re = patternStart + re;
+ }
+ if (isSub === SUBPARSE) {
+ return [re, hasMagic];
+ }
+ if (!hasMagic) {
+ return globUnescape(pattern);
+ }
+ const flags = options14.nocase ? "i" : "";
+ try {
+ return Object.assign(new RegExp("^" + re + "$", flags), {
+ _glob: pattern,
+ _src: re
+ });
+ } catch (er) {
+ return new RegExp("$.");
+ }
+ }
+ makeRe() {
+ if (this.regexp || this.regexp === false)
+ return this.regexp;
+ const set = this.set;
+ if (!set.length) {
+ this.regexp = false;
+ return this.regexp;
+ }
+ const options14 = this.options;
+ const twoStar = options14.noglobstar ? star : options14.dot ? twoStarDot : twoStarNoDot;
+ const flags = options14.nocase ? "i" : "";
+ let re = set.map((pattern) => {
+ pattern = pattern.map(
+ (p) => typeof p === "string" ? regExpEscape(p) : p === GLOBSTAR ? GLOBSTAR : p._src
+ ).reduce((set2, p) => {
+ if (!(set2[set2.length - 1] === GLOBSTAR && p === GLOBSTAR)) {
+ set2.push(p);
+ }
+ return set2;
+ }, []);
+ pattern.forEach((p, i) => {
+ if (p !== GLOBSTAR || pattern[i - 1] === GLOBSTAR) {
+ return;
+ }
+ if (i === 0) {
+ if (pattern.length > 1) {
+ pattern[i + 1] = "(?:\\/|" + twoStar + "\\/)?" + pattern[i + 1];
+ } else {
+ pattern[i] = twoStar;
+ }
+ } else if (i === pattern.length - 1) {
+ pattern[i - 1] += "(?:\\/|" + twoStar + ")?";
+ } else {
+ pattern[i - 1] += "(?:\\/|\\/" + twoStar + "\\/)" + pattern[i + 1];
+ pattern[i + 1] = GLOBSTAR;
+ }
+ });
+ return pattern.filter((p) => p !== GLOBSTAR).join("/");
+ }).join("|");
+ re = "^(?:" + re + ")$";
+ if (this.negate)
+ re = "^(?!" + re + ").*$";
+ try {
+ this.regexp = new RegExp(re, flags);
+ } catch (ex) {
+ this.regexp = false;
+ }
+ return this.regexp;
+ }
+ match(f, partial = this.partial) {
+ this.debug("match", f, this.pattern);
+ if (this.comment)
+ return false;
+ if (this.empty)
+ return f === "";
+ if (f === "/" && partial)
+ return true;
+ const options14 = this.options;
+ if (path45.sep !== "/") {
+ f = f.split(path45.sep).join("/");
+ }
+ f = f.split(slashSplit);
+ this.debug(this.pattern, "split", f);
+ const set = this.set;
+ this.debug(this.pattern, "set", set);
+ let filename;
+ for (let i = f.length - 1; i >= 0; i--) {
+ filename = f[i];
+ if (filename)
+ break;
+ }
+ for (let i = 0; i < set.length; i++) {
+ const pattern = set[i];
+ let file = f;
+ if (options14.matchBase && pattern.length === 1) {
+ file = [filename];
+ }
+ const hit = this.matchOne(file, pattern, partial);
+ if (hit) {
+ if (options14.flipNegate)
+ return true;
+ return !this.negate;
+ }
+ }
+ if (options14.flipNegate)
+ return false;
+ return this.negate;
+ }
+ static defaults(def) {
+ return minimatch.defaults(def).Minimatch;
+ }
+ };
+ __name(Minimatch2, "Minimatch");
+ minimatch.Minimatch = Minimatch2;
+ }
+});
+
+// ../../node_modules/.pnpm/ini@1.3.8/node_modules/ini/ini.js
+var require_ini = __commonJS({
+ "../../node_modules/.pnpm/ini@1.3.8/node_modules/ini/ini.js"(exports2) {
+ init_import_meta_url();
+ exports2.parse = exports2.decode = decode;
+ exports2.stringify = exports2.encode = encode;
+ exports2.safe = safe;
+ exports2.unsafe = unsafe;
+ var eol = typeof process !== "undefined" && process.platform === "win32" ? "\r\n" : "\n";
+ function encode(obj, opt) {
+ var children = [];
+ var out = "";
+ if (typeof opt === "string") {
+ opt = {
+ section: opt,
+ whitespace: false
+ };
+ } else {
+ opt = opt || {};
+ opt.whitespace = opt.whitespace === true;
+ }
+ var separator = opt.whitespace ? " = " : "=";
+ Object.keys(obj).forEach(function(k, _2, __) {
+ var val = obj[k];
+ if (val && Array.isArray(val)) {
+ val.forEach(function(item) {
+ out += safe(k + "[]") + separator + safe(item) + "\n";
+ });
+ } else if (val && typeof val === "object")
+ children.push(k);
+ else
+ out += safe(k) + separator + safe(val) + eol;
+ });
+ if (opt.section && out.length)
+ out = "[" + safe(opt.section) + "]" + eol + out;
+ children.forEach(function(k, _2, __) {
+ var nk = dotSplit(k).join("\\.");
+ var section = (opt.section ? opt.section + "." : "") + nk;
+ var child = encode(obj[k], {
+ section,
+ whitespace: opt.whitespace
+ });
+ if (out.length && child.length)
+ out += eol;
+ out += child;
+ });
+ return out;
+ }
+ __name(encode, "encode");
+ function dotSplit(str) {
+ return str.replace(/\1/g, "LITERAL\\1LITERAL").replace(/\\\./g, "").split(/\./).map(function(part) {
+ return part.replace(/\1/g, "\\.").replace(/\2LITERAL\\1LITERAL\2/g, "");
+ });
+ }
+ __name(dotSplit, "dotSplit");
+ function decode(str) {
+ var out = {};
+ var p = out;
+ var section = null;
+ var re = /^\[([^\]]*)\]$|^([^=]+)(=(.*))?$/i;
+ var lines = str.split(/[\r\n]+/g);
+ lines.forEach(function(line, _2, __) {
+ if (!line || line.match(/^\s*[;#]/))
+ return;
+ var match = line.match(re);
+ if (!match)
+ return;
+ if (match[1] !== void 0) {
+ section = unsafe(match[1]);
+ if (section === "__proto__") {
+ p = {};
+ return;
+ }
+ p = out[section] = out[section] || {};
+ return;
+ }
+ var key = unsafe(match[2]);
+ if (key === "__proto__")
+ return;
+ var value = match[3] ? unsafe(match[4]) : true;
+ switch (value) {
+ case "true":
+ case "false":
+ case "null":
+ value = JSON.parse(value);
+ }
+ if (key.length > 2 && key.slice(-2) === "[]") {
+ key = key.substring(0, key.length - 2);
+ if (key === "__proto__")
+ return;
+ if (!p[key])
+ p[key] = [];
+ else if (!Array.isArray(p[key]))
+ p[key] = [p[key]];
+ }
+ if (Array.isArray(p[key]))
+ p[key].push(value);
+ else
+ p[key] = value;
+ });
+ Object.keys(out).filter(function(k, _2, __) {
+ if (!out[k] || typeof out[k] !== "object" || Array.isArray(out[k]))
+ return false;
+ var parts = dotSplit(k);
+ var p2 = out;
+ var l = parts.pop();
+ var nl = l.replace(/\\\./g, ".");
+ parts.forEach(function(part, _3, __2) {
+ if (part === "__proto__")
+ return;
+ if (!p2[part] || typeof p2[part] !== "object")
+ p2[part] = {};
+ p2 = p2[part];
+ });
+ if (p2 === out && nl === l)
+ return false;
+ p2[nl] = out[k];
+ return true;
+ }).forEach(function(del, _2, __) {
+ delete out[del];
+ });
+ return out;
+ }
+ __name(decode, "decode");
+ function isQuoted(val) {
+ return val.charAt(0) === '"' && val.slice(-1) === '"' || val.charAt(0) === "'" && val.slice(-1) === "'";
+ }
+ __name(isQuoted, "isQuoted");
+ function safe(val) {
+ return typeof val !== "string" || val.match(/[=\r\n]/) || val.match(/^\[/) || val.length > 1 && isQuoted(val) || val !== val.trim() ? JSON.stringify(val) : val.replace(/;/g, "\\;").replace(/#/g, "\\#");
+ }
+ __name(safe, "safe");
+ function unsafe(val, doUnesc) {
+ val = (val || "").trim();
+ if (isQuoted(val)) {
+ if (val.charAt(0) === "'")
+ val = val.substr(1, val.length - 2);
+ try {
+ val = JSON.parse(val);
+ } catch (_2) {
+ }
+ } else {
+ var esc = false;
+ var unesc = "";
+ for (var i = 0, l = val.length; i < l; i++) {
+ var c = val.charAt(i);
+ if (esc) {
+ if ("\\;#".indexOf(c) !== -1)
+ unesc += c;
+ else
+ unesc += "\\" + c;
+ esc = false;
+ } else if (";#".indexOf(c) !== -1)
+ break;
+ else if (c === "\\")
+ esc = true;
+ else
+ unesc += c;
+ }
+ if (esc)
+ unesc += "\\";
+ return unesc.trim();
+ }
+ return val;
+ }
+ __name(unsafe, "unsafe");
+ }
+});
+
+// ../../node_modules/.pnpm/strip-json-comments@2.0.1/node_modules/strip-json-comments/index.js
+var require_strip_json_comments = __commonJS({
+ "../../node_modules/.pnpm/strip-json-comments@2.0.1/node_modules/strip-json-comments/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ var singleComment = 1;
+ var multiComment = 2;
+ function stripWithoutWhitespace() {
+ return "";
+ }
+ __name(stripWithoutWhitespace, "stripWithoutWhitespace");
+ function stripWithWhitespace(str, start, end) {
+ return str.slice(start, end).replace(/\S/g, " ");
+ }
+ __name(stripWithWhitespace, "stripWithWhitespace");
+ module2.exports = function(str, opts) {
+ opts = opts || {};
+ var currentChar;
+ var nextChar;
+ var insideString = false;
+ var insideComment = false;
+ var offset = 0;
+ var ret = "";
+ var strip = opts.whitespace === false ? stripWithoutWhitespace : stripWithWhitespace;
+ for (var i = 0; i < str.length; i++) {
+ currentChar = str[i];
+ nextChar = str[i + 1];
+ if (!insideComment && currentChar === '"') {
+ var escaped = str[i - 1] === "\\" && str[i - 2] !== "\\";
+ if (!escaped) {
+ insideString = !insideString;
+ }
+ }
+ if (insideString) {
+ continue;
+ }
+ if (!insideComment && currentChar + nextChar === "//") {
+ ret += str.slice(offset, i);
+ offset = i;
+ insideComment = singleComment;
+ i++;
+ } else if (insideComment === singleComment && currentChar + nextChar === "\r\n") {
+ i++;
+ insideComment = false;
+ ret += strip(str, offset, i);
+ offset = i;
+ continue;
+ } else if (insideComment === singleComment && currentChar === "\n") {
+ insideComment = false;
+ ret += strip(str, offset, i);
+ offset = i;
+ } else if (!insideComment && currentChar + nextChar === "/*") {
+ ret += str.slice(offset, i);
+ offset = i;
+ insideComment = multiComment;
+ i++;
+ continue;
+ } else if (insideComment === multiComment && currentChar + nextChar === "*/") {
+ i++;
+ insideComment = false;
+ ret += strip(str, offset, i + 1);
+ offset = i + 1;
+ continue;
+ }
+ }
+ return ret + (insideComment ? strip(str.substr(offset)) : str.substr(offset));
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/lib/utils.js
+var require_utils6 = __commonJS({
+ "../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/lib/utils.js"(exports2) {
+ "use strict";
+ init_import_meta_url();
+ var fs20 = require("fs");
+ var ini = require_ini();
+ var path45 = require("path");
+ var stripJsonComments = require_strip_json_comments();
+ var parse4 = exports2.parse = function(content) {
+ if (/^\s*{/.test(content))
+ return JSON.parse(stripJsonComments(content));
+ return ini.parse(content);
+ };
+ var file = exports2.file = function() {
+ var args = [].slice.call(arguments).filter(function(arg) {
+ return arg != null;
+ });
+ for (var i in args)
+ if ("string" !== typeof args[i])
+ return;
+ var file2 = path45.join.apply(null, args);
+ var content;
+ try {
+ return fs20.readFileSync(file2, "utf-8");
+ } catch (err) {
+ return;
+ }
+ };
+ var json = exports2.json = function() {
+ var content = file.apply(null, arguments);
+ return content ? parse4(content) : null;
+ };
+ var env5 = exports2.env = function(prefix, env6) {
+ env6 = env6 || process.env;
+ var obj = {};
+ var l = prefix.length;
+ for (var k in env6) {
+ if (k.toLowerCase().indexOf(prefix.toLowerCase()) === 0) {
+ var keypath = k.substring(l).split("__");
+ var _emptyStringIndex;
+ while ((_emptyStringIndex = keypath.indexOf("")) > -1) {
+ keypath.splice(_emptyStringIndex, 1);
+ }
+ var cursor = obj;
+ keypath.forEach(/* @__PURE__ */ __name(function _buildSubObj(_subkey, i) {
+ if (!_subkey || typeof cursor !== "object")
+ return;
+ if (i === keypath.length - 1)
+ cursor[_subkey] = env6[k];
+ if (cursor[_subkey] === void 0)
+ cursor[_subkey] = {};
+ cursor = cursor[_subkey];
+ }, "_buildSubObj"));
+ }
+ }
+ return obj;
+ };
+ var find = exports2.find = function() {
+ var rel = path45.join.apply(null, [].slice.call(arguments));
+ function find2(start, rel2) {
+ var file2 = path45.join(start, rel2);
+ try {
+ fs20.statSync(file2);
+ return file2;
+ } catch (err) {
+ if (path45.dirname(start) !== start)
+ return find2(path45.dirname(start), rel2);
+ }
+ }
+ __name(find2, "find");
+ return find2(process.cwd(), rel);
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/deep-extend@0.6.0/node_modules/deep-extend/lib/deep-extend.js
+var require_deep_extend = __commonJS({
+ "../../node_modules/.pnpm/deep-extend@0.6.0/node_modules/deep-extend/lib/deep-extend.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ function isSpecificValue(val) {
+ return val instanceof Buffer || val instanceof Date || val instanceof RegExp ? true : false;
+ }
+ __name(isSpecificValue, "isSpecificValue");
+ function cloneSpecificValue(val) {
+ if (val instanceof Buffer) {
+ var x = Buffer.alloc ? Buffer.alloc(val.length) : new Buffer(val.length);
+ val.copy(x);
+ return x;
+ } else if (val instanceof Date) {
+ return new Date(val.getTime());
+ } else if (val instanceof RegExp) {
+ return new RegExp(val);
+ } else {
+ throw new Error("Unexpected situation");
+ }
+ }
+ __name(cloneSpecificValue, "cloneSpecificValue");
+ function deepCloneArray(arr) {
+ var clone = [];
+ arr.forEach(function(item, index) {
+ if (typeof item === "object" && item !== null) {
+ if (Array.isArray(item)) {
+ clone[index] = deepCloneArray(item);
+ } else if (isSpecificValue(item)) {
+ clone[index] = cloneSpecificValue(item);
+ } else {
+ clone[index] = deepExtend({}, item);
+ }
+ } else {
+ clone[index] = item;
+ }
+ });
+ return clone;
+ }
+ __name(deepCloneArray, "deepCloneArray");
+ function safeGetProperty(object, property) {
+ return property === "__proto__" ? void 0 : object[property];
+ }
+ __name(safeGetProperty, "safeGetProperty");
+ var deepExtend = module2.exports = function() {
+ if (arguments.length < 1 || typeof arguments[0] !== "object") {
+ return false;
+ }
+ if (arguments.length < 2) {
+ return arguments[0];
+ }
+ var target = arguments[0];
+ var args = Array.prototype.slice.call(arguments, 1);
+ var val, src, clone;
+ args.forEach(function(obj) {
+ if (typeof obj !== "object" || obj === null || Array.isArray(obj)) {
+ return;
+ }
+ Object.keys(obj).forEach(function(key) {
+ src = safeGetProperty(target, key);
+ val = safeGetProperty(obj, key);
+ if (val === target) {
+ return;
+ } else if (typeof val !== "object" || val === null) {
+ target[key] = val;
+ return;
+ } else if (Array.isArray(val)) {
+ target[key] = deepCloneArray(val);
+ return;
+ } else if (isSpecificValue(val)) {
+ target[key] = cloneSpecificValue(val);
+ return;
+ } else if (typeof src !== "object" || src === null || Array.isArray(src)) {
+ target[key] = deepExtend({}, val);
+ return;
+ } else {
+ target[key] = deepExtend(src, val);
+ return;
+ }
+ });
+ });
+ return target;
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js
+var require_minimist = __commonJS({
+ "../../node_modules/.pnpm/minimist@1.2.6/node_modules/minimist/index.js"(exports2, module2) {
+ init_import_meta_url();
+ module2.exports = function(args, opts) {
+ if (!opts)
+ opts = {};
+ var flags = { bools: {}, strings: {}, unknownFn: null };
+ if (typeof opts["unknown"] === "function") {
+ flags.unknownFn = opts["unknown"];
+ }
+ if (typeof opts["boolean"] === "boolean" && opts["boolean"]) {
+ flags.allBools = true;
+ } else {
+ [].concat(opts["boolean"]).filter(Boolean).forEach(function(key2) {
+ flags.bools[key2] = true;
+ });
+ }
+ var aliases2 = {};
+ Object.keys(opts.alias || {}).forEach(function(key2) {
+ aliases2[key2] = [].concat(opts.alias[key2]);
+ aliases2[key2].forEach(function(x) {
+ aliases2[x] = [key2].concat(aliases2[key2].filter(function(y) {
+ return x !== y;
+ }));
+ });
+ });
+ [].concat(opts.string).filter(Boolean).forEach(function(key2) {
+ flags.strings[key2] = true;
+ if (aliases2[key2]) {
+ flags.strings[aliases2[key2]] = true;
+ }
+ });
+ var defaults = opts["default"] || {};
+ var argv = { _: [] };
+ Object.keys(flags.bools).forEach(function(key2) {
+ setArg(key2, defaults[key2] === void 0 ? false : defaults[key2]);
+ });
+ var notFlags = [];
+ if (args.indexOf("--") !== -1) {
+ notFlags = args.slice(args.indexOf("--") + 1);
+ args = args.slice(0, args.indexOf("--"));
+ }
+ function argDefined(key2, arg2) {
+ return flags.allBools && /^--[^=]+$/.test(arg2) || flags.strings[key2] || flags.bools[key2] || aliases2[key2];
+ }
+ __name(argDefined, "argDefined");
+ function setArg(key2, val, arg2) {
+ if (arg2 && flags.unknownFn && !argDefined(key2, arg2)) {
+ if (flags.unknownFn(arg2) === false)
+ return;
+ }
+ var value2 = !flags.strings[key2] && isNumber(val) ? Number(val) : val;
+ setKey(argv, key2.split("."), value2);
+ (aliases2[key2] || []).forEach(function(x) {
+ setKey(argv, x.split("."), value2);
+ });
+ }
+ __name(setArg, "setArg");
+ function setKey(obj, keys, value2) {
+ var o = obj;
+ for (var i2 = 0; i2 < keys.length - 1; i2++) {
+ var key2 = keys[i2];
+ if (isConstructorOrProto(o, key2))
+ return;
+ if (o[key2] === void 0)
+ o[key2] = {};
+ if (o[key2] === Object.prototype || o[key2] === Number.prototype || o[key2] === String.prototype)
+ o[key2] = {};
+ if (o[key2] === Array.prototype)
+ o[key2] = [];
+ o = o[key2];
+ }
+ var key2 = keys[keys.length - 1];
+ if (isConstructorOrProto(o, key2))
+ return;
+ if (o === Object.prototype || o === Number.prototype || o === String.prototype)
+ o = {};
+ if (o === Array.prototype)
+ o = [];
+ if (o[key2] === void 0 || flags.bools[key2] || typeof o[key2] === "boolean") {
+ o[key2] = value2;
+ } else if (Array.isArray(o[key2])) {
+ o[key2].push(value2);
+ } else {
+ o[key2] = [o[key2], value2];
+ }
+ }
+ __name(setKey, "setKey");
+ function aliasIsBoolean(key2) {
+ return aliases2[key2].some(function(x) {
+ return flags.bools[x];
+ });
+ }
+ __name(aliasIsBoolean, "aliasIsBoolean");
+ for (var i = 0; i < args.length; i++) {
+ var arg = args[i];
+ if (/^--.+=/.test(arg)) {
+ var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
+ var key = m[1];
+ var value = m[2];
+ if (flags.bools[key]) {
+ value = value !== "false";
+ }
+ setArg(key, value, arg);
+ } else if (/^--no-.+/.test(arg)) {
+ var key = arg.match(/^--no-(.+)/)[1];
+ setArg(key, false, arg);
+ } else if (/^--.+/.test(arg)) {
+ var key = arg.match(/^--(.+)/)[1];
+ var next = args[i + 1];
+ if (next !== void 0 && !/^-/.test(next) && !flags.bools[key] && !flags.allBools && (aliases2[key] ? !aliasIsBoolean(key) : true)) {
+ setArg(key, next, arg);
+ i++;
+ } else if (/^(true|false)$/.test(next)) {
+ setArg(key, next === "true", arg);
+ i++;
+ } else {
+ setArg(key, flags.strings[key] ? "" : true, arg);
+ }
+ } else if (/^-[^-]+/.test(arg)) {
+ var letters = arg.slice(1, -1).split("");
+ var broken = false;
+ for (var j = 0; j < letters.length; j++) {
+ var next = arg.slice(j + 2);
+ if (next === "-") {
+ setArg(letters[j], next, arg);
+ continue;
+ }
+ if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
+ setArg(letters[j], next.split("=")[1], arg);
+ broken = true;
+ break;
+ }
+ if (/[A-Za-z]/.test(letters[j]) && /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
+ setArg(letters[j], next, arg);
+ broken = true;
+ break;
+ }
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
+ setArg(letters[j], arg.slice(j + 2), arg);
+ broken = true;
+ break;
+ } else {
+ setArg(letters[j], flags.strings[letters[j]] ? "" : true, arg);
+ }
+ }
+ var key = arg.slice(-1)[0];
+ if (!broken && key !== "-") {
+ if (args[i + 1] && !/^(-|--)[^-]/.test(args[i + 1]) && !flags.bools[key] && (aliases2[key] ? !aliasIsBoolean(key) : true)) {
+ setArg(key, args[i + 1], arg);
+ i++;
+ } else if (args[i + 1] && /^(true|false)$/.test(args[i + 1])) {
+ setArg(key, args[i + 1] === "true", arg);
+ i++;
+ } else {
+ setArg(key, flags.strings[key] ? "" : true, arg);
+ }
+ }
+ } else {
+ if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
+ argv._.push(
+ flags.strings["_"] || !isNumber(arg) ? arg : Number(arg)
+ );
+ }
+ if (opts.stopEarly) {
+ argv._.push.apply(argv._, args.slice(i + 1));
+ break;
+ }
+ }
+ }
+ Object.keys(defaults).forEach(function(key2) {
+ if (!hasKey2(argv, key2.split("."))) {
+ setKey(argv, key2.split("."), defaults[key2]);
+ (aliases2[key2] || []).forEach(function(x) {
+ setKey(argv, x.split("."), defaults[key2]);
+ });
+ }
+ });
+ if (opts["--"]) {
+ argv["--"] = new Array();
+ notFlags.forEach(function(key2) {
+ argv["--"].push(key2);
+ });
+ } else {
+ notFlags.forEach(function(key2) {
+ argv._.push(key2);
+ });
+ }
+ return argv;
+ };
+ function hasKey2(obj, keys) {
+ var o = obj;
+ keys.slice(0, -1).forEach(function(key2) {
+ o = o[key2] || {};
+ });
+ var key = keys[keys.length - 1];
+ return key in o;
+ }
+ __name(hasKey2, "hasKey");
+ function isNumber(x) {
+ if (typeof x === "number")
+ return true;
+ if (/^0x[0-9a-f]+$/i.test(x))
+ return true;
+ return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
+ }
+ __name(isNumber, "isNumber");
+ function isConstructorOrProto(obj, key) {
+ return key === "constructor" && typeof obj[key] === "function" || key === "__proto__";
+ }
+ __name(isConstructorOrProto, "isConstructorOrProto");
+ }
+});
+
+// ../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js
+var require_rc = __commonJS({
+ "../../node_modules/.pnpm/rc@1.2.8/node_modules/rc/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var cc = require_utils6();
+ var join12 = require("path").join;
+ var deepExtend = require_deep_extend();
+ var etc = "/etc";
+ var win = process.platform === "win32";
+ var home = win ? process.env.USERPROFILE : process.env.HOME;
+ module2.exports = function(name, defaults, argv, parse4) {
+ if ("string" !== typeof name)
+ throw new Error("rc(name): name *must* be string");
+ if (!argv)
+ argv = require_minimist()(process.argv.slice(2));
+ defaults = ("string" === typeof defaults ? cc.json(defaults) : defaults) || {};
+ parse4 = parse4 || cc.parse;
+ var env5 = cc.env(name + "_");
+ var configs = [defaults];
+ var configFiles = [];
+ function addConfigFile(file) {
+ if (configFiles.indexOf(file) >= 0)
+ return;
+ var fileConfig = cc.file(file);
+ if (fileConfig) {
+ configs.push(parse4(fileConfig));
+ configFiles.push(file);
+ }
+ }
+ __name(addConfigFile, "addConfigFile");
+ if (!win)
+ [
+ join12(etc, name, "config"),
+ join12(etc, name + "rc")
+ ].forEach(addConfigFile);
+ if (home)
+ [
+ join12(home, ".config", name, "config"),
+ join12(home, ".config", name),
+ join12(home, "." + name, "config"),
+ join12(home, "." + name + "rc")
+ ].forEach(addConfigFile);
+ addConfigFile(cc.find("." + name + "rc"));
+ if (env5.config)
+ addConfigFile(env5.config);
+ if (argv.config)
+ addConfigFile(argv.config);
+ return deepExtend.apply(null, configs.concat([
+ env5,
+ argv,
+ configFiles.length ? { configs: configFiles, config: configFiles[configFiles.length - 1] } : void 0
+ ]));
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/registry-url@3.1.0/node_modules/registry-url/index.js
+var require_registry_url = __commonJS({
+ "../../node_modules/.pnpm/registry-url@3.1.0/node_modules/registry-url/index.js"(exports2, module2) {
+ "use strict";
+ init_import_meta_url();
+ module2.exports = function(scope) {
+ var rc = require_rc()("npm", { registry: "https://registry.npmjs.org/" });
+ var url3 = rc[scope + ":registry"] || rc.registry;
+ return url3.slice(-1) === "/" ? url3 : url3 + "/";
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/base64.js
+var require_base64 = __commonJS({
+ "../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/base64.js"(exports2, module2) {
+ init_import_meta_url();
+ var safeBuffer = require_safe_buffer().Buffer;
+ function decodeBase64(base64) {
+ return safeBuffer.from(base64, "base64").toString("utf8");
+ }
+ __name(decodeBase64, "decodeBase64");
+ function encodeBase64(string) {
+ return safeBuffer.from(string, "utf8").toString("base64");
+ }
+ __name(encodeBase64, "encodeBase64");
+ module2.exports = {
+ decodeBase64,
+ encodeBase64
+ };
+ }
+});
+
+// ../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/index.js
+var require_registry_auth_token = __commonJS({
+ "../../node_modules/.pnpm/registry-auth-token@3.3.2/node_modules/registry-auth-token/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var url3 = require("url");
+ var base64 = require_base64();
+ var decodeBase64 = base64.decodeBase64;
+ var encodeBase64 = base64.encodeBase64;
+ var tokenKey = ":_authToken";
+ var userKey = ":username";
+ var passwordKey = ":_password";
+ module2.exports = function() {
+ var checkUrl;
+ var options14;
+ if (arguments.length >= 2) {
+ checkUrl = arguments[0];
+ options14 = arguments[1];
+ } else if (typeof arguments[0] === "string") {
+ checkUrl = arguments[0];
+ } else {
+ options14 = arguments[0];
+ }
+ options14 = options14 || {};
+ options14.npmrc = options14.npmrc || require_rc()("npm", { registry: "https://registry.npmjs.org/" });
+ checkUrl = checkUrl || options14.npmrc.registry;
+ return getRegistryAuthInfo(checkUrl, options14) || getLegacyAuthInfo(options14.npmrc);
+ };
+ function getRegistryAuthInfo(checkUrl, options14) {
+ var parsed = url3.parse(checkUrl, false, true);
+ var pathname;
+ while (pathname !== "/" && parsed.pathname !== pathname) {
+ pathname = parsed.pathname || "/";
+ var regUrl = "//" + parsed.host + pathname.replace(/\/$/, "");
+ var authInfo = getAuthInfoForUrl(regUrl, options14.npmrc);
+ if (authInfo) {
+ return authInfo;
+ }
+ if (!options14.recursive) {
+ return /\/$/.test(checkUrl) ? void 0 : getRegistryAuthInfo(url3.resolve(checkUrl, "."), options14);
+ }
+ parsed.pathname = url3.resolve(normalizePath(pathname), "..") || "/";
+ }
+ return void 0;
+ }
+ __name(getRegistryAuthInfo, "getRegistryAuthInfo");
+ function getLegacyAuthInfo(npmrc) {
+ if (npmrc._auth) {
+ return { token: npmrc._auth, type: "Basic" };
+ }
+ return void 0;
+ }
+ __name(getLegacyAuthInfo, "getLegacyAuthInfo");
+ function normalizePath(path45) {
+ return path45[path45.length - 1] === "/" ? path45 : path45 + "/";
+ }
+ __name(normalizePath, "normalizePath");
+ function getAuthInfoForUrl(regUrl, npmrc) {
+ var bearerAuth = getBearerToken(npmrc[regUrl + tokenKey] || npmrc[regUrl + "/" + tokenKey]);
+ if (bearerAuth) {
+ return bearerAuth;
+ }
+ var username = npmrc[regUrl + userKey] || npmrc[regUrl + "/" + userKey];
+ var password = npmrc[regUrl + passwordKey] || npmrc[regUrl + "/" + passwordKey];
+ var basicAuth = getTokenForUsernameAndPassword(username, password);
+ if (basicAuth) {
+ return basicAuth;
+ }
+ return void 0;
+ }
+ __name(getAuthInfoForUrl, "getAuthInfoForUrl");
+ function getBearerToken(tok) {
+ if (!tok) {
+ return void 0;
+ }
+ var token = tok.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
+ return process.env[envVar];
+ });
+ return { token, type: "Bearer" };
+ }
+ __name(getBearerToken, "getBearerToken");
+ function getTokenForUsernameAndPassword(username, password) {
+ if (!username || !password) {
+ return void 0;
+ }
+ var pass = decodeBase64(password.replace(/^\$\{?([^}]*)\}?$/, function(fullMatch, envVar) {
+ return process.env[envVar];
+ }));
+ var token = encodeBase64(username + ":" + pass);
+ return {
+ token,
+ type: "Basic",
+ password: pass,
+ username
+ };
+ }
+ __name(getTokenForUsernameAndPassword, "getTokenForUsernameAndPassword");
+ }
+});
+
+// ../../node_modules/.pnpm/update-check@1.5.4/node_modules/update-check/index.js
+var require_update_check = __commonJS({
+ "../../node_modules/.pnpm/update-check@1.5.4/node_modules/update-check/index.js"(exports2, module2) {
+ init_import_meta_url();
+ var { URL: URL4 } = require("url");
+ var { join: join12 } = require("path");
+ var fs20 = require("fs");
+ var { promisify: promisify2 } = require("util");
+ var { tmpdir: tmpdir5 } = require("os");
+ var registryUrl = require_registry_url();
+ var writeFile4 = promisify2(fs20.writeFile);
+ var mkdir3 = promisify2(fs20.mkdir);
+ var readFile6 = promisify2(fs20.readFile);
+ var compareVersions = /* @__PURE__ */ __name((a, b) => a.localeCompare(b, "en-US", { numeric: true }), "compareVersions");
+ var encode = /* @__PURE__ */ __name((value) => encodeURIComponent(value).replace(/^%40/, "@"), "encode");
+ var getFile = /* @__PURE__ */ __name(async (details, distTag) => {
+ const rootDir = tmpdir5();
+ const subDir = join12(rootDir, "update-check");
+ if (!fs20.existsSync(subDir)) {
+ await mkdir3(subDir);
+ }
+ let name = `${details.name}-${distTag}.json`;
+ if (details.scope) {
+ name = `${details.scope}-${name}`;
+ }
+ return join12(subDir, name);
+ }, "getFile");
+ var evaluateCache = /* @__PURE__ */ __name(async (file, time, interval2) => {
+ if (fs20.existsSync(file)) {
+ const content = await readFile6(file, "utf8");
+ const { lastUpdate, latest } = JSON.parse(content);
+ const nextCheck = lastUpdate + interval2;
+ if (nextCheck > time) {
+ return {
+ shouldCheck: false,
+ latest
+ };
+ }
+ }
+ return {
+ shouldCheck: true,
+ latest: null
+ };
+ }, "evaluateCache");
+ var updateCache = /* @__PURE__ */ __name(async (file, latest, lastUpdate) => {
+ const content = JSON.stringify({
+ latest,
+ lastUpdate
+ });
+ await writeFile4(file, content, "utf8");
+ }, "updateCache");
+ var loadPackage = /* @__PURE__ */ __name((url3, authInfo) => new Promise((resolve18, reject) => {
+ const options14 = {
+ host: url3.hostname,
+ path: url3.pathname,
+ port: url3.port,
+ headers: {
+ accept: "application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*"
+ },
+ timeout: 2e3
+ };
+ if (authInfo) {
+ options14.headers.authorization = `${authInfo.type} ${authInfo.token}`;
+ }
+ const { get } = url3.protocol === "https:" ? require("https") : require("http");
+ get(options14, (response) => {
+ const { statusCode } = response;
+ if (statusCode !== 200) {
+ const error = new Error(`Request failed with code ${statusCode}`);
+ error.code = statusCode;
+ reject(error);
+ response.resume();
+ return;
+ }
+ let rawData = "";
+ response.setEncoding("utf8");
+ response.on("data", (chunk) => {
+ rawData += chunk;
+ });
+ response.on("end", () => {
+ try {
+ const parsedData = JSON.parse(rawData);
+ resolve18(parsedData);
+ } catch (e2) {
+ reject(e2);
+ }
+ });
+ }).on("error", reject).on("timeout", reject);
+ }), "loadPackage");
+ var getMostRecent = /* @__PURE__ */ __name(async ({ full, scope }, distTag) => {
+ const regURL = registryUrl(scope);
+ const url3 = new URL4(full, regURL);
+ let spec = null;
+ try {
+ spec = await loadPackage(url3);
+ } catch (err) {
+ if (err.code && String(err.code).startsWith(4)) {
+ const registryAuthToken = require_registry_auth_token();
+ const authInfo = registryAuthToken(regURL, { recursive: true });
+ spec = await loadPackage(url3, authInfo);
+ } else {
+ throw err;
+ }
+ }
+ const version2 = spec["dist-tags"][distTag];
+ if (!version2) {
+ throw new Error(`Distribution tag ${distTag} is not available`);
+ }
+ return version2;
+ }, "getMostRecent");
+ var defaultConfig = {
+ interval: 36e5,
+ distTag: "latest"
+ };
+ var getDetails = /* @__PURE__ */ __name((name) => {
+ const spec = {
+ full: encode(name)
+ };
+ if (name.includes("/")) {
+ const parts = name.split("/");
+ spec.scope = parts[0];
+ spec.name = parts[1];
+ } else {
+ spec.scope = null;
+ spec.name = name;
+ }
+ return spec;
+ }, "getDetails");
+ module2.exports = async (pkg, config) => {
+ if (typeof pkg !== "object") {
+ throw new Error("The first parameter should be your package.json file content");
+ }
+ const details = getDetails(pkg.name);
+ const time = Date.now();
+ const { distTag, interval: interval2 } = Object.assign({}, defaultConfig, config);
+ const file = await getFile(details, distTag);
+ let latest = null;
+ let shouldCheck = true;
+ ({ shouldCheck, latest } = await evaluateCache(file, time, interval2));
+ if (shouldCheck) {
+ latest = await getMostRecent(details, distTag);
+ await updateCache(file, latest, time);
+ }
+ const comparision = compareVersions(pkg.version, latest);
+ if (comparision === -1) {
+ return {
+ latest,
+ fromCache: !shouldCheck
+ };
+ }
+ return null;
+ };
+ }
+});
+
+// src/cli.ts
+var cli_exports = {};
+__export(cli_exports, {
+ unstable_dev: () => unstable_dev,
+ unstable_pages: () => unstable_pages
+});
+module.exports = __toCommonJS(cli_exports);
+init_import_meta_url();
+var import_process = __toESM(require("process"));
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/helpers/helpers.mjs
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/apply-extends.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/yerror.js
+init_import_meta_url();
+var YError = class extends Error {
+ constructor(msg) {
+ super(msg || "yargs error");
+ this.name = "YError";
+ if (Error.captureStackTrace) {
+ Error.captureStackTrace(this, YError);
+ }
+ }
+};
+__name(YError, "YError");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/apply-extends.js
+var previouslyVisitedConfigs = [];
+var shim;
+function applyExtends(config, cwd2, mergeExtends, _shim) {
+ shim = _shim;
+ let defaultConfig = {};
+ if (Object.prototype.hasOwnProperty.call(config, "extends")) {
+ if (typeof config.extends !== "string")
+ return defaultConfig;
+ const isPath = /\.json|\..*rc$/.test(config.extends);
+ let pathToDefault = null;
+ if (!isPath) {
+ try {
+ pathToDefault = require.resolve(config.extends);
+ } catch (_err) {
+ return config;
+ }
+ } else {
+ pathToDefault = getPathToDefaultConfig(cwd2, config.extends);
+ }
+ checkForCircularExtends(pathToDefault);
+ previouslyVisitedConfigs.push(pathToDefault);
+ defaultConfig = isPath ? JSON.parse(shim.readFileSync(pathToDefault, "utf8")) : require(config.extends);
+ delete config.extends;
+ defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim);
+ }
+ previouslyVisitedConfigs = [];
+ return mergeExtends ? mergeDeep(defaultConfig, config) : Object.assign({}, defaultConfig, config);
+}
+__name(applyExtends, "applyExtends");
+function checkForCircularExtends(cfgPath) {
+ if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
+ throw new YError(`Circular extended configurations: '${cfgPath}'.`);
+ }
+}
+__name(checkForCircularExtends, "checkForCircularExtends");
+function getPathToDefaultConfig(cwd2, pathToExtend) {
+ return shim.path.resolve(cwd2, pathToExtend);
+}
+__name(getPathToDefaultConfig, "getPathToDefaultConfig");
+function mergeDeep(config1, config2) {
+ const target = {};
+ function isObject2(obj) {
+ return obj && typeof obj === "object" && !Array.isArray(obj);
+ }
+ __name(isObject2, "isObject");
+ Object.assign(target, config1);
+ for (const key of Object.keys(config2)) {
+ if (isObject2(config2[key]) && isObject2(target[key])) {
+ target[key] = mergeDeep(config1[key], config2[key]);
+ } else {
+ target[key] = config2[key];
+ }
+ }
+ return target;
+}
+__name(mergeDeep, "mergeDeep");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/process-argv.js
+init_import_meta_url();
+function getProcessArgvBinIndex() {
+ if (isBundledElectronApp())
+ return 0;
+ return 1;
+}
+__name(getProcessArgvBinIndex, "getProcessArgvBinIndex");
+function isBundledElectronApp() {
+ return isElectronApp() && !process.defaultApp;
+}
+__name(isBundledElectronApp, "isBundledElectronApp");
+function isElectronApp() {
+ return !!process.versions.electron;
+}
+__name(isElectronApp, "isElectronApp");
+function hideBin(argv) {
+ return argv.slice(getProcessArgvBinIndex() + 1);
+}
+__name(hideBin, "hideBin");
+function getProcessArgvBin() {
+ return process.argv[getProcessArgvBinIndex()];
+}
+__name(getProcessArgvBin, "getProcessArgvBin");
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/index.js
+init_import_meta_url();
+var import_util = require("util");
+var import_path = require("path");
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/string-utils.js
+init_import_meta_url();
+function camelCase(str) {
+ const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
+ if (!isCamelCase) {
+ str = str.toLowerCase();
+ }
+ if (str.indexOf("-") === -1 && str.indexOf("_") === -1) {
+ return str;
+ } else {
+ let camelcase = "";
+ let nextChrUpper = false;
+ const leadingHyphens = str.match(/^-+/);
+ for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
+ let chr = str.charAt(i);
+ if (nextChrUpper) {
+ nextChrUpper = false;
+ chr = chr.toUpperCase();
+ }
+ if (i !== 0 && (chr === "-" || chr === "_")) {
+ nextChrUpper = true;
+ } else if (chr !== "-" && chr !== "_") {
+ camelcase += chr;
+ }
+ }
+ return camelcase;
+ }
+}
+__name(camelCase, "camelCase");
+function decamelize(str, joinString) {
+ const lowercase = str.toLowerCase();
+ joinString = joinString || "-";
+ let notCamelcase = "";
+ for (let i = 0; i < str.length; i++) {
+ const chrLower = lowercase.charAt(i);
+ const chrString = str.charAt(i);
+ if (chrLower !== chrString && i > 0) {
+ notCamelcase += `${joinString}${lowercase.charAt(i)}`;
+ } else {
+ notCamelcase += chrString;
+ }
+ }
+ return notCamelcase;
+}
+__name(decamelize, "decamelize");
+function looksLikeNumber(x) {
+ if (x === null || x === void 0)
+ return false;
+ if (typeof x === "number")
+ return true;
+ if (/^0x[0-9a-f]+$/i.test(x))
+ return true;
+ if (/^0[^.]/.test(x))
+ return false;
+ return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
+}
+__name(looksLikeNumber, "looksLikeNumber");
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/tokenize-arg-string.js
+init_import_meta_url();
+function tokenizeArgString(argString) {
+ if (Array.isArray(argString)) {
+ return argString.map((e2) => typeof e2 !== "string" ? e2 + "" : e2);
+ }
+ argString = argString.trim();
+ let i = 0;
+ let prevC = null;
+ let c = null;
+ let opening = null;
+ const args = [];
+ for (let ii = 0; ii < argString.length; ii++) {
+ prevC = c;
+ c = argString.charAt(ii);
+ if (c === " " && !opening) {
+ if (!(prevC === " ")) {
+ i++;
+ }
+ continue;
+ }
+ if (c === opening) {
+ opening = null;
+ } else if ((c === "'" || c === '"') && !opening) {
+ opening = c;
+ }
+ if (!args[i])
+ args[i] = "";
+ args[i] += c;
+ }
+ return args;
+}
+__name(tokenizeArgString, "tokenizeArgString");
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser-types.js
+init_import_meta_url();
+var DefaultValuesForTypeKey;
+(function(DefaultValuesForTypeKey2) {
+ DefaultValuesForTypeKey2["BOOLEAN"] = "boolean";
+ DefaultValuesForTypeKey2["STRING"] = "string";
+ DefaultValuesForTypeKey2["NUMBER"] = "number";
+ DefaultValuesForTypeKey2["ARRAY"] = "array";
+})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/yargs-parser.js
+var mixin;
+var YargsParser = class {
+ constructor(_mixin) {
+ mixin = _mixin;
+ }
+ parse(argsInput, options14) {
+ const opts = Object.assign({
+ alias: void 0,
+ array: void 0,
+ boolean: void 0,
+ config: void 0,
+ configObjects: void 0,
+ configuration: void 0,
+ coerce: void 0,
+ count: void 0,
+ default: void 0,
+ envPrefix: void 0,
+ narg: void 0,
+ normalize: void 0,
+ string: void 0,
+ number: void 0,
+ __: void 0,
+ key: void 0
+ }, options14);
+ const args = tokenizeArgString(argsInput);
+ const inputIsString = typeof argsInput === "string";
+ const aliases2 = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias));
+ const configuration = Object.assign({
+ "boolean-negation": true,
+ "camel-case-expansion": true,
+ "combine-arrays": false,
+ "dot-notation": true,
+ "duplicate-arguments-array": true,
+ "flatten-duplicate-arrays": true,
+ "greedy-arrays": true,
+ "halt-at-non-option": false,
+ "nargs-eats-options": false,
+ "negation-prefix": "no-",
+ "parse-numbers": true,
+ "parse-positional-numbers": true,
+ "populate--": false,
+ "set-placeholder-key": false,
+ "short-option-groups": true,
+ "strip-aliased": false,
+ "strip-dashed": false,
+ "unknown-options-as-args": false
+ }, opts.configuration);
+ const defaults = Object.assign(/* @__PURE__ */ Object.create(null), opts.default);
+ const configObjects = opts.configObjects || [];
+ const envPrefix = opts.envPrefix;
+ const notFlagsOption = configuration["populate--"];
+ const notFlagsArgv = notFlagsOption ? "--" : "_";
+ const newAliases = /* @__PURE__ */ Object.create(null);
+ const defaulted = /* @__PURE__ */ Object.create(null);
+ const __ = opts.__ || mixin.format;
+ const flags = {
+ aliases: /* @__PURE__ */ Object.create(null),
+ arrays: /* @__PURE__ */ Object.create(null),
+ bools: /* @__PURE__ */ Object.create(null),
+ strings: /* @__PURE__ */ Object.create(null),
+ numbers: /* @__PURE__ */ Object.create(null),
+ counts: /* @__PURE__ */ Object.create(null),
+ normalize: /* @__PURE__ */ Object.create(null),
+ configs: /* @__PURE__ */ Object.create(null),
+ nargs: /* @__PURE__ */ Object.create(null),
+ coercions: /* @__PURE__ */ Object.create(null),
+ keys: []
+ };
+ const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
+ const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)");
+ [].concat(opts.array || []).filter(Boolean).forEach(function(opt) {
+ const key = typeof opt === "object" ? opt.key : opt;
+ const assignment = Object.keys(opt).map(function(key2) {
+ const arrayFlagKeys = {
+ boolean: "bools",
+ string: "strings",
+ number: "numbers"
+ };
+ return arrayFlagKeys[key2];
+ }).filter(Boolean).pop();
+ if (assignment) {
+ flags[assignment][key] = true;
+ }
+ flags.arrays[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
+ flags.bools[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.string || []).filter(Boolean).forEach(function(key) {
+ flags.strings[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.number || []).filter(Boolean).forEach(function(key) {
+ flags.numbers[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.count || []).filter(Boolean).forEach(function(key) {
+ flags.counts[key] = true;
+ flags.keys.push(key);
+ });
+ [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
+ flags.normalize[key] = true;
+ flags.keys.push(key);
+ });
+ if (typeof opts.narg === "object") {
+ Object.entries(opts.narg).forEach(([key, value]) => {
+ if (typeof value === "number") {
+ flags.nargs[key] = value;
+ flags.keys.push(key);
+ }
+ });
+ }
+ if (typeof opts.coerce === "object") {
+ Object.entries(opts.coerce).forEach(([key, value]) => {
+ if (typeof value === "function") {
+ flags.coercions[key] = value;
+ flags.keys.push(key);
+ }
+ });
+ }
+ if (typeof opts.config !== "undefined") {
+ if (Array.isArray(opts.config) || typeof opts.config === "string") {
+ ;
+ [].concat(opts.config).filter(Boolean).forEach(function(key) {
+ flags.configs[key] = true;
+ });
+ } else if (typeof opts.config === "object") {
+ Object.entries(opts.config).forEach(([key, value]) => {
+ if (typeof value === "boolean" || typeof value === "function") {
+ flags.configs[key] = value;
+ }
+ });
+ }
+ }
+ extendAliases(opts.key, aliases2, opts.default, flags.arrays);
+ Object.keys(defaults).forEach(function(key) {
+ (flags.aliases[key] || []).forEach(function(alias) {
+ defaults[alias] = defaults[key];
+ });
+ });
+ let error = null;
+ checkConfiguration();
+ let notFlags = [];
+ const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
+ const argvReturn = {};
+ for (let i = 0; i < args.length; i++) {
+ const arg = args[i];
+ const truncatedArg = arg.replace(/^-{3,}/, "---");
+ let broken;
+ let key;
+ let letters;
+ let m;
+ let next;
+ let value;
+ if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
+ pushPositional(arg);
+ } else if (truncatedArg.match(/^---+(=|$)/)) {
+ pushPositional(arg);
+ continue;
+ } else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) {
+ m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
+ if (checkAllAliases(m[1], flags.arrays)) {
+ i = eatArray(i, m[1], args, m[2]);
+ } else if (checkAllAliases(m[1], flags.nargs) !== false) {
+ i = eatNargs(i, m[1], args, m[2]);
+ } else {
+ setArg(m[1], m[2], true);
+ }
+ }
+ } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
+ m = arg.match(negatedBoolean);
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
+ key = m[1];
+ setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
+ }
+ } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
+ m = arg.match(/^--?(.+)/);
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
+ key = m[1];
+ if (checkAllAliases(key, flags.arrays)) {
+ i = eatArray(i, key, args);
+ } else if (checkAllAliases(key, flags.nargs) !== false) {
+ i = eatNargs(i, key, args);
+ } else {
+ next = args[i + 1];
+ if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
+ setArg(key, next);
+ i++;
+ } else if (/^(true|false)$/.test(next)) {
+ setArg(key, next);
+ i++;
+ } else {
+ setArg(key, defaultValue(key));
+ }
+ }
+ }
+ } else if (arg.match(/^-.\..+=/)) {
+ m = arg.match(/^-([^=]+)=([\s\S]*)$/);
+ if (m !== null && Array.isArray(m) && m.length >= 3) {
+ setArg(m[1], m[2]);
+ }
+ } else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
+ next = args[i + 1];
+ m = arg.match(/^-(.\..+)/);
+ if (m !== null && Array.isArray(m) && m.length >= 2) {
+ key = m[1];
+ if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
+ setArg(key, next);
+ i++;
+ } else {
+ setArg(key, defaultValue(key));
+ }
+ }
+ } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
+ letters = arg.slice(1, -1).split("");
+ broken = false;
+ for (let j = 0; j < letters.length; j++) {
+ next = arg.slice(j + 2);
+ if (letters[j + 1] && letters[j + 1] === "=") {
+ value = arg.slice(j + 3);
+ key = letters[j];
+ if (checkAllAliases(key, flags.arrays)) {
+ i = eatArray(i, key, args, value);
+ } else if (checkAllAliases(key, flags.nargs) !== false) {
+ i = eatNargs(i, key, args, value);
+ } else {
+ setArg(key, value);
+ }
+ broken = true;
+ break;
+ }
+ if (next === "-") {
+ setArg(letters[j], next);
+ continue;
+ }
+ if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) {
+ setArg(letters[j], next);
+ broken = true;
+ break;
+ }
+ if (letters[j + 1] && letters[j + 1].match(/\W/)) {
+ setArg(letters[j], next);
+ broken = true;
+ break;
+ } else {
+ setArg(letters[j], defaultValue(letters[j]));
+ }
+ }
+ key = arg.slice(-1)[0];
+ if (!broken && key !== "-") {
+ if (checkAllAliases(key, flags.arrays)) {
+ i = eatArray(i, key, args);
+ } else if (checkAllAliases(key, flags.nargs) !== false) {
+ i = eatNargs(i, key, args);
+ } else {
+ next = args[i + 1];
+ if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
+ setArg(key, next);
+ i++;
+ } else if (/^(true|false)$/.test(next)) {
+ setArg(key, next);
+ i++;
+ } else {
+ setArg(key, defaultValue(key));
+ }
+ }
+ }
+ } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) {
+ key = arg.slice(1);
+ setArg(key, defaultValue(key));
+ } else if (arg === "--") {
+ notFlags = args.slice(i + 1);
+ break;
+ } else if (configuration["halt-at-non-option"]) {
+ notFlags = args.slice(i);
+ break;
+ } else {
+ pushPositional(arg);
+ }
+ }
+ applyEnvVars(argv, true);
+ applyEnvVars(argv, false);
+ setConfig(argv);
+ setConfigObjects();
+ applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
+ applyCoercions(argv);
+ if (configuration["set-placeholder-key"])
+ setPlaceholderKeys(argv);
+ Object.keys(flags.counts).forEach(function(key) {
+ if (!hasKey2(argv, key.split(".")))
+ setArg(key, 0);
+ });
+ if (notFlagsOption && notFlags.length)
+ argv[notFlagsArgv] = [];
+ notFlags.forEach(function(key) {
+ argv[notFlagsArgv].push(key);
+ });
+ if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) {
+ Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => {
+ delete argv[key];
+ });
+ }
+ if (configuration["strip-aliased"]) {
+ ;
+ [].concat(...Object.keys(aliases2).map((k) => aliases2[k])).forEach((alias) => {
+ if (configuration["camel-case-expansion"] && alias.includes("-")) {
+ delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")];
+ }
+ delete argv[alias];
+ });
+ }
+ function pushPositional(arg) {
+ const maybeCoercedNumber = maybeCoerceNumber("_", arg);
+ if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") {
+ argv._.push(maybeCoercedNumber);
+ }
+ }
+ __name(pushPositional, "pushPositional");
+ function eatNargs(i, key, args2, argAfterEqualSign) {
+ let ii;
+ let toEat = checkAllAliases(key, flags.nargs);
+ toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
+ if (toEat === 0) {
+ if (!isUndefined(argAfterEqualSign)) {
+ error = Error(__("Argument unexpected for: %s", key));
+ }
+ setArg(key, defaultValue(key));
+ return i;
+ }
+ let available = isUndefined(argAfterEqualSign) ? 0 : 1;
+ if (configuration["nargs-eats-options"]) {
+ if (args2.length - (i + 1) + available < toEat) {
+ error = Error(__("Not enough arguments following: %s", key));
+ }
+ available = toEat;
+ } else {
+ for (ii = i + 1; ii < args2.length; ii++) {
+ if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii]))
+ available++;
+ else
+ break;
+ }
+ if (available < toEat)
+ error = Error(__("Not enough arguments following: %s", key));
+ }
+ let consumed = Math.min(available, toEat);
+ if (!isUndefined(argAfterEqualSign) && consumed > 0) {
+ setArg(key, argAfterEqualSign);
+ consumed--;
+ }
+ for (ii = i + 1; ii < consumed + i + 1; ii++) {
+ setArg(key, args2[ii]);
+ }
+ return i + consumed;
+ }
+ __name(eatNargs, "eatNargs");
+ function eatArray(i, key, args2, argAfterEqualSign) {
+ let argsToSet = [];
+ let next = argAfterEqualSign || args2[i + 1];
+ const nargsCount = checkAllAliases(key, flags.nargs);
+ if (checkAllAliases(key, flags.bools) && !/^(true|false)$/.test(next)) {
+ argsToSet.push(true);
+ } else if (isUndefined(next) || isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
+ if (defaults[key] !== void 0) {
+ const defVal = defaults[key];
+ argsToSet = Array.isArray(defVal) ? defVal : [defVal];
+ }
+ } else {
+ if (!isUndefined(argAfterEqualSign)) {
+ argsToSet.push(processValue(key, argAfterEqualSign, true));
+ }
+ for (let ii = i + 1; ii < args2.length; ii++) {
+ if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
+ break;
+ next = args2[ii];
+ if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
+ break;
+ i = ii;
+ argsToSet.push(processValue(key, next, inputIsString));
+ }
+ }
+ if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
+ error = Error(__("Not enough arguments following: %s", key));
+ }
+ setArg(key, argsToSet);
+ return i;
+ }
+ __name(eatArray, "eatArray");
+ function setArg(key, val, shouldStripQuotes = inputIsString) {
+ if (/-/.test(key) && configuration["camel-case-expansion"]) {
+ const alias = key.split(".").map(function(prop) {
+ return camelCase(prop);
+ }).join(".");
+ addNewAlias(key, alias);
+ }
+ const value = processValue(key, val, shouldStripQuotes);
+ const splitKey = key.split(".");
+ setKey(argv, splitKey, value);
+ if (flags.aliases[key]) {
+ flags.aliases[key].forEach(function(x) {
+ const keyProperties = x.split(".");
+ setKey(argv, keyProperties, value);
+ });
+ }
+ if (splitKey.length > 1 && configuration["dot-notation"]) {
+ ;
+ (flags.aliases[splitKey[0]] || []).forEach(function(x) {
+ let keyProperties = x.split(".");
+ const a = [].concat(splitKey);
+ a.shift();
+ keyProperties = keyProperties.concat(a);
+ if (!(flags.aliases[key] || []).includes(keyProperties.join("."))) {
+ setKey(argv, keyProperties, value);
+ }
+ });
+ }
+ if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
+ const keys = [key].concat(flags.aliases[key] || []);
+ keys.forEach(function(key2) {
+ Object.defineProperty(argvReturn, key2, {
+ enumerable: true,
+ get() {
+ return val;
+ },
+ set(value2) {
+ val = typeof value2 === "string" ? mixin.normalize(value2) : value2;
+ }
+ });
+ });
+ }
+ }
+ __name(setArg, "setArg");
+ function addNewAlias(key, alias) {
+ if (!(flags.aliases[key] && flags.aliases[key].length)) {
+ flags.aliases[key] = [alias];
+ newAliases[alias] = true;
+ }
+ if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
+ addNewAlias(alias, key);
+ }
+ }
+ __name(addNewAlias, "addNewAlias");
+ function processValue(key, val, shouldStripQuotes) {
+ if (shouldStripQuotes) {
+ val = stripQuotes(val);
+ }
+ if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
+ if (typeof val === "string")
+ val = val === "true";
+ }
+ let value = Array.isArray(val) ? val.map(function(v) {
+ return maybeCoerceNumber(key, v);
+ }) : maybeCoerceNumber(key, val);
+ if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === "boolean")) {
+ value = increment();
+ }
+ if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
+ if (Array.isArray(val))
+ value = val.map((val2) => {
+ return mixin.normalize(val2);
+ });
+ else
+ value = mixin.normalize(val);
+ }
+ return value;
+ }
+ __name(processValue, "processValue");
+ function maybeCoerceNumber(key, value) {
+ if (!configuration["parse-positional-numbers"] && key === "_")
+ return value;
+ if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
+ const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
+ if (shouldCoerceNumber || !isUndefined(value) && checkAllAliases(key, flags.numbers)) {
+ value = Number(value);
+ }
+ }
+ return value;
+ }
+ __name(maybeCoerceNumber, "maybeCoerceNumber");
+ function setConfig(argv2) {
+ const configLookup = /* @__PURE__ */ Object.create(null);
+ applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
+ Object.keys(flags.configs).forEach(function(configKey) {
+ const configPath = argv2[configKey] || configLookup[configKey];
+ if (configPath) {
+ try {
+ let config = null;
+ const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath);
+ const resolveConfig = flags.configs[configKey];
+ if (typeof resolveConfig === "function") {
+ try {
+ config = resolveConfig(resolvedConfigPath);
+ } catch (e2) {
+ config = e2;
+ }
+ if (config instanceof Error) {
+ error = config;
+ return;
+ }
+ } else {
+ config = mixin.require(resolvedConfigPath);
+ }
+ setConfigObject(config);
+ } catch (ex) {
+ if (ex.name === "PermissionDenied")
+ error = ex;
+ else if (argv2[configKey])
+ error = Error(__("Invalid JSON config file: %s", configPath));
+ }
+ }
+ });
+ }
+ __name(setConfig, "setConfig");
+ function setConfigObject(config, prev) {
+ Object.keys(config).forEach(function(key) {
+ const value = config[key];
+ const fullKey = prev ? prev + "." + key : key;
+ if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) {
+ setConfigObject(value, fullKey);
+ } else {
+ if (!hasKey2(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags.arrays) && configuration["combine-arrays"]) {
+ setArg(fullKey, value);
+ }
+ }
+ });
+ }
+ __name(setConfigObject, "setConfigObject");
+ function setConfigObjects() {
+ if (typeof configObjects !== "undefined") {
+ configObjects.forEach(function(configObject) {
+ setConfigObject(configObject);
+ });
+ }
+ }
+ __name(setConfigObjects, "setConfigObjects");
+ function applyEnvVars(argv2, configOnly) {
+ if (typeof envPrefix === "undefined")
+ return;
+ const prefix = typeof envPrefix === "string" ? envPrefix : "";
+ const env5 = mixin.env();
+ Object.keys(env5).forEach(function(envVar) {
+ if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
+ const keys = envVar.split("__").map(function(key, i) {
+ if (i === 0) {
+ key = key.substring(prefix.length);
+ }
+ return camelCase(key);
+ });
+ if ((configOnly && flags.configs[keys.join(".")] || !configOnly) && !hasKey2(argv2, keys)) {
+ setArg(keys.join("."), env5[envVar]);
+ }
+ }
+ });
+ }
+ __name(applyEnvVars, "applyEnvVars");
+ function applyCoercions(argv2) {
+ let coerce;
+ const applied = /* @__PURE__ */ new Set();
+ Object.keys(argv2).forEach(function(key) {
+ if (!applied.has(key)) {
+ coerce = checkAllAliases(key, flags.coercions);
+ if (typeof coerce === "function") {
+ try {
+ const value = maybeCoerceNumber(key, coerce(argv2[key]));
+ [].concat(flags.aliases[key] || [], key).forEach((ali) => {
+ applied.add(ali);
+ argv2[ali] = value;
+ });
+ } catch (err) {
+ error = err;
+ }
+ }
+ }
+ });
+ }
+ __name(applyCoercions, "applyCoercions");
+ function setPlaceholderKeys(argv2) {
+ flags.keys.forEach((key) => {
+ if (~key.indexOf("."))
+ return;
+ if (typeof argv2[key] === "undefined")
+ argv2[key] = void 0;
+ });
+ return argv2;
+ }
+ __name(setPlaceholderKeys, "setPlaceholderKeys");
+ function applyDefaultsAndAliases(obj, aliases3, defaults2, canLog = false) {
+ Object.keys(defaults2).forEach(function(key) {
+ if (!hasKey2(obj, key.split("."))) {
+ setKey(obj, key.split("."), defaults2[key]);
+ if (canLog)
+ defaulted[key] = true;
+ (aliases3[key] || []).forEach(function(x) {
+ if (hasKey2(obj, x.split(".")))
+ return;
+ setKey(obj, x.split("."), defaults2[key]);
+ });
+ }
+ });
+ }
+ __name(applyDefaultsAndAliases, "applyDefaultsAndAliases");
+ function hasKey2(obj, keys) {
+ let o = obj;
+ if (!configuration["dot-notation"])
+ keys = [keys.join(".")];
+ keys.slice(0, -1).forEach(function(key2) {
+ o = o[key2] || {};
+ });
+ const key = keys[keys.length - 1];
+ if (typeof o !== "object")
+ return false;
+ else
+ return key in o;
+ }
+ __name(hasKey2, "hasKey");
+ function setKey(obj, keys, value) {
+ let o = obj;
+ if (!configuration["dot-notation"])
+ keys = [keys.join(".")];
+ keys.slice(0, -1).forEach(function(key2) {
+ key2 = sanitizeKey(key2);
+ if (typeof o === "object" && o[key2] === void 0) {
+ o[key2] = {};
+ }
+ if (typeof o[key2] !== "object" || Array.isArray(o[key2])) {
+ if (Array.isArray(o[key2])) {
+ o[key2].push({});
+ } else {
+ o[key2] = [o[key2], {}];
+ }
+ o = o[key2][o[key2].length - 1];
+ } else {
+ o = o[key2];
+ }
+ });
+ const key = sanitizeKey(keys[keys.length - 1]);
+ const isTypeArray = checkAllAliases(keys.join("."), flags.arrays);
+ const isValueArray = Array.isArray(value);
+ let duplicate = configuration["duplicate-arguments-array"];
+ if (!duplicate && checkAllAliases(key, flags.nargs)) {
+ duplicate = true;
+ if (!isUndefined(o[key]) && flags.nargs[key] === 1 || Array.isArray(o[key]) && o[key].length === flags.nargs[key]) {
+ o[key] = void 0;
+ }
+ }
+ if (value === increment()) {
+ o[key] = increment(o[key]);
+ } else if (Array.isArray(o[key])) {
+ if (duplicate && isTypeArray && isValueArray) {
+ o[key] = configuration["flatten-duplicate-arrays"] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
+ } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
+ o[key] = value;
+ } else {
+ o[key] = o[key].concat([value]);
+ }
+ } else if (o[key] === void 0 && isTypeArray) {
+ o[key] = isValueArray ? value : [value];
+ } else if (duplicate && !(o[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) {
+ o[key] = [o[key], value];
+ } else {
+ o[key] = value;
+ }
+ }
+ __name(setKey, "setKey");
+ function extendAliases(...args2) {
+ args2.forEach(function(obj) {
+ Object.keys(obj || {}).forEach(function(key) {
+ if (flags.aliases[key])
+ return;
+ flags.aliases[key] = [].concat(aliases2[key] || []);
+ flags.aliases[key].concat(key).forEach(function(x) {
+ if (/-/.test(x) && configuration["camel-case-expansion"]) {
+ const c = camelCase(x);
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
+ flags.aliases[key].push(c);
+ newAliases[c] = true;
+ }
+ }
+ });
+ flags.aliases[key].concat(key).forEach(function(x) {
+ if (x.length > 1 && /[A-Z]/.test(x) && configuration["camel-case-expansion"]) {
+ const c = decamelize(x, "-");
+ if (c !== key && flags.aliases[key].indexOf(c) === -1) {
+ flags.aliases[key].push(c);
+ newAliases[c] = true;
+ }
+ }
+ });
+ flags.aliases[key].forEach(function(x) {
+ flags.aliases[x] = [key].concat(flags.aliases[key].filter(function(y) {
+ return x !== y;
+ }));
+ });
+ });
+ });
+ }
+ __name(extendAliases, "extendAliases");
+ function checkAllAliases(key, flag) {
+ const toCheck = [].concat(flags.aliases[key] || [], key);
+ const keys = Object.keys(flag);
+ const setAlias = toCheck.find((key2) => keys.includes(key2));
+ return setAlias ? flag[setAlias] : false;
+ }
+ __name(checkAllAliases, "checkAllAliases");
+ function hasAnyFlag(key) {
+ const flagsKeys = Object.keys(flags);
+ const toCheck = [].concat(flagsKeys.map((k) => flags[k]));
+ return toCheck.some(function(flag) {
+ return Array.isArray(flag) ? flag.includes(key) : flag[key];
+ });
+ }
+ __name(hasAnyFlag, "hasAnyFlag");
+ function hasFlagsMatching(arg, ...patterns) {
+ const toCheck = [].concat(...patterns);
+ return toCheck.some(function(pattern) {
+ const match = arg.match(pattern);
+ return match && hasAnyFlag(match[1]);
+ });
+ }
+ __name(hasFlagsMatching, "hasFlagsMatching");
+ function hasAllShortFlags(arg) {
+ if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
+ return false;
+ }
+ let hasAllFlags = true;
+ let next;
+ const letters = arg.slice(1).split("");
+ for (let j = 0; j < letters.length; j++) {
+ next = arg.slice(j + 2);
+ if (!hasAnyFlag(letters[j])) {
+ hasAllFlags = false;
+ break;
+ }
+ if (letters[j + 1] && letters[j + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j + 1] && letters[j + 1].match(/\W/)) {
+ break;
+ }
+ }
+ return hasAllFlags;
+ }
+ __name(hasAllShortFlags, "hasAllShortFlags");
+ function isUnknownOptionAsArg(arg) {
+ return configuration["unknown-options-as-args"] && isUnknownOption(arg);
+ }
+ __name(isUnknownOptionAsArg, "isUnknownOptionAsArg");
+ function isUnknownOption(arg) {
+ arg = arg.replace(/^-{3,}/, "--");
+ if (arg.match(negative)) {
+ return false;
+ }
+ if (hasAllShortFlags(arg)) {
+ return false;
+ }
+ const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
+ const normalFlag = /^-+([^=]+?)$/;
+ const flagEndingInHyphen = /^-+([^=]+?)-$/;
+ const flagEndingInDigits = /^-+([^=]+?\d+)$/;
+ const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
+ return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
+ }
+ __name(isUnknownOption, "isUnknownOption");
+ function defaultValue(key) {
+ if (!checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts) && `${key}` in defaults) {
+ return defaults[key];
+ } else {
+ return defaultForType(guessType2(key));
+ }
+ }
+ __name(defaultValue, "defaultValue");
+ function defaultForType(type) {
+ const def = {
+ [DefaultValuesForTypeKey.BOOLEAN]: true,
+ [DefaultValuesForTypeKey.STRING]: "",
+ [DefaultValuesForTypeKey.NUMBER]: void 0,
+ [DefaultValuesForTypeKey.ARRAY]: []
+ };
+ return def[type];
+ }
+ __name(defaultForType, "defaultForType");
+ function guessType2(key) {
+ let type = DefaultValuesForTypeKey.BOOLEAN;
+ if (checkAllAliases(key, flags.strings))
+ type = DefaultValuesForTypeKey.STRING;
+ else if (checkAllAliases(key, flags.numbers))
+ type = DefaultValuesForTypeKey.NUMBER;
+ else if (checkAllAliases(key, flags.bools))
+ type = DefaultValuesForTypeKey.BOOLEAN;
+ else if (checkAllAliases(key, flags.arrays))
+ type = DefaultValuesForTypeKey.ARRAY;
+ return type;
+ }
+ __name(guessType2, "guessType");
+ function isUndefined(num) {
+ return num === void 0;
+ }
+ __name(isUndefined, "isUndefined");
+ function checkConfiguration() {
+ Object.keys(flags.counts).find((key) => {
+ if (checkAllAliases(key, flags.arrays)) {
+ error = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
+ return true;
+ } else if (checkAllAliases(key, flags.nargs)) {
+ error = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
+ return true;
+ }
+ return false;
+ });
+ }
+ __name(checkConfiguration, "checkConfiguration");
+ return {
+ aliases: Object.assign({}, flags.aliases),
+ argv: Object.assign(argvReturn, argv),
+ configuration,
+ defaulted: Object.assign({}, defaulted),
+ error,
+ newAliases: Object.assign({}, newAliases)
+ };
+ }
+};
+__name(YargsParser, "YargsParser");
+function combineAliases(aliases2) {
+ const aliasArrays = [];
+ const combined = /* @__PURE__ */ Object.create(null);
+ let change = true;
+ Object.keys(aliases2).forEach(function(key) {
+ aliasArrays.push([].concat(aliases2[key], key));
+ });
+ while (change) {
+ change = false;
+ for (let i = 0; i < aliasArrays.length; i++) {
+ for (let ii = i + 1; ii < aliasArrays.length; ii++) {
+ const intersect = aliasArrays[i].filter(function(v) {
+ return aliasArrays[ii].indexOf(v) !== -1;
+ });
+ if (intersect.length) {
+ aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
+ aliasArrays.splice(ii, 1);
+ change = true;
+ break;
+ }
+ }
+ }
+ }
+ aliasArrays.forEach(function(aliasArray) {
+ aliasArray = aliasArray.filter(function(v, i, self2) {
+ return self2.indexOf(v) === i;
+ });
+ const lastAlias = aliasArray.pop();
+ if (lastAlias !== void 0 && typeof lastAlias === "string") {
+ combined[lastAlias] = aliasArray;
+ }
+ });
+ return combined;
+}
+__name(combineAliases, "combineAliases");
+function increment(orig) {
+ return orig !== void 0 ? orig + 1 : 1;
+}
+__name(increment, "increment");
+function sanitizeKey(key) {
+ if (key === "__proto__")
+ return "___proto___";
+ return key;
+}
+__name(sanitizeKey, "sanitizeKey");
+function stripQuotes(val) {
+ return typeof val === "string" && (val[0] === "'" || val[0] === '"') && val[val.length - 1] === val[0] ? val.substring(1, val.length - 1) : val;
+}
+__name(stripQuotes, "stripQuotes");
+
+// ../../node_modules/.pnpm/yargs-parser@21.1.1/node_modules/yargs-parser/build/lib/index.js
+var import_fs = require("fs");
+var _a;
+var _b;
+var _c;
+var minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION ? Number(process.env.YARGS_MIN_NODE_VERSION) : 12;
+var nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
+if (nodeVersion) {
+ const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
+ if (major < minNodeVersion) {
+ throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
+ }
+}
+var env = process ? process.env : {};
+var parser = new YargsParser({
+ cwd: process.cwd,
+ env: () => {
+ return env;
+ },
+ format: import_util.format,
+ normalize: import_path.normalize,
+ resolve: import_path.resolve,
+ // TODO: figure out a way to combine ESM and CJS coverage, such that
+ // we can exercise all the lines below:
+ require: (path45) => {
+ if (typeof require !== "undefined") {
+ return require(path45);
+ } else if (path45.match(/\.json$/)) {
+ return JSON.parse((0, import_fs.readFileSync)(path45, "utf8"));
+ } else {
+ throw Error("only .json config files are supported in ESM");
+ }
+ }
+});
+var yargsParser = /* @__PURE__ */ __name(function Parser(args, opts) {
+ const result = parser.parse(args.slice(), opts);
+ return result.argv;
+}, "Parser");
+yargsParser.detailed = function(args, opts) {
+ return parser.parse(args.slice(), opts);
+};
+yargsParser.camelCase = camelCase;
+yargsParser.decamelize = decamelize;
+yargsParser.looksLikeNumber = looksLikeNumber;
+var lib_default = yargsParser;
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/lib/platform-shims/esm.mjs
+init_import_meta_url();
+var import_assert = require("assert");
+
+// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/index.mjs
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/index.js
+init_import_meta_url();
+var align = {
+ right: alignRight,
+ center: alignCenter
+};
+var top = 0;
+var right = 1;
+var bottom = 2;
+var left = 3;
+var UI = class {
+ constructor(opts) {
+ var _a2;
+ this.width = opts.width;
+ this.wrap = (_a2 = opts.wrap) !== null && _a2 !== void 0 ? _a2 : true;
+ this.rows = [];
+ }
+ span(...args) {
+ const cols = this.div(...args);
+ cols.span = true;
+ }
+ resetOutput() {
+ this.rows = [];
+ }
+ div(...args) {
+ if (args.length === 0) {
+ this.div("");
+ }
+ if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === "string") {
+ return this.applyLayoutDSL(args[0]);
+ }
+ const cols = args.map((arg) => {
+ if (typeof arg === "string") {
+ return this.colFromString(arg);
+ }
+ return arg;
+ });
+ this.rows.push(cols);
+ return cols;
+ }
+ shouldApplyLayoutDSL(...args) {
+ return args.length === 1 && typeof args[0] === "string" && /[\t\n]/.test(args[0]);
+ }
+ applyLayoutDSL(str) {
+ const rows = str.split("\n").map((row) => row.split(" "));
+ let leftColumnWidth = 0;
+ rows.forEach((columns) => {
+ if (columns.length > 1 && mixin2.stringWidth(columns[0]) > leftColumnWidth) {
+ leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin2.stringWidth(columns[0]));
+ }
+ });
+ rows.forEach((columns) => {
+ this.div(...columns.map((r, i) => {
+ return {
+ text: r.trim(),
+ padding: this.measurePadding(r),
+ width: i === 0 && columns.length > 1 ? leftColumnWidth : void 0
+ };
+ }));
+ });
+ return this.rows[this.rows.length - 1];
+ }
+ colFromString(text) {
+ return {
+ text,
+ padding: this.measurePadding(text)
+ };
+ }
+ measurePadding(str) {
+ const noAnsi = mixin2.stripAnsi(str);
+ return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
+ }
+ toString() {
+ const lines = [];
+ this.rows.forEach((row) => {
+ this.rowToString(row, lines);
+ });
+ return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n");
+ }
+ rowToString(row, lines) {
+ this.rasterize(row).forEach((rrow, r) => {
+ let str = "";
+ rrow.forEach((col, c) => {
+ const { width } = row[c];
+ const wrapWidth = this.negatePadding(row[c]);
+ let ts = col;
+ if (wrapWidth > mixin2.stringWidth(col)) {
+ ts += " ".repeat(wrapWidth - mixin2.stringWidth(col));
+ }
+ if (row[c].align && row[c].align !== "left" && this.wrap) {
+ const fn2 = align[row[c].align];
+ ts = fn2(ts, wrapWidth);
+ if (mixin2.stringWidth(ts) < wrapWidth) {
+ ts += " ".repeat((width || 0) - mixin2.stringWidth(ts) - 1);
+ }
+ }
+ const padding = row[c].padding || [0, 0, 0, 0];
+ if (padding[left]) {
+ str += " ".repeat(padding[left]);
+ }
+ str += addBorder(row[c], ts, "| ");
+ str += ts;
+ str += addBorder(row[c], ts, " |");
+ if (padding[right]) {
+ str += " ".repeat(padding[right]);
+ }
+ if (r === 0 && lines.length > 0) {
+ str = this.renderInline(str, lines[lines.length - 1]);
+ }
+ });
+ lines.push({
+ text: str.replace(/ +$/, ""),
+ span: row.span
+ });
+ });
+ return lines;
+ }
+ // if the full 'source' can render in
+ // the target line, do so.
+ renderInline(source, previousLine) {
+ const match = source.match(/^ */);
+ const leadingWhitespace = match ? match[0].length : 0;
+ const target = previousLine.text;
+ const targetTextWidth = mixin2.stringWidth(target.trimRight());
+ if (!previousLine.span) {
+ return source;
+ }
+ if (!this.wrap) {
+ previousLine.hidden = true;
+ return target + source;
+ }
+ if (leadingWhitespace < targetTextWidth) {
+ return source;
+ }
+ previousLine.hidden = true;
+ return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
+ }
+ rasterize(row) {
+ const rrows = [];
+ const widths = this.columnWidths(row);
+ let wrapped;
+ row.forEach((col, c) => {
+ col.width = widths[c];
+ if (this.wrap) {
+ wrapped = mixin2.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n");
+ } else {
+ wrapped = col.text.split("\n");
+ }
+ if (col.border) {
+ wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + ".");
+ wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'");
+ }
+ if (col.padding) {
+ wrapped.unshift(...new Array(col.padding[top] || 0).fill(""));
+ wrapped.push(...new Array(col.padding[bottom] || 0).fill(""));
+ }
+ wrapped.forEach((str, r) => {
+ if (!rrows[r]) {
+ rrows.push([]);
+ }
+ const rrow = rrows[r];
+ for (let i = 0; i < c; i++) {
+ if (rrow[i] === void 0) {
+ rrow.push("");
+ }
+ }
+ rrow.push(str);
+ });
+ });
+ return rrows;
+ }
+ negatePadding(col) {
+ let wrapWidth = col.width || 0;
+ if (col.padding) {
+ wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
+ }
+ if (col.border) {
+ wrapWidth -= 4;
+ }
+ return wrapWidth;
+ }
+ columnWidths(row) {
+ if (!this.wrap) {
+ return row.map((col) => {
+ return col.width || mixin2.stringWidth(col.text);
+ });
+ }
+ let unset = row.length;
+ let remainingWidth = this.width;
+ const widths = row.map((col) => {
+ if (col.width) {
+ unset--;
+ remainingWidth -= col.width;
+ return col.width;
+ }
+ return void 0;
+ });
+ const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
+ return widths.map((w, i) => {
+ if (w === void 0) {
+ return Math.max(unsetWidth, _minWidth(row[i]));
+ }
+ return w;
+ });
+ }
+};
+__name(UI, "UI");
+function addBorder(col, ts, style) {
+ if (col.border) {
+ if (/[.']-+[.']/.test(ts)) {
+ return "";
+ }
+ if (ts.trim().length !== 0) {
+ return style;
+ }
+ return " ";
+ }
+ return "";
+}
+__name(addBorder, "addBorder");
+function _minWidth(col) {
+ const padding = col.padding || [];
+ const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
+ if (col.border) {
+ return minWidth + 4;
+ }
+ return minWidth;
+}
+__name(_minWidth, "_minWidth");
+function getWindowWidth() {
+ if (typeof process === "object" && process.stdout && process.stdout.columns) {
+ return process.stdout.columns;
+ }
+ return 80;
+}
+__name(getWindowWidth, "getWindowWidth");
+function alignRight(str, width) {
+ str = str.trim();
+ const strWidth = mixin2.stringWidth(str);
+ if (strWidth < width) {
+ return " ".repeat(width - strWidth) + str;
+ }
+ return str;
+}
+__name(alignRight, "alignRight");
+function alignCenter(str, width) {
+ str = str.trim();
+ const strWidth = mixin2.stringWidth(str);
+ if (strWidth >= width) {
+ return str;
+ }
+ return " ".repeat(width - strWidth >> 1) + str;
+}
+__name(alignCenter, "alignCenter");
+var mixin2;
+function cliui(opts, _mixin) {
+ mixin2 = _mixin;
+ return new UI({
+ width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
+ wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
+ });
+}
+__name(cliui, "cliui");
+
+// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/build/lib/string-utils.js
+init_import_meta_url();
+var ansi = new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", "g");
+function stripAnsi(str) {
+ return str.replace(ansi, "");
+}
+__name(stripAnsi, "stripAnsi");
+function wrap(str, width) {
+ const [start, end] = str.match(ansi) || ["", ""];
+ str = stripAnsi(str);
+ let wrapped = "";
+ for (let i = 0; i < str.length; i++) {
+ if (i !== 0 && i % width === 0) {
+ wrapped += "\n";
+ }
+ wrapped += str.charAt(i);
+ }
+ if (start && end) {
+ wrapped = `${start}${wrapped}${end}`;
+ }
+ return wrapped;
+}
+__name(wrap, "wrap");
+
+// ../../node_modules/.pnpm/cliui@8.0.1/node_modules/cliui/index.mjs
+function ui(opts) {
+ return cliui(opts, {
+ stringWidth: (str) => {
+ return [...str].length;
+ },
+ stripAnsi,
+ wrap
+ });
+}
+__name(ui, "ui");
+
+// ../../node_modules/.pnpm/escalade@3.1.1/node_modules/escalade/sync/index.mjs
+init_import_meta_url();
+var import_path2 = require("path");
+var import_fs2 = require("fs");
+function sync_default(start, callback) {
+ let dir = (0, import_path2.resolve)(".", start);
+ let tmp5, stats = (0, import_fs2.statSync)(dir);
+ if (!stats.isDirectory()) {
+ dir = (0, import_path2.dirname)(dir);
+ }
+ while (true) {
+ tmp5 = callback(dir, (0, import_fs2.readdirSync)(dir));
+ if (tmp5)
+ return (0, import_path2.resolve)(dir, tmp5);
+ dir = (0, import_path2.dirname)(tmp5 = dir);
+ if (tmp5 === dir)
+ break;
+ }
+}
+__name(sync_default, "default");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/lib/platform-shims/esm.mjs
+var import_util3 = require("util");
+var import_fs4 = require("fs");
+var import_url = require("url");
+var import_path4 = require("path");
+
+// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/index.mjs
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/build/lib/platform-shims/node.js
+init_import_meta_url();
+var import_fs3 = require("fs");
+var import_util2 = require("util");
+var import_path3 = require("path");
+var node_default = {
+ fs: {
+ readFileSync: import_fs3.readFileSync,
+ writeFile: import_fs3.writeFile
+ },
+ format: import_util2.format,
+ resolve: import_path3.resolve,
+ exists: (file) => {
+ try {
+ return (0, import_fs3.statSync)(file).isFile();
+ } catch (err) {
+ return false;
+ }
+ }
+};
+
+// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/build/lib/index.js
+init_import_meta_url();
+var shim2;
+var Y18N = class {
+ constructor(opts) {
+ opts = opts || {};
+ this.directory = opts.directory || "./locales";
+ this.updateFiles = typeof opts.updateFiles === "boolean" ? opts.updateFiles : true;
+ this.locale = opts.locale || "en";
+ this.fallbackToLanguage = typeof opts.fallbackToLanguage === "boolean" ? opts.fallbackToLanguage : true;
+ this.cache = /* @__PURE__ */ Object.create(null);
+ this.writeQueue = [];
+ }
+ __(...args) {
+ if (typeof arguments[0] !== "string") {
+ return this._taggedLiteral(arguments[0], ...arguments);
+ }
+ const str = args.shift();
+ let cb = /* @__PURE__ */ __name(function() {
+ }, "cb");
+ if (typeof args[args.length - 1] === "function")
+ cb = args.pop();
+ cb = cb || function() {
+ };
+ if (!this.cache[this.locale])
+ this._readLocaleFile();
+ if (!this.cache[this.locale][str] && this.updateFiles) {
+ this.cache[this.locale][str] = str;
+ this._enqueueWrite({
+ directory: this.directory,
+ locale: this.locale,
+ cb
+ });
+ } else {
+ cb();
+ }
+ return shim2.format.apply(shim2.format, [this.cache[this.locale][str] || str].concat(args));
+ }
+ __n() {
+ const args = Array.prototype.slice.call(arguments);
+ const singular = args.shift();
+ const plural = args.shift();
+ const quantity = args.shift();
+ let cb = /* @__PURE__ */ __name(function() {
+ }, "cb");
+ if (typeof args[args.length - 1] === "function")
+ cb = args.pop();
+ if (!this.cache[this.locale])
+ this._readLocaleFile();
+ let str = quantity === 1 ? singular : plural;
+ if (this.cache[this.locale][singular]) {
+ const entry = this.cache[this.locale][singular];
+ str = entry[quantity === 1 ? "one" : "other"];
+ }
+ if (!this.cache[this.locale][singular] && this.updateFiles) {
+ this.cache[this.locale][singular] = {
+ one: singular,
+ other: plural
+ };
+ this._enqueueWrite({
+ directory: this.directory,
+ locale: this.locale,
+ cb
+ });
+ } else {
+ cb();
+ }
+ const values = [str];
+ if (~str.indexOf("%d"))
+ values.push(quantity);
+ return shim2.format.apply(shim2.format, values.concat(args));
+ }
+ setLocale(locale) {
+ this.locale = locale;
+ }
+ getLocale() {
+ return this.locale;
+ }
+ updateLocale(obj) {
+ if (!this.cache[this.locale])
+ this._readLocaleFile();
+ for (const key in obj) {
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
+ this.cache[this.locale][key] = obj[key];
+ }
+ }
+ }
+ _taggedLiteral(parts, ...args) {
+ let str = "";
+ parts.forEach(function(part, i) {
+ const arg = args[i + 1];
+ str += part;
+ if (typeof arg !== "undefined") {
+ str += "%s";
+ }
+ });
+ return this.__.apply(this, [str].concat([].slice.call(args, 1)));
+ }
+ _enqueueWrite(work) {
+ this.writeQueue.push(work);
+ if (this.writeQueue.length === 1)
+ this._processWriteQueue();
+ }
+ _processWriteQueue() {
+ const _this = this;
+ const work = this.writeQueue[0];
+ const directory = work.directory;
+ const locale = work.locale;
+ const cb = work.cb;
+ const languageFile = this._resolveLocaleFile(directory, locale);
+ const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
+ shim2.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
+ _this.writeQueue.shift();
+ if (_this.writeQueue.length > 0)
+ _this._processWriteQueue();
+ cb(err);
+ });
+ }
+ _readLocaleFile() {
+ let localeLookup = {};
+ const languageFile = this._resolveLocaleFile(this.directory, this.locale);
+ try {
+ if (shim2.fs.readFileSync) {
+ localeLookup = JSON.parse(shim2.fs.readFileSync(languageFile, "utf-8"));
+ }
+ } catch (err) {
+ if (err instanceof SyntaxError) {
+ err.message = "syntax error in " + languageFile;
+ }
+ if (err.code === "ENOENT")
+ localeLookup = {};
+ else
+ throw err;
+ }
+ this.cache[this.locale] = localeLookup;
+ }
+ _resolveLocaleFile(directory, locale) {
+ let file = shim2.resolve(directory, "./", locale + ".json");
+ if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf("_")) {
+ const languageFile = shim2.resolve(directory, "./", locale.split("_")[0] + ".json");
+ if (this._fileExistsSync(languageFile))
+ file = languageFile;
+ }
+ return file;
+ }
+ _fileExistsSync(file) {
+ return shim2.exists(file);
+ }
+};
+__name(Y18N, "Y18N");
+function y18n(opts, _shim) {
+ shim2 = _shim;
+ const y18n3 = new Y18N(opts);
+ return {
+ __: y18n3.__.bind(y18n3),
+ __n: y18n3.__n.bind(y18n3),
+ setLocale: y18n3.setLocale.bind(y18n3),
+ getLocale: y18n3.getLocale.bind(y18n3),
+ updateLocale: y18n3.updateLocale.bind(y18n3),
+ locale: y18n3.locale
+ };
+}
+__name(y18n, "y18n");
+
+// ../../node_modules/.pnpm/y18n@5.0.8/node_modules/y18n/index.mjs
+var y18n2 = /* @__PURE__ */ __name((opts) => {
+ return y18n(opts, node_default);
+}, "y18n");
+var y18n_default = y18n2;
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/lib/platform-shims/esm.mjs
+var REQUIRE_ERROR = "require is not supported by ESM";
+var REQUIRE_DIRECTORY_ERROR = "loading a directory of commands is not supported yet for ESM";
+var __dirname2;
+try {
+ __dirname2 = (0, import_url.fileURLToPath)(import_meta_url);
+} catch (e2) {
+ __dirname2 = process.cwd();
+}
+var mainFilename = __dirname2.substring(0, __dirname2.lastIndexOf("node_modules"));
+var esm_default = {
+ assert: {
+ notStrictEqual: import_assert.notStrictEqual,
+ strictEqual: import_assert.strictEqual
+ },
+ cliui: ui,
+ findUp: sync_default,
+ getEnv: (key) => {
+ return process.env[key];
+ },
+ inspect: import_util3.inspect,
+ getCallerFile: () => {
+ throw new YError(REQUIRE_DIRECTORY_ERROR);
+ },
+ getProcessArgvBin,
+ mainFilename: mainFilename || process.cwd(),
+ Parser: lib_default,
+ path: {
+ basename: import_path4.basename,
+ dirname: import_path4.dirname,
+ extname: import_path4.extname,
+ relative: import_path4.relative,
+ resolve: import_path4.resolve
+ },
+ process: {
+ argv: () => process.argv,
+ cwd: process.cwd,
+ emitWarning: (warning, type) => process.emitWarning(warning, type),
+ execPath: () => process.execPath,
+ exit: process.exit,
+ nextTick: process.nextTick,
+ stdColumns: typeof process.stdout.columns !== "undefined" ? process.stdout.columns : null
+ },
+ readFileSync: import_fs4.readFileSync,
+ require: () => {
+ throw new YError(REQUIRE_ERROR);
+ },
+ requireDirectory: () => {
+ throw new YError(REQUIRE_DIRECTORY_ERROR);
+ },
+ stringWidth: (str) => {
+ return [...str].length;
+ },
+ y18n: y18n_default({
+ directory: (0, import_path4.resolve)(__dirname2, "../../../locales"),
+ updateFiles: false
+ })
+};
+
+// src/api/index.ts
+init_import_meta_url();
+
+// src/api/dev.ts
+init_import_meta_url();
+var import_undici18 = __toESM(require_undici());
+
+// src/dev.tsx
+init_import_meta_url();
+var import_node_path46 = __toESM(require("node:path"));
+var import_env = __toESM(require_dist());
+var import_chalk16 = __toESM(require_chalk());
+var import_chokidar5 = require("chokidar");
+
+// ../../node_modules/.pnpm/get-port@6.1.2/node_modules/get-port/index.js
+init_import_meta_url();
+var import_node_net = __toESM(require("node:net"), 1);
+var import_node_os = __toESM(require("node:os"), 1);
+var Locked = class extends Error {
+ constructor(port2) {
+ super(`${port2} is locked`);
+ }
+};
+__name(Locked, "Locked");
+var lockedPorts = {
+ old: /* @__PURE__ */ new Set(),
+ young: /* @__PURE__ */ new Set()
+};
+var releaseOldLockedPortsIntervalMs = 1e3 * 15;
+var interval;
+var getLocalHosts = /* @__PURE__ */ __name(() => {
+ const interfaces = import_node_os.default.networkInterfaces();
+ const results = /* @__PURE__ */ new Set([void 0, "0.0.0.0"]);
+ for (const _interface of Object.values(interfaces)) {
+ for (const config of _interface) {
+ results.add(config.address);
+ }
+ }
+ return results;
+}, "getLocalHosts");
+var checkAvailablePort = /* @__PURE__ */ __name((options14) => new Promise((resolve18, reject) => {
+ const server2 = import_node_net.default.createServer();
+ server2.unref();
+ server2.on("error", reject);
+ server2.listen(options14, () => {
+ const { port: port2 } = server2.address();
+ server2.close(() => {
+ resolve18(port2);
+ });
+ });
+}), "checkAvailablePort");
+var getAvailablePort = /* @__PURE__ */ __name(async (options14, hosts) => {
+ if (options14.host || options14.port === 0) {
+ return checkAvailablePort(options14);
+ }
+ for (const host of hosts) {
+ try {
+ await checkAvailablePort({ port: options14.port, host });
+ } catch (error) {
+ if (!["EADDRNOTAVAIL", "EINVAL"].includes(error.code)) {
+ throw error;
+ }
+ }
+ }
+ return options14.port;
+}, "getAvailablePort");
+var portCheckSequence = /* @__PURE__ */ __name(function* (ports) {
+ if (ports) {
+ yield* ports;
+ }
+ yield 0;
+}, "portCheckSequence");
+async function getPorts(options14) {
+ let ports;
+ let exclude = /* @__PURE__ */ new Set();
+ if (options14) {
+ if (options14.port) {
+ ports = typeof options14.port === "number" ? [options14.port] : options14.port;
+ }
+ if (options14.exclude) {
+ const excludeIterable = options14.exclude;
+ if (typeof excludeIterable[Symbol.iterator] !== "function") {
+ throw new TypeError("The `exclude` option must be an iterable.");
+ }
+ for (const element of excludeIterable) {
+ if (typeof element !== "number") {
+ throw new TypeError("Each item in the `exclude` option must be a number corresponding to the port you want excluded.");
+ }
+ if (!Number.isSafeInteger(element)) {
+ throw new TypeError(`Number ${element} in the exclude option is not a safe integer and can't be used`);
+ }
+ }
+ exclude = new Set(excludeIterable);
+ }
+ }
+ if (interval === void 0) {
+ interval = setInterval(() => {
+ lockedPorts.old = lockedPorts.young;
+ lockedPorts.young = /* @__PURE__ */ new Set();
+ }, releaseOldLockedPortsIntervalMs);
+ if (interval.unref) {
+ interval.unref();
+ }
+ }
+ const hosts = getLocalHosts();
+ for (const port2 of portCheckSequence(ports)) {
+ try {
+ if (exclude.has(port2)) {
+ continue;
+ }
+ let availablePort = await getAvailablePort({ ...options14, port: port2 }, hosts);
+ while (lockedPorts.old.has(availablePort) || lockedPorts.young.has(availablePort)) {
+ if (port2 !== 0) {
+ throw new Locked(port2);
+ }
+ availablePort = await getAvailablePort({ ...options14, port: port2 }, hosts);
+ }
+ lockedPorts.young.add(availablePort);
+ return availablePort;
+ } catch (error) {
+ if (!["EADDRINUSE", "EACCES"].includes(error.code) && !(error instanceof Locked)) {
+ throw error;
+ }
+ }
+ }
+ throw new Error("No available ports found");
+}
+__name(getPorts, "getPorts");
+
+// src/dev.tsx
+var import_ink13 = __toESM(require_build2());
+var import_react20 = __toESM(require_react());
+
+// src/config/index.ts
+init_import_meta_url();
+var import_node_fs4 = __toESM(require("node:fs"));
+var import_dotenv = __toESM(require_main());
+
+// ../../node_modules/.pnpm/find-up@6.3.0/node_modules/find-up/index.js
+init_import_meta_url();
+var import_node_path2 = __toESM(require("node:path"), 1);
+var import_node_url2 = require("node:url");
+
+// ../../node_modules/.pnpm/locate-path@7.1.0/node_modules/locate-path/index.js
+init_import_meta_url();
+var import_node_process = __toESM(require("node:process"), 1);
+var import_node_path = __toESM(require("node:path"), 1);
+var import_node_fs = __toESM(require("node:fs"), 1);
+var import_node_url = require("node:url");
+
+// ../../node_modules/.pnpm/p-locate@6.0.0/node_modules/p-locate/index.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yocto-queue@1.0.0/node_modules/yocto-queue/index.js
+init_import_meta_url();
+var Node2 = class {
+ value;
+ next;
+ constructor(value) {
+ this.value = value;
+ }
+};
+__name(Node2, "Node");
+var Queue = class {
+ #head;
+ #tail;
+ #size;
+ constructor() {
+ this.clear();
+ }
+ enqueue(value) {
+ const node = new Node2(value);
+ if (this.#head) {
+ this.#tail.next = node;
+ this.#tail = node;
+ } else {
+ this.#head = node;
+ this.#tail = node;
+ }
+ this.#size++;
+ }
+ dequeue() {
+ const current = this.#head;
+ if (!current) {
+ return;
+ }
+ this.#head = this.#head.next;
+ this.#size--;
+ return current.value;
+ }
+ clear() {
+ this.#head = void 0;
+ this.#tail = void 0;
+ this.#size = 0;
+ }
+ get size() {
+ return this.#size;
+ }
+ *[Symbol.iterator]() {
+ let current = this.#head;
+ while (current) {
+ yield current.value;
+ current = current.next;
+ }
+ }
+};
+__name(Queue, "Queue");
+
+// ../../node_modules/.pnpm/p-limit@4.0.0/node_modules/p-limit/index.js
+function pLimit(concurrency) {
+ if (!((Number.isInteger(concurrency) || concurrency === Number.POSITIVE_INFINITY) && concurrency > 0)) {
+ throw new TypeError("Expected `concurrency` to be a number from 1 and up");
+ }
+ const queue = new Queue();
+ let activeCount = 0;
+ const next = /* @__PURE__ */ __name(() => {
+ activeCount--;
+ if (queue.size > 0) {
+ queue.dequeue()();
+ }
+ }, "next");
+ const run = /* @__PURE__ */ __name(async (fn2, resolve18, args) => {
+ activeCount++;
+ const result = (async () => fn2(...args))();
+ resolve18(result);
+ try {
+ await result;
+ } catch {
+ }
+ next();
+ }, "run");
+ const enqueue = /* @__PURE__ */ __name((fn2, resolve18, args) => {
+ queue.enqueue(run.bind(void 0, fn2, resolve18, args));
+ (async () => {
+ await Promise.resolve();
+ if (activeCount < concurrency && queue.size > 0) {
+ queue.dequeue()();
+ }
+ })();
+ }, "enqueue");
+ const generator = /* @__PURE__ */ __name((fn2, ...args) => new Promise((resolve18) => {
+ enqueue(fn2, resolve18, args);
+ }), "generator");
+ Object.defineProperties(generator, {
+ activeCount: {
+ get: () => activeCount
+ },
+ pendingCount: {
+ get: () => queue.size
+ },
+ clearQueue: {
+ value: () => {
+ queue.clear();
+ }
+ }
+ });
+ return generator;
+}
+__name(pLimit, "pLimit");
+
+// ../../node_modules/.pnpm/p-locate@6.0.0/node_modules/p-locate/index.js
+var EndError = class extends Error {
+ constructor(value) {
+ super();
+ this.value = value;
+ }
+};
+__name(EndError, "EndError");
+var testElement = /* @__PURE__ */ __name(async (element, tester) => tester(await element), "testElement");
+var finder = /* @__PURE__ */ __name(async (element) => {
+ const values = await Promise.all(element);
+ if (values[1] === true) {
+ throw new EndError(values[0]);
+ }
+ return false;
+}, "finder");
+async function pLocate(iterable, tester, {
+ concurrency = Number.POSITIVE_INFINITY,
+ preserveOrder = true
+} = {}) {
+ const limit = pLimit(concurrency);
+ const items = [...iterable].map((element) => [element, limit(testElement, element, tester)]);
+ const checkLimit = pLimit(preserveOrder ? 1 : Number.POSITIVE_INFINITY);
+ try {
+ await Promise.all(items.map((element) => checkLimit(finder, element)));
+ } catch (error) {
+ if (error instanceof EndError) {
+ return error.value;
+ }
+ throw error;
+ }
+}
+__name(pLocate, "pLocate");
+
+// ../../node_modules/.pnpm/locate-path@7.1.0/node_modules/locate-path/index.js
+var typeMappings = {
+ directory: "isDirectory",
+ file: "isFile"
+};
+function checkType(type) {
+ if (type in typeMappings) {
+ return;
+ }
+ throw new Error(`Invalid type specified: ${type}`);
+}
+__name(checkType, "checkType");
+var matchType = /* @__PURE__ */ __name((type, stat3) => type === void 0 || stat3[typeMappings[type]](), "matchType");
+var toPath = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? (0, import_node_url.fileURLToPath)(urlOrPath) : urlOrPath, "toPath");
+async function locatePath(paths, {
+ cwd: cwd2 = import_node_process.default.cwd(),
+ type = "file",
+ allowSymlinks = true,
+ concurrency,
+ preserveOrder
+} = {}) {
+ checkType(type);
+ cwd2 = toPath(cwd2);
+ const statFunction = allowSymlinks ? import_node_fs.promises.stat : import_node_fs.promises.lstat;
+ return pLocate(paths, async (path_) => {
+ try {
+ const stat3 = await statFunction(import_node_path.default.resolve(cwd2, path_));
+ return matchType(type, stat3);
+ } catch {
+ return false;
+ }
+ }, { concurrency, preserveOrder });
+}
+__name(locatePath, "locatePath");
+function locatePathSync(paths, {
+ cwd: cwd2 = import_node_process.default.cwd(),
+ type = "file",
+ allowSymlinks = true
+} = {}) {
+ checkType(type);
+ cwd2 = toPath(cwd2);
+ const statFunction = allowSymlinks ? import_node_fs.default.statSync : import_node_fs.default.lstatSync;
+ for (const path_ of paths) {
+ try {
+ const stat3 = statFunction(import_node_path.default.resolve(cwd2, path_));
+ if (matchType(type, stat3)) {
+ return path_;
+ }
+ } catch {
+ }
+ }
+}
+__name(locatePathSync, "locatePathSync");
+
+// ../../node_modules/.pnpm/path-exists@5.0.0/node_modules/path-exists/index.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/find-up@6.3.0/node_modules/find-up/index.js
+var toPath2 = /* @__PURE__ */ __name((urlOrPath) => urlOrPath instanceof URL ? (0, import_node_url2.fileURLToPath)(urlOrPath) : urlOrPath, "toPath");
+var findUpStop = Symbol("findUpStop");
+async function findUpMultiple(name, options14 = {}) {
+ let directory = import_node_path2.default.resolve(toPath2(options14.cwd) || "");
+ const { root } = import_node_path2.default.parse(directory);
+ const stopAt = import_node_path2.default.resolve(directory, options14.stopAt || root);
+ const limit = options14.limit || Number.POSITIVE_INFINITY;
+ const paths = [name].flat();
+ const runMatcher = /* @__PURE__ */ __name(async (locateOptions) => {
+ if (typeof name !== "function") {
+ return locatePath(paths, locateOptions);
+ }
+ const foundPath = await name(locateOptions.cwd);
+ if (typeof foundPath === "string") {
+ return locatePath([foundPath], locateOptions);
+ }
+ return foundPath;
+ }, "runMatcher");
+ const matches = [];
+ while (true) {
+ const foundPath = await runMatcher({ ...options14, cwd: directory });
+ if (foundPath === findUpStop) {
+ break;
+ }
+ if (foundPath) {
+ matches.push(import_node_path2.default.resolve(directory, foundPath));
+ }
+ if (directory === stopAt || matches.length >= limit) {
+ break;
+ }
+ directory = import_node_path2.default.dirname(directory);
+ }
+ return matches;
+}
+__name(findUpMultiple, "findUpMultiple");
+function findUpMultipleSync(name, options14 = {}) {
+ let directory = import_node_path2.default.resolve(toPath2(options14.cwd) || "");
+ const { root } = import_node_path2.default.parse(directory);
+ const stopAt = options14.stopAt || root;
+ const limit = options14.limit || Number.POSITIVE_INFINITY;
+ const paths = [name].flat();
+ const runMatcher = /* @__PURE__ */ __name((locateOptions) => {
+ if (typeof name !== "function") {
+ return locatePathSync(paths, locateOptions);
+ }
+ const foundPath = name(locateOptions.cwd);
+ if (typeof foundPath === "string") {
+ return locatePathSync([foundPath], locateOptions);
+ }
+ return foundPath;
+ }, "runMatcher");
+ const matches = [];
+ while (true) {
+ const foundPath = runMatcher({ ...options14, cwd: directory });
+ if (foundPath === findUpStop) {
+ break;
+ }
+ if (foundPath) {
+ matches.push(import_node_path2.default.resolve(directory, foundPath));
+ }
+ if (directory === stopAt || matches.length >= limit) {
+ break;
+ }
+ directory = import_node_path2.default.dirname(directory);
+ }
+ return matches;
+}
+__name(findUpMultipleSync, "findUpMultipleSync");
+async function findUp(name, options14 = {}) {
+ const matches = await findUpMultiple(name, { ...options14, limit: 1 });
+ return matches[0];
+}
+__name(findUp, "findUp");
+function findUpSync(name, options14 = {}) {
+ const matches = findUpMultipleSync(name, { ...options14, limit: 1 });
+ return matches[0];
+}
+__name(findUpSync, "findUpSync");
+
+// src/logger.ts
+init_import_meta_url();
+var import_node_util = require("node:util");
+var import_chalk = __toESM(require_chalk());
+var import_cli_table3 = __toESM(require_cli_table3());
+var import_esbuild = require("esbuild");
+
+// src/environment-variables/factory.ts
+init_import_meta_url();
+function getEnvironmentVariableFactory({
+ variableName,
+ deprecatedName,
+ defaultValue
+}) {
+ let hasWarned = false;
+ return () => {
+ if (process.env[variableName]) {
+ return process.env[variableName];
+ } else if (deprecatedName && process.env[deprecatedName]) {
+ if (!hasWarned) {
+ hasWarned = true;
+ logger.warn(
+ `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
+ );
+ }
+ return process.env[deprecatedName];
+ } else {
+ return defaultValue?.();
+ }
+ };
+}
+__name(getEnvironmentVariableFactory, "getEnvironmentVariableFactory");
+
+// src/logger.ts
+var LOGGER_LEVELS = {
+ none: -1,
+ error: 0,
+ warn: 1,
+ info: 2,
+ log: 3,
+ debug: 4
+};
+var LOGGER_LEVEL_FORMAT_TYPE_MAP = {
+ error: "error",
+ warn: "warning",
+ info: void 0,
+ log: void 0,
+ debug: void 0
+};
+var getLogLevelFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_LOG"
+});
+function getLoggerLevel() {
+ const fromEnv = getLogLevelFromEnv()?.toLowerCase();
+ if (fromEnv !== void 0) {
+ if (fromEnv in LOGGER_LEVELS)
+ return fromEnv;
+ const expected = Object.keys(LOGGER_LEVELS).map((level) => `"${level}"`).join(" | ");
+ console.warn(
+ `Unrecognised WRANGLER_LOG value ${JSON.stringify(
+ fromEnv
+ )}, expected ${expected}, defaulting to "log"...`
+ );
+ }
+ return "log";
+}
+__name(getLoggerLevel, "getLoggerLevel");
+var Logger = class {
+ constructor() {
+ }
+ loggerLevel = getLoggerLevel();
+ columns = process.stdout.columns;
+ debug = (...args) => this.doLog("debug", args);
+ info = (...args) => this.doLog("info", args);
+ log = (...args) => this.doLog("log", args);
+ warn = (...args) => this.doLog("warn", args);
+ error = (...args) => this.doLog("error", args);
+ table(data) {
+ const keys = data.length === 0 ? [] : Object.keys(data[0]);
+ const t2 = new import_cli_table3.default({
+ head: keys,
+ style: {
+ head: import_chalk.default.level ? ["blue"] : [],
+ border: import_chalk.default.level ? ["gray"] : []
+ }
+ });
+ t2.push(...data.map((row) => keys.map((k) => row[k])));
+ return this.doLog("log", [t2.toString()]);
+ }
+ doLog(messageLevel, args) {
+ if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
+ console[messageLevel](this.formatMessage(messageLevel, (0, import_node_util.format)(...args)));
+ }
+ }
+ formatMessage(level, message) {
+ const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
+ if (kind) {
+ const [firstLine, ...otherLines] = message.split("\n");
+ const notes = otherLines.length > 0 ? otherLines.map((text) => ({ text })) : void 0;
+ return (0, import_esbuild.formatMessagesSync)([{ text: firstLine, notes }], {
+ color: true,
+ kind,
+ terminalWidth: this.columns
+ })[0];
+ } else {
+ return message;
+ }
+ }
+};
+__name(Logger, "Logger");
+var logger = new Logger();
+function logBuildWarnings(warnings) {
+ const logs = (0, import_esbuild.formatMessagesSync)(warnings, { kind: "warning", color: true });
+ for (const log of logs)
+ console.warn(log);
+}
+__name(logBuildWarnings, "logBuildWarnings");
+function logBuildFailure(errors, warnings) {
+ const logs = (0, import_esbuild.formatMessagesSync)(errors, { kind: "error", color: true });
+ for (const log of logs)
+ console.error(log);
+ logBuildWarnings(warnings);
+}
+__name(logBuildFailure, "logBuildFailure");
+
+// src/parse.ts
+init_import_meta_url();
+var fs2 = __toESM(require("node:fs"));
+var import_node_path3 = require("node:path");
+var import_toml = __toESM(require_toml());
+var import_esbuild2 = require("esbuild");
+
+// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/main.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/format.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/scanner.js
+init_import_meta_url();
+function createScanner(text, ignoreTrivia = false) {
+ const len = text.length;
+ let pos = 0, value = "", tokenOffset = 0, token = 16, lineNumber = 0, lineStartOffset = 0, tokenLineStartOffset = 0, prevTokenLineStartOffset = 0, scanError = 0;
+ function scanHexDigits(count, exact) {
+ let digits = 0;
+ let value2 = 0;
+ while (digits < count || !exact) {
+ let ch = text.charCodeAt(pos);
+ if (ch >= 48 && ch <= 57) {
+ value2 = value2 * 16 + ch - 48;
+ } else if (ch >= 65 && ch <= 70) {
+ value2 = value2 * 16 + ch - 65 + 10;
+ } else if (ch >= 97 && ch <= 102) {
+ value2 = value2 * 16 + ch - 97 + 10;
+ } else {
+ break;
+ }
+ pos++;
+ digits++;
+ }
+ if (digits < count) {
+ value2 = -1;
+ }
+ return value2;
+ }
+ __name(scanHexDigits, "scanHexDigits");
+ function setPosition(newPosition) {
+ pos = newPosition;
+ value = "";
+ tokenOffset = 0;
+ token = 16;
+ scanError = 0;
+ }
+ __name(setPosition, "setPosition");
+ function scanNumber() {
+ let start = pos;
+ if (text.charCodeAt(pos) === 48) {
+ pos++;
+ } else {
+ pos++;
+ while (pos < text.length && isDigit2(text.charCodeAt(pos))) {
+ pos++;
+ }
+ }
+ if (pos < text.length && text.charCodeAt(pos) === 46) {
+ pos++;
+ if (pos < text.length && isDigit2(text.charCodeAt(pos))) {
+ pos++;
+ while (pos < text.length && isDigit2(text.charCodeAt(pos))) {
+ pos++;
+ }
+ } else {
+ scanError = 3;
+ return text.substring(start, pos);
+ }
+ }
+ let end = pos;
+ if (pos < text.length && (text.charCodeAt(pos) === 69 || text.charCodeAt(pos) === 101)) {
+ pos++;
+ if (pos < text.length && text.charCodeAt(pos) === 43 || text.charCodeAt(pos) === 45) {
+ pos++;
+ }
+ if (pos < text.length && isDigit2(text.charCodeAt(pos))) {
+ pos++;
+ while (pos < text.length && isDigit2(text.charCodeAt(pos))) {
+ pos++;
+ }
+ end = pos;
+ } else {
+ scanError = 3;
+ }
+ }
+ return text.substring(start, end);
+ }
+ __name(scanNumber, "scanNumber");
+ function scanString() {
+ let result = "", start = pos;
+ while (true) {
+ if (pos >= len) {
+ result += text.substring(start, pos);
+ scanError = 2;
+ break;
+ }
+ const ch = text.charCodeAt(pos);
+ if (ch === 34) {
+ result += text.substring(start, pos);
+ pos++;
+ break;
+ }
+ if (ch === 92) {
+ result += text.substring(start, pos);
+ pos++;
+ if (pos >= len) {
+ scanError = 2;
+ break;
+ }
+ const ch2 = text.charCodeAt(pos++);
+ switch (ch2) {
+ case 34:
+ result += '"';
+ break;
+ case 92:
+ result += "\\";
+ break;
+ case 47:
+ result += "/";
+ break;
+ case 98:
+ result += "\b";
+ break;
+ case 102:
+ result += "\f";
+ break;
+ case 110:
+ result += "\n";
+ break;
+ case 114:
+ result += "\r";
+ break;
+ case 116:
+ result += " ";
+ break;
+ case 117:
+ const ch3 = scanHexDigits(4, true);
+ if (ch3 >= 0) {
+ result += String.fromCharCode(ch3);
+ } else {
+ scanError = 4;
+ }
+ break;
+ default:
+ scanError = 5;
+ }
+ start = pos;
+ continue;
+ }
+ if (ch >= 0 && ch <= 31) {
+ if (isLineBreak(ch)) {
+ result += text.substring(start, pos);
+ scanError = 2;
+ break;
+ } else {
+ scanError = 6;
+ }
+ }
+ pos++;
+ }
+ return result;
+ }
+ __name(scanString, "scanString");
+ function scanNext() {
+ value = "";
+ scanError = 0;
+ tokenOffset = pos;
+ lineStartOffset = lineNumber;
+ prevTokenLineStartOffset = tokenLineStartOffset;
+ if (pos >= len) {
+ tokenOffset = len;
+ return token = 17;
+ }
+ let code = text.charCodeAt(pos);
+ if (isWhiteSpace(code)) {
+ do {
+ pos++;
+ value += String.fromCharCode(code);
+ code = text.charCodeAt(pos);
+ } while (isWhiteSpace(code));
+ return token = 15;
+ }
+ if (isLineBreak(code)) {
+ pos++;
+ value += String.fromCharCode(code);
+ if (code === 13 && text.charCodeAt(pos) === 10) {
+ pos++;
+ value += "\n";
+ }
+ lineNumber++;
+ tokenLineStartOffset = pos;
+ return token = 14;
+ }
+ switch (code) {
+ case 123:
+ pos++;
+ return token = 1;
+ case 125:
+ pos++;
+ return token = 2;
+ case 91:
+ pos++;
+ return token = 3;
+ case 93:
+ pos++;
+ return token = 4;
+ case 58:
+ pos++;
+ return token = 6;
+ case 44:
+ pos++;
+ return token = 5;
+ case 34:
+ pos++;
+ value = scanString();
+ return token = 10;
+ case 47:
+ const start = pos - 1;
+ if (text.charCodeAt(pos + 1) === 47) {
+ pos += 2;
+ while (pos < len) {
+ if (isLineBreak(text.charCodeAt(pos))) {
+ break;
+ }
+ pos++;
+ }
+ value = text.substring(start, pos);
+ return token = 12;
+ }
+ if (text.charCodeAt(pos + 1) === 42) {
+ pos += 2;
+ const safeLength = len - 1;
+ let commentClosed = false;
+ while (pos < safeLength) {
+ const ch = text.charCodeAt(pos);
+ if (ch === 42 && text.charCodeAt(pos + 1) === 47) {
+ pos += 2;
+ commentClosed = true;
+ break;
+ }
+ pos++;
+ if (isLineBreak(ch)) {
+ if (ch === 13 && text.charCodeAt(pos) === 10) {
+ pos++;
+ }
+ lineNumber++;
+ tokenLineStartOffset = pos;
+ }
+ }
+ if (!commentClosed) {
+ pos++;
+ scanError = 1;
+ }
+ value = text.substring(start, pos);
+ return token = 13;
+ }
+ value += String.fromCharCode(code);
+ pos++;
+ return token = 16;
+ case 45:
+ value += String.fromCharCode(code);
+ pos++;
+ if (pos === len || !isDigit2(text.charCodeAt(pos))) {
+ return token = 16;
+ }
+ case 48:
+ case 49:
+ case 50:
+ case 51:
+ case 52:
+ case 53:
+ case 54:
+ case 55:
+ case 56:
+ case 57:
+ value += scanNumber();
+ return token = 11;
+ default:
+ while (pos < len && isUnknownContentCharacter(code)) {
+ pos++;
+ code = text.charCodeAt(pos);
+ }
+ if (tokenOffset !== pos) {
+ value = text.substring(tokenOffset, pos);
+ switch (value) {
+ case "true":
+ return token = 8;
+ case "false":
+ return token = 9;
+ case "null":
+ return token = 7;
+ }
+ return token = 16;
+ }
+ value += String.fromCharCode(code);
+ pos++;
+ return token = 16;
+ }
+ }
+ __name(scanNext, "scanNext");
+ function isUnknownContentCharacter(code) {
+ if (isWhiteSpace(code) || isLineBreak(code)) {
+ return false;
+ }
+ switch (code) {
+ case 125:
+ case 93:
+ case 123:
+ case 91:
+ case 34:
+ case 58:
+ case 44:
+ case 47:
+ return false;
+ }
+ return true;
+ }
+ __name(isUnknownContentCharacter, "isUnknownContentCharacter");
+ function scanNextNonTrivia() {
+ let result;
+ do {
+ result = scanNext();
+ } while (result >= 12 && result <= 15);
+ return result;
+ }
+ __name(scanNextNonTrivia, "scanNextNonTrivia");
+ return {
+ setPosition,
+ getPosition: () => pos,
+ scan: ignoreTrivia ? scanNextNonTrivia : scanNext,
+ getToken: () => token,
+ getTokenValue: () => value,
+ getTokenOffset: () => tokenOffset,
+ getTokenLength: () => pos - tokenOffset,
+ getTokenStartLine: () => lineStartOffset,
+ getTokenStartCharacter: () => tokenOffset - prevTokenLineStartOffset,
+ getTokenError: () => scanError
+ };
+}
+__name(createScanner, "createScanner");
+function isWhiteSpace(ch) {
+ return ch === 32 || ch === 9;
+}
+__name(isWhiteSpace, "isWhiteSpace");
+function isLineBreak(ch) {
+ return ch === 10 || ch === 13;
+}
+__name(isLineBreak, "isLineBreak");
+function isDigit2(ch) {
+ return ch >= 48 && ch <= 57;
+}
+__name(isDigit2, "isDigit");
+var CharacterCodes;
+(function(CharacterCodes2) {
+ CharacterCodes2[CharacterCodes2["lineFeed"] = 10] = "lineFeed";
+ CharacterCodes2[CharacterCodes2["carriageReturn"] = 13] = "carriageReturn";
+ CharacterCodes2[CharacterCodes2["space"] = 32] = "space";
+ CharacterCodes2[CharacterCodes2["_0"] = 48] = "_0";
+ CharacterCodes2[CharacterCodes2["_1"] = 49] = "_1";
+ CharacterCodes2[CharacterCodes2["_2"] = 50] = "_2";
+ CharacterCodes2[CharacterCodes2["_3"] = 51] = "_3";
+ CharacterCodes2[CharacterCodes2["_4"] = 52] = "_4";
+ CharacterCodes2[CharacterCodes2["_5"] = 53] = "_5";
+ CharacterCodes2[CharacterCodes2["_6"] = 54] = "_6";
+ CharacterCodes2[CharacterCodes2["_7"] = 55] = "_7";
+ CharacterCodes2[CharacterCodes2["_8"] = 56] = "_8";
+ CharacterCodes2[CharacterCodes2["_9"] = 57] = "_9";
+ CharacterCodes2[CharacterCodes2["a"] = 97] = "a";
+ CharacterCodes2[CharacterCodes2["b"] = 98] = "b";
+ CharacterCodes2[CharacterCodes2["c"] = 99] = "c";
+ CharacterCodes2[CharacterCodes2["d"] = 100] = "d";
+ CharacterCodes2[CharacterCodes2["e"] = 101] = "e";
+ CharacterCodes2[CharacterCodes2["f"] = 102] = "f";
+ CharacterCodes2[CharacterCodes2["g"] = 103] = "g";
+ CharacterCodes2[CharacterCodes2["h"] = 104] = "h";
+ CharacterCodes2[CharacterCodes2["i"] = 105] = "i";
+ CharacterCodes2[CharacterCodes2["j"] = 106] = "j";
+ CharacterCodes2[CharacterCodes2["k"] = 107] = "k";
+ CharacterCodes2[CharacterCodes2["l"] = 108] = "l";
+ CharacterCodes2[CharacterCodes2["m"] = 109] = "m";
+ CharacterCodes2[CharacterCodes2["n"] = 110] = "n";
+ CharacterCodes2[CharacterCodes2["o"] = 111] = "o";
+ CharacterCodes2[CharacterCodes2["p"] = 112] = "p";
+ CharacterCodes2[CharacterCodes2["q"] = 113] = "q";
+ CharacterCodes2[CharacterCodes2["r"] = 114] = "r";
+ CharacterCodes2[CharacterCodes2["s"] = 115] = "s";
+ CharacterCodes2[CharacterCodes2["t"] = 116] = "t";
+ CharacterCodes2[CharacterCodes2["u"] = 117] = "u";
+ CharacterCodes2[CharacterCodes2["v"] = 118] = "v";
+ CharacterCodes2[CharacterCodes2["w"] = 119] = "w";
+ CharacterCodes2[CharacterCodes2["x"] = 120] = "x";
+ CharacterCodes2[CharacterCodes2["y"] = 121] = "y";
+ CharacterCodes2[CharacterCodes2["z"] = 122] = "z";
+ CharacterCodes2[CharacterCodes2["A"] = 65] = "A";
+ CharacterCodes2[CharacterCodes2["B"] = 66] = "B";
+ CharacterCodes2[CharacterCodes2["C"] = 67] = "C";
+ CharacterCodes2[CharacterCodes2["D"] = 68] = "D";
+ CharacterCodes2[CharacterCodes2["E"] = 69] = "E";
+ CharacterCodes2[CharacterCodes2["F"] = 70] = "F";
+ CharacterCodes2[CharacterCodes2["G"] = 71] = "G";
+ CharacterCodes2[CharacterCodes2["H"] = 72] = "H";
+ CharacterCodes2[CharacterCodes2["I"] = 73] = "I";
+ CharacterCodes2[CharacterCodes2["J"] = 74] = "J";
+ CharacterCodes2[CharacterCodes2["K"] = 75] = "K";
+ CharacterCodes2[CharacterCodes2["L"] = 76] = "L";
+ CharacterCodes2[CharacterCodes2["M"] = 77] = "M";
+ CharacterCodes2[CharacterCodes2["N"] = 78] = "N";
+ CharacterCodes2[CharacterCodes2["O"] = 79] = "O";
+ CharacterCodes2[CharacterCodes2["P"] = 80] = "P";
+ CharacterCodes2[CharacterCodes2["Q"] = 81] = "Q";
+ CharacterCodes2[CharacterCodes2["R"] = 82] = "R";
+ CharacterCodes2[CharacterCodes2["S"] = 83] = "S";
+ CharacterCodes2[CharacterCodes2["T"] = 84] = "T";
+ CharacterCodes2[CharacterCodes2["U"] = 85] = "U";
+ CharacterCodes2[CharacterCodes2["V"] = 86] = "V";
+ CharacterCodes2[CharacterCodes2["W"] = 87] = "W";
+ CharacterCodes2[CharacterCodes2["X"] = 88] = "X";
+ CharacterCodes2[CharacterCodes2["Y"] = 89] = "Y";
+ CharacterCodes2[CharacterCodes2["Z"] = 90] = "Z";
+ CharacterCodes2[CharacterCodes2["asterisk"] = 42] = "asterisk";
+ CharacterCodes2[CharacterCodes2["backslash"] = 92] = "backslash";
+ CharacterCodes2[CharacterCodes2["closeBrace"] = 125] = "closeBrace";
+ CharacterCodes2[CharacterCodes2["closeBracket"] = 93] = "closeBracket";
+ CharacterCodes2[CharacterCodes2["colon"] = 58] = "colon";
+ CharacterCodes2[CharacterCodes2["comma"] = 44] = "comma";
+ CharacterCodes2[CharacterCodes2["dot"] = 46] = "dot";
+ CharacterCodes2[CharacterCodes2["doubleQuote"] = 34] = "doubleQuote";
+ CharacterCodes2[CharacterCodes2["minus"] = 45] = "minus";
+ CharacterCodes2[CharacterCodes2["openBrace"] = 123] = "openBrace";
+ CharacterCodes2[CharacterCodes2["openBracket"] = 91] = "openBracket";
+ CharacterCodes2[CharacterCodes2["plus"] = 43] = "plus";
+ CharacterCodes2[CharacterCodes2["slash"] = 47] = "slash";
+ CharacterCodes2[CharacterCodes2["formFeed"] = 12] = "formFeed";
+ CharacterCodes2[CharacterCodes2["tab"] = 9] = "tab";
+})(CharacterCodes || (CharacterCodes = {}));
+
+// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/edit.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/impl/parser.js
+init_import_meta_url();
+var ParseOptions;
+(function(ParseOptions2) {
+ ParseOptions2.DEFAULT = {
+ allowTrailingComma: false
+ };
+})(ParseOptions || (ParseOptions = {}));
+function parse(text, errors = [], options14 = ParseOptions.DEFAULT) {
+ let currentProperty = null;
+ let currentParent = [];
+ const previousParents = [];
+ function onValue(value) {
+ if (Array.isArray(currentParent)) {
+ currentParent.push(value);
+ } else if (currentProperty !== null) {
+ currentParent[currentProperty] = value;
+ }
+ }
+ __name(onValue, "onValue");
+ const visitor = {
+ onObjectBegin: () => {
+ const object = {};
+ onValue(object);
+ previousParents.push(currentParent);
+ currentParent = object;
+ currentProperty = null;
+ },
+ onObjectProperty: (name) => {
+ currentProperty = name;
+ },
+ onObjectEnd: () => {
+ currentParent = previousParents.pop();
+ },
+ onArrayBegin: () => {
+ const array = [];
+ onValue(array);
+ previousParents.push(currentParent);
+ currentParent = array;
+ currentProperty = null;
+ },
+ onArrayEnd: () => {
+ currentParent = previousParents.pop();
+ },
+ onLiteralValue: onValue,
+ onError: (error, offset, length) => {
+ errors.push({ error, offset, length });
+ }
+ };
+ visit(text, visitor, options14);
+ return currentParent[0];
+}
+__name(parse, "parse");
+function visit(text, visitor, options14 = ParseOptions.DEFAULT) {
+ const _scanner = createScanner(text, false);
+ const _jsonPath = [];
+ function toNoArgVisit(visitFunction) {
+ return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
+ }
+ __name(toNoArgVisit, "toNoArgVisit");
+ function toNoArgVisitWithPath(visitFunction) {
+ return visitFunction ? () => visitFunction(_scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
+ }
+ __name(toNoArgVisitWithPath, "toNoArgVisitWithPath");
+ function toOneArgVisit(visitFunction) {
+ return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter()) : () => true;
+ }
+ __name(toOneArgVisit, "toOneArgVisit");
+ function toOneArgVisitWithPath(visitFunction) {
+ return visitFunction ? (arg) => visitFunction(arg, _scanner.getTokenOffset(), _scanner.getTokenLength(), _scanner.getTokenStartLine(), _scanner.getTokenStartCharacter(), () => _jsonPath.slice()) : () => true;
+ }
+ __name(toOneArgVisitWithPath, "toOneArgVisitWithPath");
+ const onObjectBegin = toNoArgVisitWithPath(visitor.onObjectBegin), onObjectProperty = toOneArgVisitWithPath(visitor.onObjectProperty), onObjectEnd = toNoArgVisit(visitor.onObjectEnd), onArrayBegin = toNoArgVisitWithPath(visitor.onArrayBegin), onArrayEnd = toNoArgVisit(visitor.onArrayEnd), onLiteralValue = toOneArgVisitWithPath(visitor.onLiteralValue), onSeparator = toOneArgVisit(visitor.onSeparator), onComment = toNoArgVisit(visitor.onComment), onError = toOneArgVisit(visitor.onError);
+ const disallowComments = options14 && options14.disallowComments;
+ const allowTrailingComma = options14 && options14.allowTrailingComma;
+ function scanNext() {
+ while (true) {
+ const token = _scanner.scan();
+ switch (_scanner.getTokenError()) {
+ case 4:
+ handleError(
+ 14
+ /* ParseErrorCode.InvalidUnicode */
+ );
+ break;
+ case 5:
+ handleError(
+ 15
+ /* ParseErrorCode.InvalidEscapeCharacter */
+ );
+ break;
+ case 3:
+ handleError(
+ 13
+ /* ParseErrorCode.UnexpectedEndOfNumber */
+ );
+ break;
+ case 1:
+ if (!disallowComments) {
+ handleError(
+ 11
+ /* ParseErrorCode.UnexpectedEndOfComment */
+ );
+ }
+ break;
+ case 2:
+ handleError(
+ 12
+ /* ParseErrorCode.UnexpectedEndOfString */
+ );
+ break;
+ case 6:
+ handleError(
+ 16
+ /* ParseErrorCode.InvalidCharacter */
+ );
+ break;
+ }
+ switch (token) {
+ case 12:
+ case 13:
+ if (disallowComments) {
+ handleError(
+ 10
+ /* ParseErrorCode.InvalidCommentToken */
+ );
+ } else {
+ onComment();
+ }
+ break;
+ case 16:
+ handleError(
+ 1
+ /* ParseErrorCode.InvalidSymbol */
+ );
+ break;
+ case 15:
+ case 14:
+ break;
+ default:
+ return token;
+ }
+ }
+ }
+ __name(scanNext, "scanNext");
+ function handleError(error, skipUntilAfter = [], skipUntil = []) {
+ onError(error);
+ if (skipUntilAfter.length + skipUntil.length > 0) {
+ let token = _scanner.getToken();
+ while (token !== 17) {
+ if (skipUntilAfter.indexOf(token) !== -1) {
+ scanNext();
+ break;
+ } else if (skipUntil.indexOf(token) !== -1) {
+ break;
+ }
+ token = scanNext();
+ }
+ }
+ }
+ __name(handleError, "handleError");
+ function parseString(isValue) {
+ const value = _scanner.getTokenValue();
+ if (isValue) {
+ onLiteralValue(value);
+ } else {
+ onObjectProperty(value);
+ _jsonPath.push(value);
+ }
+ scanNext();
+ return true;
+ }
+ __name(parseString, "parseString");
+ function parseLiteral() {
+ switch (_scanner.getToken()) {
+ case 11:
+ const tokenValue = _scanner.getTokenValue();
+ let value = Number(tokenValue);
+ if (isNaN(value)) {
+ handleError(
+ 2
+ /* ParseErrorCode.InvalidNumberFormat */
+ );
+ value = 0;
+ }
+ onLiteralValue(value);
+ break;
+ case 7:
+ onLiteralValue(null);
+ break;
+ case 8:
+ onLiteralValue(true);
+ break;
+ case 9:
+ onLiteralValue(false);
+ break;
+ default:
+ return false;
+ }
+ scanNext();
+ return true;
+ }
+ __name(parseLiteral, "parseLiteral");
+ function parseProperty() {
+ if (_scanner.getToken() !== 10) {
+ handleError(3, [], [
+ 2,
+ 5
+ /* SyntaxKind.CommaToken */
+ ]);
+ return false;
+ }
+ parseString(false);
+ if (_scanner.getToken() === 6) {
+ onSeparator(":");
+ scanNext();
+ if (!parseValue()) {
+ handleError(4, [], [
+ 2,
+ 5
+ /* SyntaxKind.CommaToken */
+ ]);
+ }
+ } else {
+ handleError(5, [], [
+ 2,
+ 5
+ /* SyntaxKind.CommaToken */
+ ]);
+ }
+ _jsonPath.pop();
+ return true;
+ }
+ __name(parseProperty, "parseProperty");
+ function parseObject() {
+ onObjectBegin();
+ scanNext();
+ let needsComma = false;
+ while (_scanner.getToken() !== 2 && _scanner.getToken() !== 17) {
+ if (_scanner.getToken() === 5) {
+ if (!needsComma) {
+ handleError(4, [], []);
+ }
+ onSeparator(",");
+ scanNext();
+ if (_scanner.getToken() === 2 && allowTrailingComma) {
+ break;
+ }
+ } else if (needsComma) {
+ handleError(6, [], []);
+ }
+ if (!parseProperty()) {
+ handleError(4, [], [
+ 2,
+ 5
+ /* SyntaxKind.CommaToken */
+ ]);
+ }
+ needsComma = true;
+ }
+ onObjectEnd();
+ if (_scanner.getToken() !== 2) {
+ handleError(7, [
+ 2
+ /* SyntaxKind.CloseBraceToken */
+ ], []);
+ } else {
+ scanNext();
+ }
+ return true;
+ }
+ __name(parseObject, "parseObject");
+ function parseArray() {
+ onArrayBegin();
+ scanNext();
+ let isFirstElement = true;
+ let needsComma = false;
+ while (_scanner.getToken() !== 4 && _scanner.getToken() !== 17) {
+ if (_scanner.getToken() === 5) {
+ if (!needsComma) {
+ handleError(4, [], []);
+ }
+ onSeparator(",");
+ scanNext();
+ if (_scanner.getToken() === 4 && allowTrailingComma) {
+ break;
+ }
+ } else if (needsComma) {
+ handleError(6, [], []);
+ }
+ if (isFirstElement) {
+ _jsonPath.push(0);
+ isFirstElement = false;
+ } else {
+ _jsonPath[_jsonPath.length - 1]++;
+ }
+ if (!parseValue()) {
+ handleError(4, [], [
+ 4,
+ 5
+ /* SyntaxKind.CommaToken */
+ ]);
+ }
+ needsComma = true;
+ }
+ onArrayEnd();
+ if (!isFirstElement) {
+ _jsonPath.pop();
+ }
+ if (_scanner.getToken() !== 4) {
+ handleError(8, [
+ 4
+ /* SyntaxKind.CloseBracketToken */
+ ], []);
+ } else {
+ scanNext();
+ }
+ return true;
+ }
+ __name(parseArray, "parseArray");
+ function parseValue() {
+ switch (_scanner.getToken()) {
+ case 3:
+ return parseArray();
+ case 1:
+ return parseObject();
+ case 10:
+ return parseString(true);
+ default:
+ return parseLiteral();
+ }
+ }
+ __name(parseValue, "parseValue");
+ scanNext();
+ if (_scanner.getToken() === 17) {
+ if (options14.allowEmptyContent) {
+ return true;
+ }
+ handleError(4, [], []);
+ return false;
+ }
+ if (!parseValue()) {
+ handleError(4, [], []);
+ return false;
+ }
+ if (_scanner.getToken() !== 17) {
+ handleError(9, [], []);
+ }
+ return true;
+}
+__name(visit, "visit");
+
+// ../../node_modules/.pnpm/jsonc-parser@3.2.0/node_modules/jsonc-parser/lib/esm/main.js
+var ScanError;
+(function(ScanError2) {
+ ScanError2[ScanError2["None"] = 0] = "None";
+ ScanError2[ScanError2["UnexpectedEndOfComment"] = 1] = "UnexpectedEndOfComment";
+ ScanError2[ScanError2["UnexpectedEndOfString"] = 2] = "UnexpectedEndOfString";
+ ScanError2[ScanError2["UnexpectedEndOfNumber"] = 3] = "UnexpectedEndOfNumber";
+ ScanError2[ScanError2["InvalidUnicode"] = 4] = "InvalidUnicode";
+ ScanError2[ScanError2["InvalidEscapeCharacter"] = 5] = "InvalidEscapeCharacter";
+ ScanError2[ScanError2["InvalidCharacter"] = 6] = "InvalidCharacter";
+})(ScanError || (ScanError = {}));
+var SyntaxKind;
+(function(SyntaxKind2) {
+ SyntaxKind2[SyntaxKind2["OpenBraceToken"] = 1] = "OpenBraceToken";
+ SyntaxKind2[SyntaxKind2["CloseBraceToken"] = 2] = "CloseBraceToken";
+ SyntaxKind2[SyntaxKind2["OpenBracketToken"] = 3] = "OpenBracketToken";
+ SyntaxKind2[SyntaxKind2["CloseBracketToken"] = 4] = "CloseBracketToken";
+ SyntaxKind2[SyntaxKind2["CommaToken"] = 5] = "CommaToken";
+ SyntaxKind2[SyntaxKind2["ColonToken"] = 6] = "ColonToken";
+ SyntaxKind2[SyntaxKind2["NullKeyword"] = 7] = "NullKeyword";
+ SyntaxKind2[SyntaxKind2["TrueKeyword"] = 8] = "TrueKeyword";
+ SyntaxKind2[SyntaxKind2["FalseKeyword"] = 9] = "FalseKeyword";
+ SyntaxKind2[SyntaxKind2["StringLiteral"] = 10] = "StringLiteral";
+ SyntaxKind2[SyntaxKind2["NumericLiteral"] = 11] = "NumericLiteral";
+ SyntaxKind2[SyntaxKind2["LineCommentTrivia"] = 12] = "LineCommentTrivia";
+ SyntaxKind2[SyntaxKind2["BlockCommentTrivia"] = 13] = "BlockCommentTrivia";
+ SyntaxKind2[SyntaxKind2["LineBreakTrivia"] = 14] = "LineBreakTrivia";
+ SyntaxKind2[SyntaxKind2["Trivia"] = 15] = "Trivia";
+ SyntaxKind2[SyntaxKind2["Unknown"] = 16] = "Unknown";
+ SyntaxKind2[SyntaxKind2["EOF"] = 17] = "EOF";
+})(SyntaxKind || (SyntaxKind = {}));
+var parse2 = parse;
+var ParseErrorCode;
+(function(ParseErrorCode2) {
+ ParseErrorCode2[ParseErrorCode2["InvalidSymbol"] = 1] = "InvalidSymbol";
+ ParseErrorCode2[ParseErrorCode2["InvalidNumberFormat"] = 2] = "InvalidNumberFormat";
+ ParseErrorCode2[ParseErrorCode2["PropertyNameExpected"] = 3] = "PropertyNameExpected";
+ ParseErrorCode2[ParseErrorCode2["ValueExpected"] = 4] = "ValueExpected";
+ ParseErrorCode2[ParseErrorCode2["ColonExpected"] = 5] = "ColonExpected";
+ ParseErrorCode2[ParseErrorCode2["CommaExpected"] = 6] = "CommaExpected";
+ ParseErrorCode2[ParseErrorCode2["CloseBraceExpected"] = 7] = "CloseBraceExpected";
+ ParseErrorCode2[ParseErrorCode2["CloseBracketExpected"] = 8] = "CloseBracketExpected";
+ ParseErrorCode2[ParseErrorCode2["EndOfFileExpected"] = 9] = "EndOfFileExpected";
+ ParseErrorCode2[ParseErrorCode2["InvalidCommentToken"] = 10] = "InvalidCommentToken";
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfComment"] = 11] = "UnexpectedEndOfComment";
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfString"] = 12] = "UnexpectedEndOfString";
+ ParseErrorCode2[ParseErrorCode2["UnexpectedEndOfNumber"] = 13] = "UnexpectedEndOfNumber";
+ ParseErrorCode2[ParseErrorCode2["InvalidUnicode"] = 14] = "InvalidUnicode";
+ ParseErrorCode2[ParseErrorCode2["InvalidEscapeCharacter"] = 15] = "InvalidEscapeCharacter";
+ ParseErrorCode2[ParseErrorCode2["InvalidCharacter"] = 16] = "InvalidCharacter";
+})(ParseErrorCode || (ParseErrorCode = {}));
+function printParseErrorCode(code) {
+ switch (code) {
+ case 1:
+ return "InvalidSymbol";
+ case 2:
+ return "InvalidNumberFormat";
+ case 3:
+ return "PropertyNameExpected";
+ case 4:
+ return "ValueExpected";
+ case 5:
+ return "ColonExpected";
+ case 6:
+ return "CommaExpected";
+ case 7:
+ return "CloseBraceExpected";
+ case 8:
+ return "CloseBracketExpected";
+ case 9:
+ return "EndOfFileExpected";
+ case 10:
+ return "InvalidCommentToken";
+ case 11:
+ return "UnexpectedEndOfComment";
+ case 12:
+ return "UnexpectedEndOfString";
+ case 13:
+ return "UnexpectedEndOfNumber";
+ case 14:
+ return "InvalidUnicode";
+ case 15:
+ return "InvalidEscapeCharacter";
+ case 16:
+ return "InvalidCharacter";
+ }
+ return "";
+}
+__name(printParseErrorCode, "printParseErrorCode");
+
+// src/parse.ts
+function formatMessage({ text, notes, location, kind = "error" }, color = true) {
+ const input = { text, notes, location };
+ delete input.location?.fileText;
+ for (const note of notes ?? []) {
+ delete note.location?.fileText;
+ }
+ const lines = (0, import_esbuild2.formatMessagesSync)([input], {
+ color,
+ kind,
+ terminalWidth: logger.columns
+ });
+ return lines.join("\n");
+}
+__name(formatMessage, "formatMessage");
+var ParseError = class extends Error {
+ text;
+ notes;
+ location;
+ kind;
+ constructor({ text, notes, location, kind }) {
+ super(text);
+ this.name = this.constructor.name;
+ this.text = text;
+ this.notes = notes ?? [];
+ this.location = location;
+ this.kind = kind ?? "error";
+ }
+};
+__name(ParseError, "ParseError");
+var TOML_ERROR_NAME = "TomlError";
+var TOML_ERROR_SUFFIX = " at row ";
+function parseTOML(input, file) {
+ try {
+ const normalizedInput = input.replace(/\r\n/g, "\n");
+ return import_toml.default.parse(normalizedInput);
+ } catch (err) {
+ const { name, message, line, col } = err;
+ if (name !== TOML_ERROR_NAME) {
+ throw err;
+ }
+ const text = message.substring(0, message.lastIndexOf(TOML_ERROR_SUFFIX));
+ const lineText = input.split("\n")[line];
+ const location = {
+ lineText,
+ line: line + 1,
+ column: col - 1,
+ file,
+ fileText: input
+ };
+ throw new ParseError({ text, location });
+ }
+}
+__name(parseTOML, "parseTOML");
+var JSON_ERROR_SUFFIX = " in JSON at position ";
+function parsePackageJSON(input, file) {
+ return parseJSON(input, file);
+}
+__name(parsePackageJSON, "parsePackageJSON");
+function parseJSON(input, file) {
+ try {
+ return JSON.parse(input);
+ } catch (err) {
+ const { message } = err;
+ const index = message.lastIndexOf(JSON_ERROR_SUFFIX);
+ if (index < 0) {
+ throw err;
+ }
+ const text = message.substring(0, index);
+ const position = parseInt(
+ message.substring(index + JSON_ERROR_SUFFIX.length)
+ );
+ const location = indexLocation({ file, fileText: input }, position);
+ throw new ParseError({ text, location });
+ }
+}
+__name(parseJSON, "parseJSON");
+function parseJSONC(input, file) {
+ const errors = [];
+ const data = parse2(input, errors);
+ if (errors.length) {
+ throw new ParseError({
+ text: printParseErrorCode(errors[0].error),
+ location: {
+ ...indexLocation({ file, fileText: input }, errors[0].offset + 1),
+ length: errors[0].length
+ }
+ });
+ }
+ return data;
+}
+__name(parseJSONC, "parseJSONC");
+function readFileSyncToBuffer(file) {
+ try {
+ return fs2.readFileSync(file);
+ } catch (err) {
+ const { message } = err;
+ throw new ParseError({
+ text: `Could not read file: ${file}`,
+ notes: [
+ {
+ text: message.replace(file, (0, import_node_path3.resolve)(file))
+ }
+ ]
+ });
+ }
+}
+__name(readFileSyncToBuffer, "readFileSyncToBuffer");
+function readFileSync5(file) {
+ try {
+ return fs2.readFileSync(file, { encoding: "utf-8" });
+ } catch (err) {
+ const { message } = err;
+ throw new ParseError({
+ text: `Could not read file: ${file}`,
+ notes: [
+ {
+ text: message.replace(file, (0, import_node_path3.resolve)(file))
+ }
+ ]
+ });
+ }
+}
+__name(readFileSync5, "readFileSync");
+function indexLocation(file, index) {
+ let lineText, line = 0, column = 0, cursor = 0;
+ const { fileText = "" } = file;
+ for (const row of fileText.split("\n")) {
+ line++;
+ cursor += row.length + 1;
+ if (cursor >= index) {
+ lineText = row;
+ column = row.length - (cursor - index);
+ break;
+ }
+ }
+ return { lineText, line, column, ...file };
+}
+__name(indexLocation, "indexLocation");
+var units = {
+ nanoseconds: 1e-9,
+ nanosecond: 1e-9,
+ microseconds: 1e-6,
+ microsecond: 1e-6,
+ milliseconds: 1e-3,
+ millisecond: 1e-3,
+ seconds: 1,
+ second: 1,
+ minutes: 60,
+ minute: 60,
+ hours: 3600,
+ hour: 3600,
+ days: 86400,
+ day: 86400,
+ weeks: 604800,
+ week: 604800,
+ month: 18144e3,
+ year: 220752e3,
+ nsecs: 1e-9,
+ nsec: 1e-9,
+ usecs: 1e-6,
+ usec: 1e-6,
+ msecs: 1e-3,
+ msec: 1e-3,
+ secs: 1,
+ sec: 1,
+ mins: 60,
+ min: 60,
+ ns: 1e-9,
+ us: 1e-6,
+ ms: 1e-3,
+ mo: 18144e3,
+ yr: 220752e3,
+ s: 1,
+ m: 60,
+ h: 3600,
+ d: 86400,
+ w: 604800,
+ y: 220752e3
+};
+function parseHumanDuration(s) {
+ const unitsMap = new Map(Object.entries(units));
+ s = s.trim().toLowerCase();
+ let base = 1;
+ for (const [name, _2] of unitsMap) {
+ if (s.endsWith(name)) {
+ s = s.substring(0, s.length - name.length);
+ base = unitsMap.get(name) || 1;
+ break;
+ }
+ }
+ return Number(s) * base;
+}
+__name(parseHumanDuration, "parseHumanDuration");
+
+// src/config/validation.ts
+init_import_meta_url();
+var import_node_path6 = __toESM(require("node:path"));
+var import_toml3 = __toESM(require_toml());
+
+// src/constellation/utils.ts
+init_import_meta_url();
+
+// src/cfetch/index.ts
+init_import_meta_url();
+var import_node_url4 = require("node:url");
+
+// src/cfetch/internal.ts
+init_import_meta_url();
+var import_node_assert2 = __toESM(require("node:assert"));
+var import_undici3 = __toESM(require_undici());
+var import_undici4 = __toESM(require_undici());
+
+// package.json
+var version = "3.9.0";
+var package_default = {
+ name: "wrangler",
+ version,
+ description: "Command-line interface for all things Cloudflare Workers",
+ keywords: [
+ "wrangler",
+ "cloudflare",
+ "workers",
+ "cloudflare workers",
+ "edge",
+ "compute",
+ "serverless",
+ "serverless application",
+ "serverless module",
+ "wasm",
+ "web",
+ "assembly",
+ "webassembly",
+ "rust",
+ "emscripten",
+ "typescript",
+ "graphql",
+ "router",
+ "http",
+ "cli"
+ ],
+ homepage: "https://github.com/cloudflare/workers-sdk#readme",
+ bugs: {
+ url: "https://github.com/cloudflare/workers-sdk/issues"
+ },
+ repository: {
+ type: "git",
+ url: "https://github.com/cloudflare/workers-sdk.git",
+ directory: "packages/wrangler"
+ },
+ license: "MIT OR Apache-2.0",
+ author: "wrangler@cloudflare.com",
+ main: "wrangler-dist/cli.js",
+ types: "wrangler-dist/cli.d.ts",
+ bin: {
+ wrangler: "./bin/wrangler.js",
+ wrangler2: "./bin/wrangler.js"
+ },
+ files: [
+ "bin",
+ "miniflare-dist",
+ "wrangler-dist",
+ "templates",
+ "kv-asset-handler.js",
+ "Cloudflare_CA.pem"
+ ],
+ scripts: {
+ "assert-git-version": "node -r esbuild-register scripts/assert-git-version.ts",
+ build: "pnpm run clean && pnpm run bundle && pnpm run emit-types",
+ bundle: "node -r esbuild-register scripts/bundle.ts",
+ "check:lint": "eslint .",
+ "check:type": "tsc",
+ clean: "rimraf wrangler-dist miniflare-dist emitted-types",
+ dev: "pnpm run clean && concurrently -c black,blue --kill-others-on-fail false 'pnpm run bundle --watch' 'pnpm run check:type --watch --preserveWatchOutput'",
+ "emit-types": "tsc -p tsconfig.emit.json && node -r esbuild-register scripts/emit-types.ts",
+ prepublishOnly: "SOURCEMAPS=false npm run build",
+ start: "pnpm run bundle && cross-env NODE_OPTIONS=--enable-source-maps ./bin/wrangler.js",
+ test: "pnpm run assert-git-version && jest",
+ "test:ci": "pnpm run test --coverage",
+ "test:debug": "pnpm run test --silent=false --verbose=true",
+ "test:e2e": "vitest --test-timeout 240000 --single-thread --dir ./e2e run",
+ "test:watch": "pnpm run test --runInBand --testTimeout=50000 --watch",
+ "type:tests": "tsc -p ./src/__tests__/tsconfig.json && tsc -p ./e2e/tsconfig.json"
+ },
+ jest: {
+ coverageReporters: [
+ "json",
+ "html",
+ "text",
+ "cobertura"
+ ],
+ moduleNameMapper: {
+ clipboardy: "/src/__tests__/helpers/clipboardy-mock.js",
+ "miniflare/cli": "/../../node_modules/miniflare/dist/src/cli.js"
+ },
+ restoreMocks: true,
+ setupFilesAfterEnv: [
+ "/src/__tests__/jest.setup.ts"
+ ],
+ testRegex: "src/__tests__/.*\\.(test|spec)\\.[jt]sx?$",
+ testTimeout: 5e4,
+ transform: {
+ "^.+\\.c?(t|j)sx?$": [
+ "esbuild-jest",
+ {
+ sourcemap: true
+ }
+ ]
+ },
+ transformIgnorePatterns: [
+ "node_modules/.pnpm/(?!find-up|locate-path|p-locate|p-limit|p-timeout|p-queue|yocto-queue|path-exists|execa|strip-final-newline|npm-run-path|path-key|onetime|mimic-fn|human-signals|is-stream|get-port|supports-color|pretty-bytes|npx-import)"
+ ],
+ snapshotFormat: {
+ escapeString: true,
+ printBasicPrototype: true
+ }
+ },
+ dependencies: {
+ "@cloudflare/kv-asset-handler": "^0.2.0",
+ "@esbuild-plugins/node-globals-polyfill": "^0.2.3",
+ "@esbuild-plugins/node-modules-polyfill": "^0.2.2",
+ "blake3-wasm": "^2.1.5",
+ chokidar: "^3.5.3",
+ esbuild: "0.17.19",
+ miniflare: "3.20230918.0",
+ nanoid: "^3.3.3",
+ "path-to-regexp": "^6.2.0",
+ selfsigned: "^2.0.1",
+ "source-map": "0.6.1",
+ "source-map-support": "0.5.21",
+ "xxhash-wasm": "^1.0.1"
+ },
+ devDependencies: {
+ "@cloudflare/pages-shared": "workspace:^",
+ "@cloudflare/eslint-config-worker": "*",
+ "@cloudflare/types": "^6.18.4",
+ "@cloudflare/workers-tsconfig": "workspace:*",
+ "@cloudflare/workers-types": "^4.20230724.0",
+ "@iarna/toml": "^3.0.0",
+ "@microsoft/api-extractor": "^7.28.3",
+ "@types/body-parser": "^1.19.2",
+ "@types/busboy": "^1.5.0",
+ "@types/command-exists": "^1.2.0",
+ "@types/express": "^4.17.13",
+ "@types/glob-to-regexp": "0.4.1",
+ "@types/is-ci": "^3.0.0",
+ "@types/javascript-time-ago": "^2.0.3",
+ "@types/mime": "^2.0.3",
+ "@types/minimatch": "^5.1.2",
+ "@types/prompts": "^2.0.14",
+ "@types/react": "^17.0.37",
+ "@types/serve-static": "^1.13.10",
+ "@types/signal-exit": "^3.0.1",
+ "@types/source-map-support": "^0.5.7",
+ "@types/supports-color": "^8.1.1",
+ "@types/ws": "^8.5.3",
+ "@types/yargs": "^17.0.10",
+ "@webcontainer/env": "^1.1.0",
+ "@types/jest": "^29.5.5",
+ "esbuild-jest": "0.5.0",
+ jest: "^29.7.0",
+ "body-parser": "^1.20.0",
+ chalk: "^2.4.2",
+ "cli-table3": "^0.6.3",
+ clipboardy: "^3.0.0",
+ "cmd-shim": "^4.1.0",
+ "command-exists": "^1.2.9",
+ concurrently: "^7.2.2",
+ "devtools-protocol": "^0.0.955664",
+ dotenv: "^16.0.0",
+ execa: "^6.1.0",
+ express: "^4.18.1",
+ finalhandler: "^1.2.0",
+ "find-up": "^6.3.0",
+ "get-port": "^6.1.2",
+ "glob-to-regexp": "0.4.1",
+ "http-terminator": "^3.2.0",
+ ignore: "^5.2.0",
+ ink: "^3.2.0",
+ "ink-select-input": "^4.2.1",
+ "ink-spinner": "^4.0.3",
+ "ink-table": "^3.0.0",
+ "ink-testing-library": "^2.1.0",
+ "ink-text-input": "^4.0.3",
+ "is-ci": "^3.0.1",
+ "javascript-time-ago": "^2.5.4",
+ "jest-fetch-mock": "^3.0.3",
+ "jest-websocket-mock": "^2.5.0",
+ mime: "^3.0.0",
+ minimatch: "^5.1.0",
+ msw: "^0.49.1",
+ "npx-import": "^1.1.3",
+ open: "^8.4.0",
+ "p-queue": "^7.2.0",
+ "patch-console": "^1.0.0",
+ "pretty-bytes": "^6.0.0",
+ prompts: "^2.4.2",
+ react: "^17.0.2",
+ "react-error-boundary": "^3.1.4",
+ "remove-accents-esm": "^0.0.1",
+ semiver: "^1.1.0",
+ "serve-static": "^1.15.0",
+ shellac: "^0.8.0",
+ "signal-exit": "^3.0.7",
+ "strip-ansi": "^7.0.1",
+ "supports-color": "^9.2.2",
+ "timeago.js": "^4.0.2",
+ "tmp-promise": "^3.0.3",
+ "ts-dedent": "^2.2.0",
+ undici: "5.20.0",
+ "update-check": "^1.5.4",
+ vitest: "^0.34.4",
+ ws: "^8.5.0",
+ "xdg-app-paths": "^7.3.0",
+ yargs: "^17.4.1",
+ "yoga-layout": "file:../../vendor/yoga-layout-2.0.0-beta.1.tgz"
+ },
+ optionalDependencies: {
+ fsevents: "~2.3.2"
+ },
+ engines: {
+ node: ">=16.13.0"
+ }
+};
+
+// src/environment-variables/misc-variables.ts
+init_import_meta_url();
+var getC3CommandFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_C3_COMMAND",
+ defaultValue: () => "create cloudflare@2"
+});
+var getWranglerSendMetricsFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_SEND_METRICS"
+});
+var getCloudflareApiEnvironmentFromEnv = getEnvironmentVariableFactory(
+ {
+ variableName: "WRANGLER_API_ENVIRONMENT",
+ defaultValue: () => "production"
+ }
+);
+var getCloudflareApiBaseUrl = getEnvironmentVariableFactory({
+ variableName: "CLOUDFLARE_API_BASE_URL",
+ deprecatedName: "CF_API_BASE_URL",
+ defaultValue: () => getCloudflareApiEnvironmentFromEnv() === "staging" ? "https://api.staging.cloudflare.com/client/v4" : "https://api.cloudflare.com/client/v4"
+});
+
+// src/user/index.ts
+init_import_meta_url();
+
+// src/user/user.ts
+init_import_meta_url();
+var import_node_assert = __toESM(require("node:assert"));
+var import_node_crypto2 = require("node:crypto");
+var import_node_fs3 = require("node:fs");
+var import_node_http = __toESM(require("node:http"));
+var import_node_path5 = __toESM(require("node:path"));
+var import_node_url3 = __toESM(require("node:url"));
+var import_node_util2 = require("node:util");
+var import_toml2 = __toESM(require_toml());
+var import_undici2 = __toESM(require_undici());
+
+// src/config-cache.ts
+init_import_meta_url();
+var import_fs5 = require("fs");
+var path3 = __toESM(require("path"));
+
+// src/is-ci.ts
+init_import_meta_url();
+var import_is_ci = __toESM(require_is_ci2());
+var CI = {
+ /** Is Wrangler currently running in a CI? */
+ isCI() {
+ return import_is_ci.default;
+ }
+};
+
+// src/is-interactive.ts
+init_import_meta_url();
+function isInteractive() {
+ if (process.env.CF_PAGES === "1") {
+ return false;
+ }
+ try {
+ return Boolean(process.stdin.isTTY && process.stdout.isTTY);
+ } catch {
+ return false;
+ }
+}
+__name(isInteractive, "isInteractive");
+
+// src/config-cache.ts
+var cacheMessageShown = false;
+var __cacheFolder;
+function getCacheFolder() {
+ if (__cacheFolder || __cacheFolder === null)
+ return __cacheFolder;
+ const closestNodeModulesDirectory = findUpSync("node_modules", {
+ type: "directory"
+ });
+ __cacheFolder = closestNodeModulesDirectory ? path3.join(closestNodeModulesDirectory, ".cache/wrangler") : null;
+ if (!__cacheFolder) {
+ logger.debug("No folder available to cache configuration");
+ }
+ return __cacheFolder;
+}
+__name(getCacheFolder, "getCacheFolder");
+var arrayFormatter = new Intl.ListFormat("en", {
+ style: "long",
+ type: "conjunction"
+});
+function showCacheMessage(fields, folder) {
+ if (!cacheMessageShown && isInteractive() && !CI.isCI()) {
+ if (fields.length > 0) {
+ logger.debug(
+ `Retrieving cached values for ${arrayFormatter.format(
+ fields
+ )} from ${path3.relative(process.cwd(), folder)}`
+ );
+ cacheMessageShown = true;
+ }
+ }
+}
+__name(showCacheMessage, "showCacheMessage");
+function getConfigCache(fileName) {
+ try {
+ const cacheFolder = getCacheFolder();
+ if (cacheFolder) {
+ const configCacheLocation = path3.join(cacheFolder, fileName);
+ const configCache = JSON.parse(
+ (0, import_fs5.readFileSync)(configCacheLocation, "utf-8")
+ );
+ showCacheMessage(Object.keys(configCache), cacheFolder);
+ return configCache;
+ } else
+ return {};
+ } catch (err) {
+ return {};
+ }
+}
+__name(getConfigCache, "getConfigCache");
+function saveToConfigCache(fileName, newValues) {
+ const cacheFolder = getCacheFolder();
+ if (cacheFolder) {
+ logger.debug(`Saving to cache: ${JSON.stringify(newValues)}`);
+ const configCacheLocation = path3.join(cacheFolder, fileName);
+ const existingValues = getConfigCache(fileName);
+ (0, import_fs5.mkdirSync)(path3.dirname(configCacheLocation), { recursive: true });
+ (0, import_fs5.writeFileSync)(
+ configCacheLocation,
+ JSON.stringify({ ...existingValues, ...newValues }, null, 2)
+ );
+ }
+}
+__name(saveToConfigCache, "saveToConfigCache");
+function purgeConfigCaches() {
+ const cacheFolder = getCacheFolder();
+ if (cacheFolder) {
+ (0, import_fs5.rmSync)(cacheFolder, { recursive: true, force: true });
+ }
+ __cacheFolder = void 0;
+}
+__name(purgeConfigCaches, "purgeConfigCaches");
+
+// src/dialogs.ts
+init_import_meta_url();
+var import_chalk2 = __toESM(require_chalk());
+var import_prompts = __toESM(require_prompts3());
+function isNonInteractiveOrCI() {
+ return !isInteractive() || CI.isCI();
+}
+__name(isNonInteractiveOrCI, "isNonInteractiveOrCI");
+var NoDefaultValueProvided = class extends Error {
+ constructor() {
+ super("This command cannot be run in a non-interactive context");
+ Object.setPrototypeOf(this, new.target.prototype);
+ }
+};
+__name(NoDefaultValueProvided, "NoDefaultValueProvided");
+async function confirm(text, { defaultValue = true } = {}) {
+ if (isNonInteractiveOrCI()) {
+ logger.log(`? ${text}`);
+ logger.log(
+ `\u{1F916} ${import_chalk2.default.dim(
+ "Using default value in non-interactive context:"
+ )} ${import_chalk2.default.white.bold(defaultValue ? "yes" : "no")}`
+ );
+ return defaultValue;
+ }
+ const { value } = await (0, import_prompts.default)({
+ type: "confirm",
+ name: "value",
+ message: text,
+ initial: defaultValue,
+ onState: (state) => {
+ if (state.aborted) {
+ process.nextTick(() => {
+ process.exit(1);
+ });
+ }
+ }
+ });
+ return value;
+}
+__name(confirm, "confirm");
+async function prompt(text, options14 = {}) {
+ if (isNonInteractiveOrCI()) {
+ if (options14?.defaultValue === void 0) {
+ throw new NoDefaultValueProvided();
+ }
+ logger.log(`? ${text}`);
+ logger.log(
+ `\u{1F916} ${import_chalk2.default.dim(
+ "Using default value in non-interactive context:"
+ )} ${import_chalk2.default.white.bold(options14.defaultValue)}`
+ );
+ return options14.defaultValue;
+ }
+ const { value } = await (0, import_prompts.default)({
+ type: "text",
+ name: "value",
+ message: text,
+ initial: options14?.defaultValue,
+ style: options14?.isSecret ? "password" : "default",
+ onState: (state) => {
+ if (state.aborted) {
+ process.nextTick(() => {
+ process.exit(1);
+ });
+ }
+ }
+ });
+ return value;
+}
+__name(prompt, "prompt");
+async function select(text, options14) {
+ if (isNonInteractiveOrCI()) {
+ if (options14?.defaultOption === void 0) {
+ throw new NoDefaultValueProvided();
+ }
+ logger.log(`? ${text}`);
+ logger.log(
+ `\u{1F916} ${import_chalk2.default.dim(
+ "Using default value in non-interactive context:"
+ )} ${import_chalk2.default.white.bold(options14.choices[options14.defaultOption].title)}`
+ );
+ return options14.choices[options14.defaultOption].value;
+ }
+ const { value } = await (0, import_prompts.default)({
+ type: "select",
+ name: "value",
+ message: text,
+ choices: options14.choices,
+ initial: options14.defaultOption,
+ onState: (state) => {
+ if (state.aborted) {
+ process.nextTick(() => {
+ process.exit(1);
+ });
+ }
+ }
+ });
+ return value;
+}
+__name(select, "select");
+
+// src/global-wrangler-config-path.ts
+init_import_meta_url();
+var import_node_fs2 = __toESM(require("node:fs"));
+var import_node_os2 = __toESM(require("node:os"));
+var import_node_path4 = __toESM(require("node:path"));
+
+// ../../node_modules/.pnpm/xdg-app-paths@7.3.0/node_modules/xdg-app-paths/dist/cjs/esm-wrapper/mod.esm.js
+var mod_esm_exports = {};
+__export(mod_esm_exports, {
+ default: () => mod_esm_default
+});
+init_import_meta_url();
+var import_mod_cjs = __toESM(require_mod_cjs3(), 1);
+__reExport(mod_esm_exports, __toESM(require_mod_cjs3(), 1));
+var mod_esm_default = import_mod_cjs.default;
+
+// src/global-wrangler-config-path.ts
+function isDirectory(configPath) {
+ try {
+ return import_node_fs2.default.statSync(configPath).isDirectory();
+ } catch (error) {
+ return false;
+ }
+}
+__name(isDirectory, "isDirectory");
+function getGlobalWranglerConfigPath() {
+ const configDir = mod_esm_default(".wrangler").config();
+ const legacyConfigDir = import_node_path4.default.join(import_node_os2.default.homedir(), ".wrangler");
+ if (isDirectory(legacyConfigDir)) {
+ return legacyConfigDir;
+ } else {
+ return configDir;
+ }
+}
+__name(getGlobalWranglerConfigPath, "getGlobalWranglerConfigPath");
+
+// src/open-in-browser.ts
+init_import_meta_url();
+var import_open = __toESM(require_open());
+async function openInBrowser(url3) {
+ const childProcess2 = await (0, import_open.default)(url3);
+ childProcess2.on("error", () => {
+ logger.warn("Failed to open");
+ });
+}
+__name(openInBrowser, "openInBrowser");
+
+// src/user/access.ts
+init_import_meta_url();
+var import_child_process = require("child_process");
+var import_undici = __toESM(require_undici());
+var cache = {};
+var usesAccessCache = /* @__PURE__ */ new Map();
+async function domainUsesAccess(domain) {
+ logger.debug("Checking if domain has Access enabled:", domain);
+ if (usesAccessCache.has(domain)) {
+ logger.debug(
+ "Using cached Access switch for:",
+ domain,
+ usesAccessCache.get(domain)
+ );
+ return usesAccessCache.get(domain);
+ }
+ logger.debug("Access switch not cached for:", domain);
+ try {
+ const controller = new AbortController();
+ const cancel2 = setTimeout(() => {
+ controller.abort();
+ }, 1e3);
+ const output = await (0, import_undici.fetch)(`https://${domain}`, {
+ redirect: "manual",
+ signal: controller.signal
+ });
+ clearTimeout(cancel2);
+ const usesAccess = !!(output.status === 302 && output.headers.get("location")?.includes("cloudflareaccess.com"));
+ logger.debug("Caching access switch for:", domain);
+ usesAccessCache.set(domain, usesAccess);
+ return usesAccess;
+ } catch (e2) {
+ usesAccessCache.set(domain, false);
+ return false;
+ }
+}
+__name(domainUsesAccess, "domainUsesAccess");
+async function getAccessToken(domain) {
+ if (!await domainUsesAccess(domain)) {
+ return void 0;
+ }
+ if (cache[domain]) {
+ return cache[domain];
+ }
+ const output = (0, import_child_process.spawnSync)("cloudflared", ["access", "login", domain]);
+ if (output.error) {
+ throw new Error(
+ "To use Wrangler with Cloudflare Access, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
+ );
+ }
+ const stringOutput = output.stdout.toString();
+ const matches = stringOutput.match(/fetched your token:\n\n(.*)/m);
+ if (matches && matches.length >= 2) {
+ cache[domain] = matches[1];
+ return matches[1];
+ }
+ throw new Error("Failed to authenticate with Cloudflare Access");
+}
+__name(getAccessToken, "getAccessToken");
+
+// src/user/auth-variables.ts
+init_import_meta_url();
+var getCloudflareAccountIdFromEnv = getEnvironmentVariableFactory({
+ variableName: "CLOUDFLARE_ACCOUNT_ID",
+ deprecatedName: "CF_ACCOUNT_ID"
+});
+var getCloudflareAPITokenFromEnv = getEnvironmentVariableFactory({
+ variableName: "CLOUDFLARE_API_TOKEN",
+ deprecatedName: "CF_API_TOKEN"
+});
+var getCloudflareGlobalAuthKeyFromEnv = getEnvironmentVariableFactory({
+ variableName: "CLOUDFLARE_API_KEY",
+ deprecatedName: "CF_API_KEY"
+});
+var getCloudflareGlobalAuthEmailFromEnv = getEnvironmentVariableFactory({
+ variableName: "CLOUDFLARE_EMAIL",
+ deprecatedName: "CF_EMAIL"
+});
+var getClientIdFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_CLIENT_ID",
+ defaultValue: () => getCloudflareApiEnvironmentFromEnv() === "staging" ? "4b2ea6cc-9421-4761-874b-ce550e0e3def" : "54d11594-84e4-41aa-b438-e81b8fa78ee7"
+});
+var getAuthDomainFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_AUTH_DOMAIN",
+ defaultValue: () => getCloudflareApiEnvironmentFromEnv() === "staging" ? "dash.staging.cloudflare.com" : "dash.cloudflare.com"
+});
+var getAuthUrlFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_AUTH_URL",
+ defaultValue: () => `https://${getAuthDomainFromEnv()}/oauth2/auth`
+});
+var getTokenUrlFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_TOKEN_URL",
+ defaultValue: () => `https://${getAuthDomainFromEnv()}/oauth2/token`
+});
+var getRevokeUrlFromEnv = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_REVOKE_URL",
+ defaultValue: () => `https://${getAuthDomainFromEnv()}/oauth2/revoke`
+});
+var getCloudflareAccessToken = /* @__PURE__ */ __name(async () => {
+ const env5 = getEnvironmentVariableFactory({
+ variableName: "WRANGLER_CF_AUTHORIZATION_TOKEN"
+ })();
+ if (env5 !== void 0) {
+ return env5;
+ }
+ return getAccessToken(getAuthDomainFromEnv());
+}, "getCloudflareAccessToken");
+
+// src/user/choose-account.tsx
+init_import_meta_url();
+async function getAccountChoices() {
+ const accountIdFromEnv = getCloudflareAccountIdFromEnv();
+ if (accountIdFromEnv) {
+ return [{ id: accountIdFromEnv, name: "" }];
+ } else {
+ try {
+ const response = await fetchListResult(`/memberships`);
+ const accounts = response.map((r) => r.account);
+ if (accounts.length === 0) {
+ throw new Error(
+ "Failed to automatically retrieve account IDs for the logged in user.\nIn a non-interactive environment, it is mandatory to specify an account ID, either by assigning its value to CLOUDFLARE_ACCOUNT_ID, or as `account_id` in your `wrangler.toml` file."
+ );
+ } else {
+ return accounts;
+ }
+ } catch (err) {
+ if (err.code === 9109) {
+ throw new Error(
+ `Failed to automatically retrieve account IDs for the logged in user.
+You may have incorrect permissions on your API token. You can skip this account check by adding an \`account_id\` in your \`wrangler.toml\`, or by setting the value of CLOUDFLARE_ACCOUNT_ID"`
+ );
+ } else
+ throw err;
+ }
+ }
+}
+__name(getAccountChoices, "getAccountChoices");
+
+// src/user/generate-auth-url.ts
+init_import_meta_url();
+var generateAuthUrl = /* @__PURE__ */ __name(({
+ authUrl,
+ clientId,
+ callbackUrl,
+ scopes,
+ stateQueryParam,
+ codeChallenge
+}) => {
+ return authUrl + `?response_type=code&client_id=${encodeURIComponent(clientId)}&redirect_uri=${encodeURIComponent(callbackUrl)}&scope=${encodeURIComponent([...scopes, "offline_access"].join(" "))}&state=${stateQueryParam}&code_challenge=${encodeURIComponent(codeChallenge)}&code_challenge_method=S256`;
+}, "generateAuthUrl");
+
+// src/user/generate-random-state.ts
+init_import_meta_url();
+var import_node_crypto = require("node:crypto");
+function generateRandomState(lengthOfState) {
+ const output = new Uint32Array(lengthOfState);
+ import_node_crypto.webcrypto.getRandomValues(output);
+ return Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("");
+}
+__name(generateRandomState, "generateRandomState");
+
+// src/user/user.ts
+function getAuthFromEnv() {
+ const globalApiKey = getCloudflareGlobalAuthKeyFromEnv();
+ const globalApiEmail = getCloudflareGlobalAuthEmailFromEnv();
+ const apiToken = getCloudflareAPITokenFromEnv();
+ if (globalApiKey && globalApiEmail) {
+ return { authKey: globalApiKey, authEmail: globalApiEmail };
+ } else if (apiToken) {
+ return { apiToken };
+ }
+}
+__name(getAuthFromEnv, "getAuthFromEnv");
+var USER_AUTH_CONFIG_FILE = "config/default.toml";
+var Scopes = {
+ "account:read": "See your account info such as account details, analytics, and memberships.",
+ "user:read": "See your user info such as name, email address, and account memberships.",
+ "workers:write": "See and change Cloudflare Workers data such as zones, KV storage, namespaces, scripts, and routes.",
+ "workers_kv:write": "See and change Cloudflare Workers KV Storage data such as keys and namespaces.",
+ "workers_routes:write": "See and change Cloudflare Workers data such as filters and routes.",
+ "workers_scripts:write": "See and change Cloudflare Workers scripts, durable objects, subdomains, triggers, and tail data.",
+ "workers_tail:read": "See Cloudflare Workers tail and script data.",
+ "d1:write": "See and change D1 Databases.",
+ "pages:write": "See and change Cloudflare Pages projects, settings and deployments.",
+ "zone:read": "Grants read level access to account zone.",
+ "ssl_certs:write": "See and manage mTLS certificates for your account",
+ "constellation:write": "Manage Constellation projects/models"
+};
+var ScopeKeys = Object.keys(Scopes);
+function validateScopeKeys(scopes) {
+ return scopes.every((scope) => scope in Scopes);
+}
+__name(validateScopeKeys, "validateScopeKeys");
+var CALLBACK_URL = "http://localhost:8976/oauth/callback";
+var LocalState = {
+ ...getAuthTokens()
+};
+function getAuthTokens(config) {
+ try {
+ if (getAuthFromEnv())
+ return;
+ const { oauth_token, refresh_token, expiration_time, scopes, api_token } = config || readAuthConfigFile();
+ if (oauth_token) {
+ return {
+ accessToken: {
+ value: oauth_token,
+ // If there is no `expiration_time` field then set it to an old date, to cause it to expire immediately.
+ expiry: expiration_time ?? "2000-01-01:00:00:00+00:00"
+ },
+ refreshToken: { value: refresh_token ?? "" },
+ scopes
+ };
+ } else if (api_token) {
+ logger.warn(
+ "It looks like you have used Wrangler v1's `config` command to login with an API token.\nThis is no longer supported in the current version of Wrangler.\nIf you wish to authenticate via an API token then please set the `CLOUDFLARE_API_TOKEN` environment variable."
+ );
+ return { apiToken: api_token };
+ }
+ } catch {
+ return void 0;
+ }
+}
+__name(getAuthTokens, "getAuthTokens");
+function reinitialiseAuthTokens(config) {
+ LocalState = {
+ ...getAuthTokens(config)
+ };
+}
+__name(reinitialiseAuthTokens, "reinitialiseAuthTokens");
+function getAPIToken() {
+ if (LocalState.apiToken) {
+ return { apiToken: LocalState.apiToken };
+ }
+ const localAPIToken = getAuthFromEnv();
+ if (localAPIToken)
+ return localAPIToken;
+ const storedAccessToken = LocalState.accessToken?.value;
+ if (storedAccessToken)
+ return { apiToken: storedAccessToken };
+ return void 0;
+}
+__name(getAPIToken, "getAPIToken");
+var ErrorOAuth2 = class extends Error {
+ toString() {
+ return "ErrorOAuth2";
+ }
+};
+__name(ErrorOAuth2, "ErrorOAuth2");
+var ErrorUnknown = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorUnknown";
+ }
+};
+__name(ErrorUnknown, "ErrorUnknown");
+var ErrorNoAuthCode = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorNoAuthCode";
+ }
+};
+__name(ErrorNoAuthCode, "ErrorNoAuthCode");
+var ErrorInvalidReturnedStateParam = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorInvalidReturnedStateParam";
+ }
+};
+__name(ErrorInvalidReturnedStateParam, "ErrorInvalidReturnedStateParam");
+var ErrorInvalidJson = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorInvalidJson";
+ }
+};
+__name(ErrorInvalidJson, "ErrorInvalidJson");
+var ErrorInvalidScope = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorInvalidScope";
+ }
+};
+__name(ErrorInvalidScope, "ErrorInvalidScope");
+var ErrorInvalidRequest = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorInvalidRequest";
+ }
+};
+__name(ErrorInvalidRequest, "ErrorInvalidRequest");
+var ErrorInvalidToken = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorInvalidToken";
+ }
+};
+__name(ErrorInvalidToken, "ErrorInvalidToken");
+var ErrorAuthenticationGrant = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorAuthenticationGrant";
+ }
+};
+__name(ErrorAuthenticationGrant, "ErrorAuthenticationGrant");
+var ErrorUnauthorizedClient = class extends ErrorAuthenticationGrant {
+ toString() {
+ return "ErrorUnauthorizedClient";
+ }
+};
+__name(ErrorUnauthorizedClient, "ErrorUnauthorizedClient");
+var ErrorAccessDenied = class extends ErrorAuthenticationGrant {
+ toString() {
+ return "ErrorAccessDenied";
+ }
+};
+__name(ErrorAccessDenied, "ErrorAccessDenied");
+var ErrorUnsupportedResponseType = class extends ErrorAuthenticationGrant {
+ toString() {
+ return "ErrorUnsupportedResponseType";
+ }
+};
+__name(ErrorUnsupportedResponseType, "ErrorUnsupportedResponseType");
+var ErrorServerError = class extends ErrorAuthenticationGrant {
+ toString() {
+ return "ErrorServerError";
+ }
+};
+__name(ErrorServerError, "ErrorServerError");
+var ErrorTemporarilyUnavailable = class extends ErrorAuthenticationGrant {
+ toString() {
+ return "ErrorTemporarilyUnavailable";
+ }
+};
+__name(ErrorTemporarilyUnavailable, "ErrorTemporarilyUnavailable");
+var ErrorAccessTokenResponse = class extends ErrorOAuth2 {
+ toString() {
+ return "ErrorAccessTokenResponse";
+ }
+};
+__name(ErrorAccessTokenResponse, "ErrorAccessTokenResponse");
+var ErrorInvalidClient = class extends ErrorAccessTokenResponse {
+ toString() {
+ return "ErrorInvalidClient";
+ }
+};
+__name(ErrorInvalidClient, "ErrorInvalidClient");
+var ErrorInvalidGrant = class extends ErrorAccessTokenResponse {
+ toString() {
+ return "ErrorInvalidGrant";
+ }
+};
+__name(ErrorInvalidGrant, "ErrorInvalidGrant");
+var ErrorUnsupportedGrantType = class extends ErrorAccessTokenResponse {
+ toString() {
+ return "ErrorUnsupportedGrantType";
+ }
+};
+__name(ErrorUnsupportedGrantType, "ErrorUnsupportedGrantType");
+var RawErrorToErrorClassMap = {
+ invalid_request: ErrorInvalidRequest,
+ invalid_grant: ErrorInvalidGrant,
+ unauthorized_client: ErrorUnauthorizedClient,
+ access_denied: ErrorAccessDenied,
+ unsupported_response_type: ErrorUnsupportedResponseType,
+ invalid_scope: ErrorInvalidScope,
+ server_error: ErrorServerError,
+ temporarily_unavailable: ErrorTemporarilyUnavailable,
+ invalid_client: ErrorInvalidClient,
+ unsupported_grant_type: ErrorUnsupportedGrantType,
+ invalid_json: ErrorInvalidJson,
+ invalid_token: ErrorInvalidToken
+};
+function toErrorClass(rawError) {
+ return new (RawErrorToErrorClassMap[rawError] || ErrorUnknown)();
+}
+__name(toErrorClass, "toErrorClass");
+var RECOMMENDED_CODE_VERIFIER_LENGTH = 96;
+var RECOMMENDED_STATE_LENGTH = 32;
+var PKCE_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";
+function isReturningFromAuthServer(query) {
+ if (query.error) {
+ if (Array.isArray(query.error)) {
+ throw toErrorClass(query.error[0]);
+ }
+ throw toErrorClass(query.error);
+ }
+ const code = query.code;
+ if (!code) {
+ return false;
+ }
+ const state = LocalState;
+ const stateQueryParam = query.state;
+ if (stateQueryParam !== state.stateQueryParam) {
+ logger.warn(
+ "Received query string parameter doesn't match the one sent! Possible malicious activity somewhere."
+ );
+ throw new ErrorInvalidReturnedStateParam();
+ }
+ (0, import_node_assert.default)(!Array.isArray(code));
+ state.authorizationCode = code;
+ state.hasAuthCodeBeenExchangedForAccessToken = false;
+ return true;
+}
+__name(isReturningFromAuthServer, "isReturningFromAuthServer");
+async function getAuthURL(scopes = ScopeKeys) {
+ const { codeChallenge, codeVerifier } = await generatePKCECodes();
+ const stateQueryParam = generateRandomState(RECOMMENDED_STATE_LENGTH);
+ Object.assign(LocalState, {
+ codeChallenge,
+ codeVerifier,
+ stateQueryParam
+ });
+ return generateAuthUrl({
+ authUrl: getAuthUrlFromEnv(),
+ clientId: getClientIdFromEnv(),
+ callbackUrl: CALLBACK_URL,
+ scopes,
+ stateQueryParam,
+ codeChallenge
+ });
+}
+__name(getAuthURL, "getAuthURL");
+async function exchangeRefreshTokenForAccessToken() {
+ if (!LocalState.refreshToken) {
+ logger.warn("No refresh token is present.");
+ }
+ const params = new URLSearchParams({
+ grant_type: "refresh_token",
+ refresh_token: LocalState.refreshToken?.value ?? "",
+ client_id: getClientIdFromEnv()
+ });
+ const response = await fetchAuthToken(params);
+ if (response.status >= 400) {
+ let tokenExchangeResErr = void 0;
+ try {
+ tokenExchangeResErr = await response.text();
+ tokenExchangeResErr = JSON.parse(tokenExchangeResErr);
+ } catch (e2) {
+ }
+ if (tokenExchangeResErr !== void 0) {
+ throw typeof tokenExchangeResErr === "string" ? new Error(tokenExchangeResErr) : tokenExchangeResErr;
+ } else {
+ throw new ErrorUnknown(
+ "Failed to parse Error from exchangeRefreshTokenForAccessToken"
+ );
+ }
+ } else {
+ try {
+ const json = await response.json();
+ if ("error" in json) {
+ throw json.error;
+ }
+ const { access_token, expires_in, refresh_token, scope } = json;
+ let scopes = [];
+ const accessToken = {
+ value: access_token,
+ expiry: new Date(Date.now() + expires_in * 1e3).toISOString()
+ };
+ LocalState.accessToken = accessToken;
+ if (refresh_token) {
+ LocalState.refreshToken = {
+ value: refresh_token
+ };
+ }
+ if (scope) {
+ scopes = scope.split(" ");
+ LocalState.scopes = scopes;
+ }
+ const accessContext = {
+ token: accessToken,
+ scopes,
+ refreshToken: LocalState.refreshToken
+ };
+ return accessContext;
+ } catch (error) {
+ if (typeof error === "string") {
+ throw toErrorClass(error);
+ } else {
+ throw error;
+ }
+ }
+ }
+}
+__name(exchangeRefreshTokenForAccessToken, "exchangeRefreshTokenForAccessToken");
+async function exchangeAuthCodeForAccessToken() {
+ const { authorizationCode, codeVerifier = "" } = LocalState;
+ if (!codeVerifier) {
+ logger.warn("No code verifier is being sent.");
+ } else if (!authorizationCode) {
+ logger.warn("No authorization grant code is being passed.");
+ }
+ const params = new URLSearchParams({
+ grant_type: `authorization_code`,
+ code: authorizationCode ?? "",
+ redirect_uri: CALLBACK_URL,
+ client_id: getClientIdFromEnv(),
+ code_verifier: codeVerifier
+ });
+ const response = await fetchAuthToken(params);
+ if (!response.ok) {
+ const { error } = await response.json();
+ if (error === "invalid_grant") {
+ logger.log("Expired! Auth code or refresh token needs to be renewed.");
+ }
+ throw toErrorClass(error);
+ }
+ const json = await response.json();
+ if ("error" in json) {
+ throw new Error(json.error);
+ }
+ const { access_token, expires_in, refresh_token, scope } = json;
+ let scopes = [];
+ LocalState.hasAuthCodeBeenExchangedForAccessToken = true;
+ const expiryDate = new Date(Date.now() + expires_in * 1e3);
+ const accessToken = {
+ value: access_token,
+ expiry: expiryDate.toISOString()
+ };
+ LocalState.accessToken = accessToken;
+ if (refresh_token) {
+ LocalState.refreshToken = {
+ value: refresh_token
+ };
+ }
+ if (scope) {
+ scopes = scope.split(" ");
+ LocalState.scopes = scopes;
+ }
+ const accessContext = {
+ token: accessToken,
+ scopes,
+ refreshToken: LocalState.refreshToken
+ };
+ return accessContext;
+}
+__name(exchangeAuthCodeForAccessToken, "exchangeAuthCodeForAccessToken");
+function base64urlEncode(value) {
+ let base64 = btoa(value);
+ base64 = base64.replace(/\+/g, "-");
+ base64 = base64.replace(/\//g, "_");
+ base64 = base64.replace(/=/g, "");
+ return base64;
+}
+__name(base64urlEncode, "base64urlEncode");
+async function generatePKCECodes() {
+ const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
+ import_node_crypto2.webcrypto.getRandomValues(output);
+ const codeVerifier = base64urlEncode(
+ Array.from(output).map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length]).join("")
+ );
+ const buffer = await import_node_crypto2.webcrypto.subtle.digest(
+ "SHA-256",
+ new import_node_util2.TextEncoder().encode(codeVerifier)
+ );
+ const hash = new Uint8Array(buffer);
+ let binary = "";
+ const hashLength = hash.byteLength;
+ for (let i = 0; i < hashLength; i++) {
+ binary += String.fromCharCode(hash[i]);
+ }
+ const codeChallenge = base64urlEncode(binary);
+ return { codeChallenge, codeVerifier };
+}
+__name(generatePKCECodes, "generatePKCECodes");
+function writeAuthConfigFile(config) {
+ const authConfigFilePath = import_node_path5.default.join(
+ getGlobalWranglerConfigPath(),
+ USER_AUTH_CONFIG_FILE
+ );
+ (0, import_node_fs3.mkdirSync)(import_node_path5.default.dirname(authConfigFilePath), {
+ recursive: true
+ });
+ (0, import_node_fs3.writeFileSync)(
+ import_node_path5.default.join(authConfigFilePath),
+ import_toml2.default.stringify(config),
+ { encoding: "utf-8" }
+ );
+ reinitialiseAuthTokens();
+}
+__name(writeAuthConfigFile, "writeAuthConfigFile");
+function readAuthConfigFile() {
+ const authConfigFilePath = import_node_path5.default.join(
+ getGlobalWranglerConfigPath(),
+ USER_AUTH_CONFIG_FILE
+ );
+ const toml = parseTOML(readFileSync5(authConfigFilePath));
+ return toml;
+}
+__name(readAuthConfigFile, "readAuthConfigFile");
+async function loginOrRefreshIfRequired() {
+ const { isCI: isCI2 } = CI;
+ if (!getAPIToken()) {
+ return isInteractive() && !isCI2() && await login();
+ } else if (isAccessTokenExpired()) {
+ const didRefresh = await refreshToken();
+ if (didRefresh) {
+ return true;
+ } else {
+ return isInteractive() && !isCI2() && await login();
+ }
+ } else {
+ return true;
+ }
+}
+__name(loginOrRefreshIfRequired, "loginOrRefreshIfRequired");
+async function login(props = { browser: true }) {
+ logger.log("Attempting to login via OAuth...");
+ const urlToOpen = await getAuthURL(props?.scopes);
+ let server2;
+ let loginTimeoutHandle;
+ const timerPromise = new Promise((resolve18) => {
+ loginTimeoutHandle = setTimeout(() => {
+ logger.error(
+ "Timed out waiting for authorization code, please try again."
+ );
+ server2.close();
+ clearTimeout(loginTimeoutHandle);
+ resolve18(false);
+ }, 12e4);
+ });
+ const loginPromise = new Promise((resolve18, reject) => {
+ server2 = import_node_http.default.createServer(async (req, res) => {
+ function finish(status, error) {
+ clearTimeout(loginTimeoutHandle);
+ server2.close((closeErr) => {
+ if (error || closeErr) {
+ reject(error || closeErr);
+ } else
+ resolve18(status);
+ });
+ }
+ __name(finish, "finish");
+ (0, import_node_assert.default)(req.url, "This request doesn't have a URL");
+ const { pathname, query } = import_node_url3.default.parse(req.url, true);
+ switch (pathname) {
+ case "/oauth/callback": {
+ let hasAuthCode = false;
+ try {
+ hasAuthCode = isReturningFromAuthServer(query);
+ } catch (err) {
+ if (err instanceof ErrorAccessDenied) {
+ res.writeHead(307, {
+ Location: "https://welcome.developers.workers.dev/wrangler-oauth-consent-denied"
+ });
+ res.end(() => {
+ finish(false);
+ });
+ logger.error(
+ "Error: Consent denied. You must grant consent to Wrangler in order to login.\nIf you don't want to do this consider passing an API token via the `CLOUDFLARE_API_TOKEN` environment variable"
+ );
+ return;
+ } else {
+ finish(false, err);
+ return;
+ }
+ }
+ if (!hasAuthCode) {
+ finish(false, new ErrorNoAuthCode());
+ return;
+ } else {
+ const exchange = await exchangeAuthCodeForAccessToken();
+ writeAuthConfigFile({
+ oauth_token: exchange.token?.value ?? "",
+ expiration_time: exchange.token?.expiry,
+ refresh_token: exchange.refreshToken?.value,
+ scopes: exchange.scopes
+ });
+ res.writeHead(307, {
+ Location: "https://welcome.developers.workers.dev/wrangler-oauth-consent-granted"
+ });
+ res.end(() => {
+ finish(true);
+ });
+ logger.log(`Successfully logged in.`);
+ purgeConfigCaches();
+ return;
+ }
+ }
+ }
+ });
+ server2.listen(8976);
+ });
+ if (props?.browser) {
+ logger.log(`Opening a link in your default browser: ${urlToOpen}`);
+ await openInBrowser(urlToOpen);
+ } else {
+ logger.log(`Visit this link to authenticate: ${urlToOpen}`);
+ }
+ return Promise.race([timerPromise, loginPromise]);
+}
+__name(login, "login");
+function isAccessTokenExpired() {
+ const { accessToken } = LocalState;
+ return Boolean(accessToken && /* @__PURE__ */ new Date() >= new Date(accessToken.expiry));
+}
+__name(isAccessTokenExpired, "isAccessTokenExpired");
+async function refreshToken() {
+ try {
+ const {
+ token: { value: oauth_token, expiry: expiration_time } = {
+ value: "",
+ expiry: ""
+ },
+ refreshToken: { value: refresh_token } = {},
+ scopes
+ } = await exchangeRefreshTokenForAccessToken();
+ writeAuthConfigFile({
+ oauth_token,
+ expiration_time,
+ refresh_token,
+ scopes
+ });
+ return true;
+ } catch (err) {
+ return false;
+ }
+}
+__name(refreshToken, "refreshToken");
+async function logout() {
+ if (!LocalState.accessToken) {
+ if (!LocalState.refreshToken) {
+ logger.log("Not logged in, exiting...");
+ return;
+ }
+ const body2 = `client_id=${encodeURIComponent(getClientIdFromEnv())}&token_type_hint=refresh_token&token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
+ const response2 = await (0, import_undici2.fetch)(getRevokeUrlFromEnv(), {
+ method: "POST",
+ body: body2,
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded"
+ }
+ });
+ await response2.text();
+ logger.log(
+ "\u{1F481} Wrangler is configured with an OAuth token. The token has been successfully revoked"
+ );
+ }
+ const body = `client_id=${encodeURIComponent(getClientIdFromEnv())}&token_type_hint=refresh_token&token=${encodeURIComponent(LocalState.refreshToken?.value || "")}`;
+ const response = await (0, import_undici2.fetch)(getRevokeUrlFromEnv(), {
+ method: "POST",
+ body,
+ headers: {
+ "Content-Type": "application/x-www-form-urlencoded"
+ }
+ });
+ await response.text();
+ (0, import_node_fs3.rmSync)(import_node_path5.default.join(getGlobalWranglerConfigPath(), USER_AUTH_CONFIG_FILE));
+ logger.log(`Successfully logged out.`);
+}
+__name(logout, "logout");
+function listScopes(message = "\u{1F481} Available scopes:") {
+ logger.log(message);
+ const data = ScopeKeys.map((scope) => ({
+ Scope: scope,
+ Description: Scopes[scope]
+ }));
+ logger.table(data);
+}
+__name(listScopes, "listScopes");
+async function getAccountId() {
+ const apiToken = getAPIToken();
+ if (!apiToken)
+ return;
+ const cachedAccount = getAccountFromCache();
+ if (cachedAccount && !getCloudflareAccountIdFromEnv()) {
+ return cachedAccount.id;
+ }
+ const accounts = await getAccountChoices();
+ if (accounts.length === 1) {
+ saveAccountToCache({ id: accounts[0].id, name: accounts[0].name });
+ return accounts[0].id;
+ }
+ try {
+ const accountID = await select("Select an account", {
+ choices: accounts.map((account2) => ({
+ title: account2.name,
+ value: account2.id
+ }))
+ });
+ const account = accounts.find(
+ (a) => a.id === accountID
+ );
+ saveAccountToCache({ id: account.id, name: account.name });
+ return accountID;
+ } catch (e2) {
+ if (e2 instanceof NoDefaultValueProvided) {
+ throw new Error(
+ `More than one account available but unable to select one in non-interactive mode.
+Please set the appropriate \`account_id\` in your \`wrangler.toml\` file.
+Available accounts are (\`\`: \`\`):
+${accounts.map((account) => ` \`${account.name}\`: \`${account.id}\``).join("\n")}`
+ );
+ }
+ throw e2;
+ }
+}
+__name(getAccountId, "getAccountId");
+async function requireAuth(config) {
+ const loggedIn = await loginOrRefreshIfRequired();
+ if (!loggedIn) {
+ if (!isInteractive() || CI.isCI()) {
+ throw new Error(
+ "In a non-interactive environment, it's necessary to set a CLOUDFLARE_API_TOKEN environment variable for wrangler to work. Please go to https://developers.cloudflare.com/fundamentals/api/get-started/create-token/ for instructions on how to create an api token, and assign its value to CLOUDFLARE_API_TOKEN."
+ );
+ } else {
+ throw new Error("Did not login, quitting...");
+ }
+ }
+ const accountId = config.account_id || await getAccountId();
+ if (!accountId) {
+ throw new Error("No account id found, quitting...");
+ }
+ return accountId;
+}
+__name(requireAuth, "requireAuth");
+function requireApiToken() {
+ const credentials = getAPIToken();
+ if (!credentials) {
+ throw new Error("No API token found.");
+ }
+ return credentials;
+}
+__name(requireApiToken, "requireApiToken");
+function saveAccountToCache(account) {
+ saveToConfigCache(
+ "wrangler-account.json",
+ { account }
+ );
+}
+__name(saveAccountToCache, "saveAccountToCache");
+function getAccountFromCache() {
+ return getConfigCache(
+ "wrangler-account.json"
+ ).account;
+}
+__name(getAccountFromCache, "getAccountFromCache");
+function getScopes() {
+ return LocalState.scopes;
+}
+__name(getScopes, "getScopes");
+async function fetchAuthToken(body) {
+ const headers = {
+ "Content-Type": "application/x-www-form-urlencoded"
+ };
+ if (await domainUsesAccess(getAuthDomainFromEnv())) {
+ headers["Cookie"] = `CF_Authorization=${await getCloudflareAccessToken()}`;
+ }
+ return await (0, import_undici2.fetch)(getTokenUrlFromEnv(), {
+ method: "POST",
+ body: body.toString(),
+ headers
+ });
+}
+__name(fetchAuthToken, "fetchAuthToken");
+
+// src/cfetch/internal.ts
+async function performApiFetch(resource, init = {}, queryParams, abortSignal) {
+ const method = init.method ?? "GET";
+ (0, import_node_assert2.default)(
+ resource.startsWith("/"),
+ `CF API fetch - resource path must start with a "/" but got "${resource}"`
+ );
+ await requireLoggedIn();
+ const apiToken = requireApiToken();
+ const headers = cloneHeaders(init.headers);
+ addAuthorizationHeaderIfUnspecified(headers, apiToken);
+ addUserAgent(headers);
+ const queryString = queryParams ? `?${queryParams.toString()}` : "";
+ logger.debug(
+ `-- START CF API REQUEST: ${method} ${getCloudflareApiBaseUrl()}${resource}${queryString}`
+ );
+ const logHeaders = cloneHeaders(headers);
+ delete logHeaders["Authorization"];
+ logger.debug("HEADERS:", JSON.stringify(logHeaders, null, 2));
+ logger.debug(
+ "INIT:",
+ JSON.stringify({ ...init, headers: logHeaders }, null, 2)
+ );
+ logger.debug("-- END CF API REQUEST");
+ return await (0, import_undici3.fetch)(`${getCloudflareApiBaseUrl()}${resource}${queryString}`, {
+ method,
+ ...init,
+ headers,
+ signal: abortSignal
+ });
+}
+__name(performApiFetch, "performApiFetch");
+async function fetchInternal(resource, init = {}, queryParams, abortSignal) {
+ const method = init.method ?? "GET";
+ const response = await performApiFetch(
+ resource,
+ init,
+ queryParams,
+ abortSignal
+ );
+ const jsonText = await response.text();
+ logger.debug(
+ "-- START CF API RESPONSE:",
+ response.statusText,
+ response.status
+ );
+ const logHeaders = cloneHeaders(response.headers);
+ delete logHeaders["Authorization"];
+ logger.debug("HEADERS:", JSON.stringify(logHeaders, null, 2));
+ logger.debug("RESPONSE:", jsonText);
+ logger.debug("-- END CF API RESPONSE");
+ try {
+ return parseJSON(jsonText);
+ } catch (err) {
+ throw new ParseError({
+ text: "Received a malformed response from the API",
+ notes: [
+ {
+ text: truncate(jsonText, 100)
+ },
+ {
+ text: `${method} ${resource} -> ${response.status} ${response.statusText}`
+ }
+ ]
+ });
+ }
+}
+__name(fetchInternal, "fetchInternal");
+function truncate(text, maxLength) {
+ const { length } = text;
+ if (length <= maxLength) {
+ return text;
+ }
+ return `${text.substring(0, maxLength)}... (length = ${length})`;
+}
+__name(truncate, "truncate");
+function cloneHeaders(headers) {
+ return headers instanceof import_undici3.Headers ? Object.fromEntries(headers.entries()) : Array.isArray(headers) ? Object.fromEntries(headers) : { ...headers };
+}
+__name(cloneHeaders, "cloneHeaders");
+async function requireLoggedIn() {
+ const loggedIn = await loginOrRefreshIfRequired();
+ if (!loggedIn) {
+ throw new Error("Not logged in.");
+ }
+}
+__name(requireLoggedIn, "requireLoggedIn");
+function addAuthorizationHeaderIfUnspecified(headers, auth) {
+ if (!("Authorization" in headers)) {
+ if ("apiToken" in auth) {
+ headers["Authorization"] = `Bearer ${auth.apiToken}`;
+ } else {
+ headers["X-Auth-Key"] = auth.authKey;
+ headers["X-Auth-Email"] = auth.authEmail;
+ }
+ }
+}
+__name(addAuthorizationHeaderIfUnspecified, "addAuthorizationHeaderIfUnspecified");
+function addUserAgent(headers) {
+ headers["User-Agent"] = `wrangler/${version}`;
+}
+__name(addUserAgent, "addUserAgent");
+async function fetchKVGetValue(accountId, namespaceId, key) {
+ await requireLoggedIn();
+ const auth = requireApiToken();
+ const headers = {};
+ addAuthorizationHeaderIfUnspecified(headers, auth);
+ const resource = `${getCloudflareApiBaseUrl()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
+ const response = await (0, import_undici3.fetch)(resource, {
+ method: "GET",
+ headers
+ });
+ if (response.ok) {
+ return await response.arrayBuffer();
+ } else {
+ throw new Error(
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
+ );
+ }
+}
+__name(fetchKVGetValue, "fetchKVGetValue");
+async function fetchR2Objects(resource, bodyInit = {}) {
+ await requireLoggedIn();
+ const auth = requireApiToken();
+ const headers = cloneHeaders(bodyInit.headers);
+ addAuthorizationHeaderIfUnspecified(headers, auth);
+ addUserAgent(headers);
+ const response = await (0, import_undici3.fetch)(`${getCloudflareApiBaseUrl()}${resource}`, {
+ ...bodyInit,
+ headers
+ });
+ if (response.ok && response.body) {
+ return response;
+ } else {
+ throw new Error(
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
+ );
+ }
+}
+__name(fetchR2Objects, "fetchR2Objects");
+async function fetchDashboardScript(resource, bodyInit = {}) {
+ await requireLoggedIn();
+ const auth = requireApiToken();
+ const headers = cloneHeaders(bodyInit.headers);
+ addAuthorizationHeaderIfUnspecified(headers, auth);
+ addUserAgent(headers);
+ let response = await (0, import_undici3.fetch)(`${getCloudflareApiBaseUrl()}${resource}`, {
+ ...bodyInit,
+ headers
+ });
+ if (!response.ok || !response.body) {
+ console.error(response.ok, response.body);
+ throw new Error(
+ `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
+ );
+ }
+ const usesModules = response.headers.get("content-type")?.startsWith("multipart");
+ if (usesModules) {
+ if (!response.formData) {
+ response = new import_undici4.Response(await response.text(), response);
+ }
+ const form = await response.formData();
+ const files = Array.from(form.entries()).map(
+ ([filename, contents]) => contents instanceof import_undici3.File ? contents : new import_undici3.File([contents], filename)
+ );
+ return files;
+ } else {
+ const contents = await response.text();
+ const filename = response.headers.get("cf-entrypoint") ?? "index.js";
+ const file = new import_undici3.File([contents], filename, { type: "text" });
+ return [file];
+ }
+}
+__name(fetchDashboardScript, "fetchDashboardScript");
+
+// src/cfetch/index.ts
+async function fetchResult(resource, init = {}, queryParams, abortSignal) {
+ const json = await fetchInternal(
+ resource,
+ init,
+ queryParams,
+ abortSignal
+ );
+ if (json.success) {
+ return json.result;
+ } else {
+ throwFetchError(resource, json);
+ }
+}
+__name(fetchResult, "fetchResult");
+async function fetchGraphqlResult(init = {}, abortSignal) {
+ const json = await fetchInternal(
+ "/graphql",
+ { ...init, method: "POST" },
+ //Cloudflare API v4 doesn't allow GETs to /graphql
+ void 0,
+ abortSignal
+ );
+ if (json) {
+ return json;
+ } else {
+ throw new Error("A request to the Cloudflare API (/graphql) failed.");
+ }
+}
+__name(fetchGraphqlResult, "fetchGraphqlResult");
+async function fetchListResult(resource, init = {}, queryParams) {
+ const results = [];
+ let getMoreResults = true;
+ let cursor;
+ while (getMoreResults) {
+ if (cursor) {
+ queryParams = new import_node_url4.URLSearchParams(queryParams);
+ queryParams.set("cursor", cursor);
+ }
+ const json = await fetchInternal(
+ resource,
+ init,
+ queryParams
+ );
+ if (json.success) {
+ results.push(...json.result);
+ if (hasCursor(json.result_info)) {
+ cursor = json.result_info?.cursor;
+ } else {
+ getMoreResults = false;
+ }
+ } else {
+ throwFetchError(resource, json);
+ }
+ }
+ return results;
+}
+__name(fetchListResult, "fetchListResult");
+function throwFetchError(resource, response) {
+ const error = new ParseError({
+ text: `A request to the Cloudflare API (${resource}) failed.`,
+ notes: response.errors.map((err) => ({
+ text: renderError(err)
+ }))
+ });
+ const code = response.errors[0]?.code;
+ if (code) {
+ error.code = code;
+ }
+ throw error;
+}
+__name(throwFetchError, "throwFetchError");
+function hasCursor(result_info) {
+ const cursor = result_info?.cursor;
+ return cursor !== void 0 && cursor !== null && cursor !== "";
+}
+__name(hasCursor, "hasCursor");
+function renderError(err, level = 0) {
+ const chainedMessages = err.error_chain?.map(
+ (chainedError) => `
+${" ".repeat(level)}- ${renderError(chainedError, level + 1)}`
+ ).join("\n") ?? "";
+ return (err.code ? `${err.message} [code: ${err.code}]` : err.message) + chainedMessages;
+}
+__name(renderError, "renderError");
+async function fetchScriptContent(resource, init = {}, queryParams, abortSignal) {
+ const response = await performApiFetch(
+ resource,
+ init,
+ queryParams,
+ abortSignal
+ );
+ logger.debug(
+ "-- START CF API RESPONSE:",
+ response.statusText,
+ response.status
+ );
+ logger.debug("HEADERS:", { ...response.headers });
+ logger.debug("-- END CF API RESPONSE");
+ const contentType = response.headers.get("content-type");
+ const usesModules = contentType?.startsWith("multipart");
+ if (usesModules && contentType) {
+ const form = await response.formData();
+ const entries = Array.from(form.entries());
+ return entries.map((e2) => e2[1]).join("\n");
+ } else {
+ return await response.text();
+ }
+}
+__name(fetchScriptContent, "fetchScriptContent");
+
+// src/constellation/utils.ts
+var getConstellationWarningFromEnv = getEnvironmentVariableFactory({
+ variableName: "NO_CONSTELLATION_WARNING"
+});
+var constellationBetaWarning = getConstellationWarningFromEnv() !== void 0 ? "" : "--------------------\n\u{1F6A7} Constellation is currently in open alpha and is not recommended for production data and traffic\n\u{1F6A7} Please report any bugs to https://github.com/cloudflare/workers-sdk/issues/new/choose\n\u{1F6A7} To give feedback, visit https://discord.gg/cloudflaredev\n--------------------\n";
+var getProjectByName = /* @__PURE__ */ __name(async (config, accountId, name) => {
+ const allProjects = await listProjects(accountId);
+ const matchingProj = allProjects.find((proj) => proj.name === name);
+ if (!matchingProj) {
+ throw new Error(`Couldn't find Project with name '${name}'`);
+ }
+ return matchingProj;
+}, "getProjectByName");
+var getProjectModelByName = /* @__PURE__ */ __name(async (config, accountId, proj, modelName) => {
+ const allModels = await listModels(accountId, proj);
+ const matchingModel = allModels.find((model) => model.name === modelName);
+ if (!matchingModel) {
+ throw new Error(`Couldn't find Model with name '${modelName}'`);
+ }
+ return matchingModel;
+}, "getProjectModelByName");
+async function constellationList(accountId, partialUrl) {
+ const pageSize = 50;
+ let page = 1;
+ const results = [];
+ while (results.length % pageSize === 0) {
+ const json = await fetchResult(
+ `/accounts/${accountId}/constellation/${partialUrl}`,
+ {},
+ new URLSearchParams({
+ per_page: pageSize.toString(),
+ page: page.toString()
+ })
+ );
+ page++;
+ results.push(...json);
+ if (json.length < pageSize) {
+ break;
+ }
+ }
+ return results;
+}
+__name(constellationList, "constellationList");
+var listCatalogEntries = /* @__PURE__ */ __name(async (accountId) => {
+ return await constellationList(accountId, "catalog");
+}, "listCatalogEntries");
+var listModels = /* @__PURE__ */ __name(async (accountId, proj) => {
+ return constellationList(accountId, `project/${proj.id}/model`);
+}, "listModels");
+var listProjects = /* @__PURE__ */ __name(async (accountId) => {
+ return await constellationList(accountId, "project");
+}, "listProjects");
+var listRuntimes = /* @__PURE__ */ __name(async (accountId) => {
+ return await constellationList(accountId, "runtime");
+}, "listRuntimes");
+
+// src/config/diagnostics.ts
+init_import_meta_url();
+var Diagnostics = class {
+ /**
+ * Create a new Diagnostics object.
+ * @param description A general description of this collection of messages.
+ */
+ constructor(description) {
+ this.description = description;
+ }
+ errors = [];
+ warnings = [];
+ children = [];
+ /**
+ * Merge the given `diagnostics` into this as a child.
+ */
+ addChild(diagnostics) {
+ if (diagnostics.hasErrors() || diagnostics.hasWarnings()) {
+ this.children.push(diagnostics);
+ }
+ }
+ /** Does this or any of its children have errors. */
+ hasErrors() {
+ if (this.errors.length > 0) {
+ return true;
+ } else {
+ return this.children.some((child) => child.hasErrors());
+ }
+ }
+ /** Render the errors of this and all its children. */
+ renderErrors() {
+ return this.render("errors");
+ }
+ /** Does this or any of its children have warnings. */
+ hasWarnings() {
+ if (this.warnings.length > 0) {
+ return true;
+ } else {
+ return this.children.some((child) => child.hasWarnings());
+ }
+ }
+ /** Render the warnings of this and all its children. */
+ renderWarnings() {
+ return this.render("warnings");
+ }
+ render(field) {
+ const hasMethod = field === "errors" ? "hasErrors" : "hasWarnings";
+ return indentText(
+ `${this.description}
+` + // Output all the fields (errors or warnings) at this level
+ this[field].map((message) => `- ${indentText(message)}`).join("\n") + // Output all the child diagnostics at the next level
+ this.children.map(
+ (child) => child[hasMethod]() ? "\n- " + child.render(field) : ""
+ ).filter((output) => output !== "").join("\n")
+ );
+ }
+};
+__name(Diagnostics, "Diagnostics");
+function indentText(str) {
+ return str.split("\n").map(
+ (line, index) => (index === 0 ? line : ` ${line}`).replace(/^\s*$/, "")
+ ).join("\n");
+}
+__name(indentText, "indentText");
+
+// src/config/validation-helpers.ts
+init_import_meta_url();
+function deprecated(diagnostics, config, fieldPath, message, remove, title = "Deprecation", type = "warning") {
+ const BOLD = "\x1B[1m";
+ const NORMAL = "\x1B[0m";
+ const diagnosticMessage = `${BOLD}${title}${NORMAL}: "${fieldPath}":
+${message}`;
+ const result = unwindPropertyPath(config, fieldPath);
+ if (result !== void 0 && result.field in result.container) {
+ diagnostics[`${type}s`].push(diagnosticMessage);
+ if (remove) {
+ delete result.container[result.field];
+ }
+ }
+}
+__name(deprecated, "deprecated");
+function experimental(diagnostics, config, fieldPath) {
+ const result = unwindPropertyPath(config, fieldPath);
+ if (result !== void 0 && result.field in result.container) {
+ diagnostics.warnings.push(
+ `"${fieldPath}" fields are experimental and may change or break at any time.`
+ );
+ }
+}
+__name(experimental, "experimental");
+function inheritable(diagnostics, topLevelEnv, rawEnv, field, validate2, defaultValue, transformFn = (v) => v) {
+ validate2(diagnostics, field, rawEnv[field], topLevelEnv);
+ return rawEnv[field] ?? transformFn(topLevelEnv?.[field]) ?? defaultValue;
+}
+__name(inheritable, "inheritable");
+function inheritableInLegacyEnvironments(diagnostics, isLegacyEnv2, topLevelEnv, rawEnv, field, validate2, transformFn = (v) => v, defaultValue) {
+ return topLevelEnv === void 0 || isLegacyEnv2 === true ? inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ field,
+ validate2,
+ defaultValue,
+ transformFn
+ ) : notAllowedInNamedServiceEnvironment(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ field
+ );
+}
+__name(inheritableInLegacyEnvironments, "inheritableInLegacyEnvironments");
+var appendEnvName = /* @__PURE__ */ __name((envName) => (fieldValue) => fieldValue ? `${fieldValue}-${envName}` : void 0, "appendEnvName");
+function notAllowedInNamedServiceEnvironment(diagnostics, topLevelEnv, rawEnv, field) {
+ if (field in rawEnv) {
+ diagnostics.errors.push(
+ `The "${field}" field is not allowed in named service environments.
+Please remove the field from this environment.`
+ );
+ }
+ return topLevelEnv[field];
+}
+__name(notAllowedInNamedServiceEnvironment, "notAllowedInNamedServiceEnvironment");
+function notInheritable(diagnostics, topLevelEnv, rawConfig, rawEnv, envName, field, validate2, defaultValue) {
+ if (rawEnv[field] !== void 0) {
+ validate2(diagnostics, field, rawEnv[field], topLevelEnv);
+ } else {
+ if (rawConfig?.[field] !== void 0) {
+ diagnostics.warnings.push(
+ `"${field}" exists at the top level, but not on "env.${envName}".
+This is not what you probably want, since "${field}" is not inherited by environments.
+Please add "${field}" to "env.${envName}".`
+ );
+ }
+ }
+ return rawEnv[field] ?? defaultValue;
+}
+__name(notInheritable, "notInheritable");
+function unwindPropertyPath(root, path45) {
+ let container = root;
+ const parts = path45.split(".");
+ for (let i = 0; i < parts.length - 1; i++) {
+ if (!hasProperty(container, parts[i])) {
+ return;
+ }
+ container = container[parts[i]];
+ }
+ return { container, field: parts[parts.length - 1] };
+}
+__name(unwindPropertyPath, "unwindPropertyPath");
+var isString = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (value !== void 0 && typeof value !== "string") {
+ diagnostics.errors.push(
+ `Expected "${field}" to be of type string but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ return true;
+}, "isString");
+var isValidName = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value === "string" && /^$|^[a-z0-9_ ][a-z0-9-_ ]*$/.test(value) || value === void 0) {
+ return true;
+ } else {
+ diagnostics.errors.push(
+ `Expected "${field}" to be of type string, alphanumeric and lowercase with dashes only but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+}, "isValidName");
+var isStringArray = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (value !== void 0 && (!Array.isArray(value) || value.some((item) => typeof item !== "string"))) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be of type string array but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ return true;
+}, "isStringArray");
+var isObjectWith = /* @__PURE__ */ __name((...properties) => (diagnostics, field, value) => {
+ if (value !== void 0 && (typeof value !== "object" || value === null || !properties.every((prop) => prop in value))) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be of type object, containing only properties ${properties}, but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ if (value !== void 0) {
+ const restFields = Object.keys(value).filter(
+ (key) => !properties.includes(key)
+ );
+ validateAdditionalProperties(diagnostics, field, restFields, []);
+ }
+ return true;
+}, "isObjectWith");
+var isOneOf = /* @__PURE__ */ __name((...choices) => (diagnostics, field, value) => {
+ if (value !== void 0 && !choices.some((choice) => value === choice)) {
+ diagnostics.errors.push(
+ `Expected "${field}" field to be one of ${JSON.stringify(
+ choices
+ )} but got ${JSON.stringify(value)}.`
+ );
+ return false;
+ }
+ return true;
+}, "isOneOf");
+var all = /* @__PURE__ */ __name((...validations) => {
+ return (diagnostics, field, value, config) => {
+ let passedValidations = true;
+ for (const validate2 of validations) {
+ if (!validate2(diagnostics, field, value, config)) {
+ passedValidations = false;
+ }
+ }
+ return passedValidations;
+ };
+}, "all");
+var isMutuallyExclusiveWith = /* @__PURE__ */ __name((container, ...fields) => {
+ return (diagnostics, field, value) => {
+ if (value === void 0) {
+ return true;
+ }
+ for (const exclusiveWith of fields) {
+ if (container[exclusiveWith] !== void 0) {
+ diagnostics.errors.push(
+ `Expected exactly one of the following fields ${JSON.stringify([
+ field,
+ ...fields
+ ])}.`
+ );
+ return false;
+ }
+ }
+ return true;
+ };
+}, "isMutuallyExclusiveWith");
+var isBoolean = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (value !== void 0 && typeof value !== "boolean") {
+ diagnostics.errors.push(
+ `Expected "${field}" to be of type boolean but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ return true;
+}, "isBoolean");
+var validateRequiredProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
+ if (container) {
+ container += ".";
+ }
+ if (value === void 0) {
+ diagnostics.errors.push(`"${container}${key}" is a required field.`);
+ return false;
+ } else if (typeof value !== type) {
+ diagnostics.errors.push(
+ `Expected "${container}${key}" to be of type ${type} but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ } else if (choices) {
+ if (!isOneOf(...choices)(diagnostics, `${container}${key}`, value, void 0)) {
+ return false;
+ }
+ }
+ return true;
+}, "validateRequiredProperty");
+var validateOptionalProperty = /* @__PURE__ */ __name((diagnostics, container, key, value, type, choices) => {
+ if (value !== void 0) {
+ return validateRequiredProperty(
+ diagnostics,
+ container,
+ key,
+ value,
+ type,
+ choices
+ );
+ }
+ return true;
+}, "validateOptionalProperty");
+var validateTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
+ let isValid = true;
+ if (!Array.isArray(value)) {
+ diagnostics.errors.push(
+ `Expected "${container}" to be an array of ${type}s but got ${JSON.stringify(
+ value
+ )}`
+ );
+ isValid = false;
+ } else {
+ for (let i = 0; i < value.length; i++) {
+ isValid = validateRequiredProperty(
+ diagnostics,
+ container,
+ `[${i}]`,
+ value[i],
+ type
+ ) && isValid;
+ }
+ }
+ return isValid;
+}, "validateTypedArray");
+var validateOptionalTypedArray = /* @__PURE__ */ __name((diagnostics, container, value, type) => {
+ if (value !== void 0) {
+ return validateTypedArray(diagnostics, container, value, type);
+ }
+ return true;
+}, "validateOptionalTypedArray");
+var isRequiredProperty = /* @__PURE__ */ __name((obj, prop, type, choices) => hasProperty(obj, prop) && typeof obj[prop] === type && (choices === void 0 || choices.includes(obj[prop])), "isRequiredProperty");
+var isOptionalProperty = /* @__PURE__ */ __name((obj, prop, type) => !hasProperty(obj, prop) || typeof obj[prop] === type, "isOptionalProperty");
+var hasProperty = /* @__PURE__ */ __name((obj, property) => property in obj, "hasProperty");
+var validateAdditionalProperties = /* @__PURE__ */ __name((diagnostics, fieldPath, restProps, knownProps) => {
+ const restPropSet = new Set(restProps);
+ for (const knownProp of knownProps) {
+ restPropSet.delete(knownProp);
+ }
+ if (restPropSet.size > 0) {
+ const fields = Array.from(restPropSet.keys()).map((field) => `"${field}"`);
+ diagnostics.warnings.push(
+ `Unexpected fields found in ${fieldPath} field: ${fields}`
+ );
+ return false;
+ }
+ return true;
+}, "validateAdditionalProperties");
+var validateSmartPlacementConfig = /* @__PURE__ */ __name((diagnostics, placement, triggers) => {
+ if (placement?.mode === "smart" && !!triggers?.crons?.length) {
+ diagnostics.errors.push(
+ `You cannot configure both [triggers] and [placement] in your wrangler.toml. Placement is not supported with cron triggers.`
+ );
+ return false;
+ }
+ return true;
+}, "validateSmartPlacementConfig");
+var getBindingNames = /* @__PURE__ */ __name((value) => {
+ if (typeof value !== "object" || value === null) {
+ return [];
+ }
+ if (isBindingList(value)) {
+ return value.bindings.map(({ name }) => name);
+ } else if (isNamespaceList(value)) {
+ return value.map(({ binding }) => binding);
+ } else if (isRecord(value)) {
+ return Object.keys(value).filter((k) => value[k] !== void 0);
+ } else {
+ return [];
+ }
+}, "getBindingNames");
+var isBindingList = /* @__PURE__ */ __name((value) => isRecord(value) && "bindings" in value && Array.isArray(value.bindings) && value.bindings.every(
+ (binding) => isRecord(binding) && "name" in binding && typeof binding.name === "string"
+), "isBindingList");
+var isNamespaceList = /* @__PURE__ */ __name((value) => Array.isArray(value) && value.every(
+ (entry) => isRecord(entry) && "binding" in entry && typeof entry.binding === "string"
+), "isNamespaceList");
+var isRecord = /* @__PURE__ */ __name((value) => typeof value === "object" && value !== null && !Array.isArray(value), "isRecord");
+
+// src/config/validation.ts
+var ENGLISH = new Intl.ListFormat("en");
+function normalizeAndValidateConfig(rawConfig, configPath, args) {
+ const diagnostics = new Diagnostics(
+ `Processing ${configPath ? import_node_path6.default.relative(process.cwd(), configPath) : "wrangler"} configuration:`
+ );
+ deprecated(
+ diagnostics,
+ rawConfig,
+ "miniflare",
+ "Wrangler does not use configuration in the `miniflare` section. Unless you are using Miniflare directly you can remove this section.",
+ true,
+ "\u{1F636} Ignored"
+ );
+ deprecated(
+ diagnostics,
+ rawConfig,
+ "type",
+ "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
+ true,
+ "\u{1F636} Ignored"
+ );
+ deprecated(
+ diagnostics,
+ rawConfig,
+ "webpack_config",
+ "Most common features now work out of the box with wrangler, including modules, jsx, typescript, etc. If you need anything more, use a custom build.",
+ true,
+ "\u{1F636} Ignored"
+ );
+ validateOptionalProperty(
+ diagnostics,
+ "",
+ "legacy_env",
+ rawConfig.legacy_env,
+ "boolean"
+ );
+ validateOptionalProperty(
+ diagnostics,
+ "",
+ "send_metrics",
+ rawConfig.send_metrics,
+ "boolean"
+ );
+ validateOptionalProperty(
+ diagnostics,
+ "",
+ "keep_vars",
+ rawConfig.keep_vars,
+ "boolean"
+ );
+ const isLegacyEnv2 = args["legacy-env"] ?? rawConfig.legacy_env ?? true;
+ if (!isLegacyEnv2) {
+ diagnostics.warnings.push(
+ "Experimental: Service environments are in beta, and their behaviour is guaranteed to change in the future. DO NOT USE IN PRODUCTION."
+ );
+ }
+ const topLevelEnv = normalizeAndValidateEnvironment(
+ diagnostics,
+ configPath,
+ rawConfig
+ );
+ const envName = args.env;
+ let activeEnv = topLevelEnv;
+ if (envName !== void 0) {
+ const envDiagnostics = new Diagnostics(
+ `"env.${envName}" environment configuration`
+ );
+ const rawEnv = rawConfig.env?.[envName];
+ if (rawEnv !== void 0) {
+ activeEnv = normalizeAndValidateEnvironment(
+ envDiagnostics,
+ configPath,
+ rawEnv,
+ envName,
+ topLevelEnv,
+ isLegacyEnv2,
+ rawConfig
+ );
+ diagnostics.addChild(envDiagnostics);
+ } else {
+ activeEnv = normalizeAndValidateEnvironment(
+ envDiagnostics,
+ configPath,
+ {},
+ envName,
+ topLevelEnv,
+ isLegacyEnv2,
+ rawConfig
+ );
+ const envNames = rawConfig.env ? `The available configured environment names are: ${JSON.stringify(
+ Object.keys(rawConfig.env)
+ )}
+` : "";
+ const message = `No environment found in configuration with name "${envName}".
+Before using \`--env=${envName}\` there should be an equivalent environment section in the configuration.
+${envNames}
+Consider adding an environment configuration section to the wrangler.toml file:
+\`\`\`
+[env.` + envName + "]\n```\n";
+ if (envNames.length > 0) {
+ diagnostics.errors.push(message);
+ } else {
+ diagnostics.warnings.push(message);
+ }
+ }
+ }
+ const config = {
+ configPath,
+ legacy_env: isLegacyEnv2,
+ send_metrics: rawConfig.send_metrics,
+ keep_vars: rawConfig.keep_vars,
+ ...activeEnv,
+ dev: normalizeAndValidateDev(diagnostics, rawConfig.dev ?? {}),
+ migrations: normalizeAndValidateMigrations(
+ diagnostics,
+ rawConfig.migrations ?? [],
+ activeEnv.durable_objects
+ ),
+ site: normalizeAndValidateSite(
+ diagnostics,
+ configPath,
+ rawConfig,
+ activeEnv.main
+ ),
+ assets: normalizeAndValidateAssets(diagnostics, configPath, rawConfig),
+ wasm_modules: normalizeAndValidateModulePaths(
+ diagnostics,
+ configPath,
+ "wasm_modules",
+ rawConfig.wasm_modules
+ ),
+ text_blobs: normalizeAndValidateModulePaths(
+ diagnostics,
+ configPath,
+ "text_blobs",
+ rawConfig.text_blobs
+ ),
+ data_blobs: normalizeAndValidateModulePaths(
+ diagnostics,
+ configPath,
+ "data_blobs",
+ rawConfig.data_blobs
+ )
+ };
+ validateBindingsHaveUniqueNames(diagnostics, config);
+ validateAdditionalProperties(
+ diagnostics,
+ "top-level",
+ Object.keys(rawConfig),
+ [...Object.keys(config), "env"]
+ );
+ validateSmartPlacementConfig(diagnostics, config.placement, config.triggers);
+ experimental(diagnostics, rawConfig, "assets");
+ return { config, diagnostics };
+}
+__name(normalizeAndValidateConfig, "normalizeAndValidateConfig");
+function normalizeAndValidateBuild(diagnostics, rawEnv, rawBuild, configPath) {
+ const { command: command2, cwd: cwd2, watch_dir = "./src", upload: upload2, ...rest } = rawBuild;
+ const deprecatedUpload = { ...upload2 };
+ validateAdditionalProperties(diagnostics, "build", Object.keys(rest), []);
+ validateOptionalProperty(diagnostics, "build", "command", command2, "string");
+ validateOptionalProperty(diagnostics, "build", "cwd", cwd2, "string");
+ if (Array.isArray(watch_dir)) {
+ validateTypedArray(diagnostics, "build.watch_dir", watch_dir, "string");
+ } else {
+ validateOptionalProperty(
+ diagnostics,
+ "build",
+ "watch_dir",
+ watch_dir,
+ "string"
+ );
+ }
+ deprecated(
+ diagnostics,
+ rawEnv,
+ "build.upload.format",
+ "The format is inferred automatically from the code.",
+ true
+ );
+ if (rawEnv.main !== void 0 && rawBuild.upload?.main) {
+ diagnostics.errors.push(
+ `Don't define both the \`main\` and \`build.upload.main\` fields in your configuration.
+They serve the same purpose: to point to the entry-point of your worker.
+Delete the \`build.upload.main\` and \`build.upload.dir\` field from your config.`
+ );
+ } else {
+ deprecated(
+ diagnostics,
+ rawEnv,
+ "build.upload.main",
+ `Delete the \`build.upload.main\` and \`build.upload.dir\` fields.
+Then add the top level \`main\` field to your configuration file:
+\`\`\`
+main = "${import_node_path6.default.join(
+ rawBuild.upload?.dir ?? "./dist",
+ rawBuild.upload?.main ?? "."
+ )}"
+\`\`\``,
+ true
+ );
+ deprecated(
+ diagnostics,
+ rawEnv,
+ "build.upload.dir",
+ `Use the top level "main" field or a command-line argument to specify the entry-point for the Worker.`,
+ true
+ );
+ }
+ return {
+ command: command2,
+ watch_dir: (
+ // - `watch_dir` only matters when `command` is defined, so we apply
+ // a default only when `command` is defined
+ // - `configPath` will always be defined since `build` can only
+ // be configured in `wrangler.toml`, but who knows, that may
+ // change in the future, so we do a check anyway
+ command2 && configPath ? Array.isArray(watch_dir) ? watch_dir.map(
+ (dir) => import_node_path6.default.relative(
+ process.cwd(),
+ import_node_path6.default.join(import_node_path6.default.dirname(configPath), `${dir}`)
+ )
+ ) : import_node_path6.default.relative(
+ process.cwd(),
+ import_node_path6.default.join(import_node_path6.default.dirname(configPath), `${watch_dir}`)
+ ) : watch_dir
+ ),
+ cwd: cwd2,
+ deprecatedUpload
+ };
+}
+__name(normalizeAndValidateBuild, "normalizeAndValidateBuild");
+function normalizeAndValidateMainField(configPath, rawMain, deprecatedUpload) {
+ const configDir = import_node_path6.default.dirname(configPath ?? "wrangler.toml");
+ if (rawMain !== void 0) {
+ if (typeof rawMain === "string") {
+ const directory = import_node_path6.default.resolve(configDir);
+ return import_node_path6.default.resolve(directory, rawMain);
+ } else {
+ return rawMain;
+ }
+ } else if (deprecatedUpload?.main !== void 0) {
+ const directory = import_node_path6.default.resolve(
+ configDir,
+ deprecatedUpload?.dir || "./dist"
+ );
+ return import_node_path6.default.resolve(directory, deprecatedUpload.main);
+ } else {
+ return;
+ }
+}
+__name(normalizeAndValidateMainField, "normalizeAndValidateMainField");
+function normalizeAndValidateBaseDirField(configPath, rawDir) {
+ const configDir = import_node_path6.default.dirname(configPath ?? "wrangler.toml");
+ if (rawDir !== void 0) {
+ if (typeof rawDir === "string") {
+ const directory = import_node_path6.default.resolve(configDir);
+ return import_node_path6.default.resolve(directory, rawDir);
+ } else {
+ return rawDir;
+ }
+ } else {
+ return;
+ }
+}
+__name(normalizeAndValidateBaseDirField, "normalizeAndValidateBaseDirField");
+function normalizeAndValidateDev(diagnostics, rawDev) {
+ const {
+ ip: ip2 = "0.0.0.0",
+ port: port2,
+ inspector_port,
+ local_protocol = "http",
+ upstream_protocol = "https",
+ host,
+ ...rest
+ } = rawDev;
+ validateAdditionalProperties(diagnostics, "dev", Object.keys(rest), []);
+ validateOptionalProperty(diagnostics, "dev", "ip", ip2, "string");
+ validateOptionalProperty(diagnostics, "dev", "port", port2, "number");
+ validateOptionalProperty(
+ diagnostics,
+ "dev",
+ "inspector_port",
+ inspector_port,
+ "number"
+ );
+ validateOptionalProperty(
+ diagnostics,
+ "dev",
+ "local_protocol",
+ local_protocol,
+ "string",
+ ["http", "https"]
+ );
+ validateOptionalProperty(
+ diagnostics,
+ "dev",
+ "upstream_protocol",
+ upstream_protocol,
+ "string",
+ ["http", "https"]
+ );
+ validateOptionalProperty(diagnostics, "dev", "host", host, "string");
+ return { ip: ip2, port: port2, inspector_port, local_protocol, upstream_protocol, host };
+}
+__name(normalizeAndValidateDev, "normalizeAndValidateDev");
+function normalizeAndValidateMigrations(diagnostics, rawMigrations, durableObjects) {
+ if (!Array.isArray(rawMigrations)) {
+ diagnostics.errors.push(
+ `The optional "migrations" field should be an array, but got ${JSON.stringify(
+ rawMigrations
+ )}`
+ );
+ return [];
+ } else {
+ for (let i = 0; i < rawMigrations.length; i++) {
+ const { tag, new_classes, renamed_classes, deleted_classes, ...rest } = rawMigrations[i];
+ validateAdditionalProperties(
+ diagnostics,
+ "migrations",
+ Object.keys(rest),
+ []
+ );
+ validateRequiredProperty(
+ diagnostics,
+ `migrations[${i}]`,
+ `tag`,
+ tag,
+ "string"
+ );
+ validateOptionalTypedArray(
+ diagnostics,
+ `migrations[${i}].new_classes`,
+ new_classes,
+ "string"
+ );
+ if (renamed_classes !== void 0) {
+ if (!Array.isArray(renamed_classes)) {
+ diagnostics.errors.push(
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
+ renamed_classes
+ )}.`
+ );
+ } else if (renamed_classes.some(
+ (c) => typeof c !== "object" || !isRequiredProperty(c, "from", "string") || !isRequiredProperty(c, "to", "string")
+ )) {
+ diagnostics.errors.push(
+ `Expected "migrations[${i}].renamed_classes" to be an array of "{from: string, to: string}" objects but got ${JSON.stringify(
+ renamed_classes
+ )}.`
+ );
+ }
+ }
+ validateOptionalTypedArray(
+ diagnostics,
+ `migrations[${i}].deleted_classes`,
+ deleted_classes,
+ "string"
+ );
+ }
+ if (Array.isArray(durableObjects?.bindings) && durableObjects.bindings.length > 0) {
+ const exportedDurableObjects = (durableObjects.bindings || []).filter(
+ (binding) => !binding.script_name
+ );
+ if (exportedDurableObjects.length > 0 && rawMigrations.length === 0) {
+ if (!exportedDurableObjects.some(
+ (exportedDurableObject) => typeof exportedDurableObject.class_name !== "string"
+ )) {
+ const durableObjectClassnames = exportedDurableObjects.map(
+ (durable) => durable.class_name
+ );
+ diagnostics.warnings.push(
+ `In wrangler.toml, you have configured [durable_objects] exported by this Worker (${durableObjectClassnames.join(
+ ", "
+ )}), but no [migrations] for them. This may not work as expected until you add a [migrations] section to your wrangler.toml. Add this configuration to your wrangler.toml:
+
+ \`\`\`
+ [[migrations]]
+ tag = "v1" # Should be unique for each entry
+ new_classes = [${durableObjectClassnames.map((name) => `"${name}"`).join(", ")}]
+ \`\`\`
+
+Refer to https://developers.cloudflare.com/workers/learning/using-durable-objects/#durable-object-migrations-in-wranglertoml for more details.`
+ );
+ }
+ }
+ }
+ return rawMigrations;
+ }
+}
+__name(normalizeAndValidateMigrations, "normalizeAndValidateMigrations");
+function normalizeAndValidateSite(diagnostics, configPath, rawConfig, mainEntryPoint) {
+ if (rawConfig?.site !== void 0) {
+ const { bucket, include = [], exclude = [], ...rest } = rawConfig.site;
+ validateAdditionalProperties(diagnostics, "site", Object.keys(rest), [
+ "entry-point"
+ ]);
+ validateRequiredProperty(diagnostics, "site", "bucket", bucket, "string");
+ validateTypedArray(diagnostics, "sites.include", include, "string");
+ validateTypedArray(diagnostics, "sites.exclude", exclude, "string");
+ validateOptionalProperty(
+ diagnostics,
+ "site",
+ "entry-point",
+ rawConfig.site["entry-point"],
+ "string"
+ );
+ deprecated(
+ diagnostics,
+ rawConfig,
+ `site.entry-point`,
+ `Delete the \`site.entry-point\` field, then add the top level \`main\` field to your configuration file:
+\`\`\`
+main = "${import_node_path6.default.join(
+ String(rawConfig.site["entry-point"]) || "workers-site",
+ import_node_path6.default.extname(String(rawConfig.site["entry-point"]) || "workers-site") ? "" : "index.js"
+ )}"
+\`\`\``,
+ false,
+ void 0,
+ "warning"
+ );
+ let siteEntryPoint = rawConfig.site["entry-point"];
+ if (!mainEntryPoint && !siteEntryPoint) {
+ diagnostics.warnings.push(
+ `Because you've defined a [site] configuration, we're defaulting to "workers-site" for the deprecated \`site.entry-point\`field.
+Add the top level \`main\` field to your configuration file:
+\`\`\`
+main = "workers-site/index.js"
+\`\`\``
+ );
+ siteEntryPoint = "workers-site";
+ } else if (mainEntryPoint && siteEntryPoint) {
+ diagnostics.errors.push(
+ `Don't define both the \`main\` and \`site.entry-point\` fields in your configuration.
+They serve the same purpose: to point to the entry-point of your worker.
+Delete the deprecated \`site.entry-point\` field from your config.`
+ );
+ }
+ if (configPath && siteEntryPoint) {
+ siteEntryPoint = import_node_path6.default.relative(
+ process.cwd(),
+ import_node_path6.default.join(import_node_path6.default.dirname(configPath), siteEntryPoint)
+ );
+ }
+ return {
+ bucket,
+ "entry-point": siteEntryPoint,
+ include,
+ exclude
+ };
+ }
+ return void 0;
+}
+__name(normalizeAndValidateSite, "normalizeAndValidateSite");
+function normalizeAndValidateAssets(diagnostics, configPath, rawConfig) {
+ if (typeof rawConfig?.assets === "string") {
+ return {
+ bucket: rawConfig.assets,
+ include: [],
+ exclude: [],
+ browser_TTL: void 0,
+ serve_single_page_app: false
+ };
+ }
+ if (rawConfig?.assets === void 0) {
+ return void 0;
+ }
+ if (typeof rawConfig.assets !== "object") {
+ diagnostics.errors.push(
+ `Expected the \`assets\` field to be a string or an object, but got ${typeof rawConfig.assets}.`
+ );
+ return void 0;
+ }
+ const {
+ bucket,
+ include = [],
+ exclude = [],
+ browser_TTL,
+ serve_single_page_app,
+ ...rest
+ } = rawConfig.assets;
+ validateAdditionalProperties(diagnostics, "assets", Object.keys(rest), []);
+ validateRequiredProperty(diagnostics, "assets", "bucket", bucket, "string");
+ validateTypedArray(diagnostics, "assets.include", include, "string");
+ validateTypedArray(diagnostics, "assets.exclude", exclude, "string");
+ validateOptionalProperty(
+ diagnostics,
+ "assets",
+ "browser_TTL",
+ browser_TTL,
+ "number"
+ );
+ validateOptionalProperty(
+ diagnostics,
+ "assets",
+ "serve_single_page_app",
+ serve_single_page_app,
+ "boolean"
+ );
+ return {
+ bucket,
+ include,
+ exclude,
+ browser_TTL,
+ serve_single_page_app
+ };
+}
+__name(normalizeAndValidateAssets, "normalizeAndValidateAssets");
+function normalizeAndValidateModulePaths(diagnostics, configPath, field, rawMapping) {
+ if (rawMapping === void 0) {
+ return void 0;
+ }
+ const mapping = {};
+ for (const [name, filePath] of Object.entries(rawMapping)) {
+ if (isString(diagnostics, `${field}['${name}']`, filePath, void 0)) {
+ if (configPath) {
+ mapping[name] = configPath ? import_node_path6.default.relative(
+ process.cwd(),
+ import_node_path6.default.join(import_node_path6.default.dirname(configPath), filePath)
+ ) : filePath;
+ }
+ }
+ }
+ return mapping;
+}
+__name(normalizeAndValidateModulePaths, "normalizeAndValidateModulePaths");
+function isValidRouteValue(item) {
+ if (!item) {
+ return false;
+ }
+ if (typeof item === "string") {
+ return true;
+ }
+ if (typeof item === "object") {
+ if (!hasProperty(item, "pattern") || typeof item.pattern !== "string") {
+ return false;
+ }
+ const otherKeys = Object.keys(item).length - 1;
+ const hasZoneId = hasProperty(item, "zone_id") && typeof item.zone_id === "string";
+ const hasZoneName = hasProperty(item, "zone_name") && typeof item.zone_name === "string";
+ const hasCustomDomainFlag = hasProperty(item, "custom_domain") && typeof item.custom_domain === "boolean";
+ if (otherKeys === 2 && hasCustomDomainFlag && (hasZoneId || hasZoneName)) {
+ return true;
+ } else if (otherKeys === 1 && (hasZoneId || hasZoneName || hasCustomDomainFlag)) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(isValidRouteValue, "isValidRouteValue");
+function mutateEmptyStringAccountIDValue(diagnostics, rawEnv) {
+ if (rawEnv.account_id === "") {
+ diagnostics.warnings.push(
+ `The "account_id" field in your configuration is an empty string and will be ignored.
+Please remove the "account_id" field from your configuration.`
+ );
+ rawEnv.account_id = void 0;
+ }
+ return rawEnv;
+}
+__name(mutateEmptyStringAccountIDValue, "mutateEmptyStringAccountIDValue");
+function mutateEmptyStringRouteValue(diagnostics, rawEnv) {
+ if (rawEnv["route"] === "") {
+ diagnostics.warnings.push(
+ `The "route" field in your configuration is an empty string and will be ignored.
+Please remove the "route" field from your configuration.`
+ );
+ rawEnv["route"] = void 0;
+ }
+ return rawEnv;
+}
+__name(mutateEmptyStringRouteValue, "mutateEmptyStringRouteValue");
+var isRoute = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (value !== void 0 && !isValidRouteValue(value)) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be either a string, or an object with shape { pattern, custom_domain, zone_id | zone_name }, but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ return true;
+}, "isRoute");
+var isRouteArray = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (value === void 0) {
+ return true;
+ }
+ if (!Array.isArray(value)) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
+ );
+ return false;
+ }
+ const invalidRoutes = [];
+ for (const item of value) {
+ if (!isValidRouteValue(item)) {
+ invalidRoutes.push(item);
+ }
+ }
+ if (invalidRoutes.length > 0) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be an array of either strings or objects with the shape { pattern, custom_domain, zone_id | zone_name }, but these weren't valid: ${JSON.stringify(
+ invalidRoutes,
+ null,
+ 2
+ )}.`
+ );
+ }
+ return invalidRoutes.length === 0;
+}, "isRouteArray");
+function normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv) {
+ return inheritable(
+ diagnostics,
+ topLevelEnv,
+ mutateEmptyStringRouteValue(diagnostics, rawEnv),
+ "route",
+ isRoute,
+ void 0
+ );
+}
+__name(normalizeAndValidateRoute, "normalizeAndValidateRoute");
+function validateRoutes(diagnostics, topLevelEnv, rawEnv) {
+ return inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "routes",
+ all(isRouteArray, isMutuallyExclusiveWith(rawEnv, "route")),
+ void 0
+ );
+}
+__name(validateRoutes, "validateRoutes");
+function normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv) {
+ if (rawEnv.placement) {
+ validateRequiredProperty(
+ diagnostics,
+ "placement",
+ "mode",
+ rawEnv.placement.mode,
+ "string",
+ ["off", "smart"]
+ );
+ }
+ return inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "placement",
+ () => true,
+ void 0
+ );
+}
+__name(normalizeAndValidatePlacement, "normalizeAndValidatePlacement");
+function validateTailConsumer(diagnostics, field, value) {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"${field}" should be an object but got ${JSON.stringify(value)}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ isValid = isValid && validateRequiredProperty(
+ diagnostics,
+ field,
+ "service",
+ value.service,
+ "string"
+ );
+ isValid = isValid && validateOptionalProperty(
+ diagnostics,
+ field,
+ "environment",
+ value.environment,
+ "string"
+ );
+ return isValid;
+}
+__name(validateTailConsumer, "validateTailConsumer");
+var validateTailConsumers = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (!value) {
+ return true;
+ }
+ if (!Array.isArray(value)) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be an array but got ${JSON.stringify(value)}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ for (let i = 0; i < value.length; i++) {
+ isValid = validateTailConsumer(diagnostics, `${field}[${i}]`, value[i]) && isValid;
+ }
+ return isValid;
+}, "validateTailConsumers");
+function normalizeAndValidateEnvironment(diagnostics, configPath, rawEnv, envName = "top level", topLevelEnv, isLegacyEnv2, rawConfig) {
+ deprecated(
+ diagnostics,
+ rawEnv,
+ "kv-namespaces",
+ `The "kv-namespaces" field is no longer supported, please rename to "kv_namespaces"`,
+ true
+ );
+ deprecated(
+ diagnostics,
+ rawEnv,
+ "zone_id",
+ "This is unnecessary since we can deduce this from routes directly.",
+ false
+ // We need to leave this in-place for the moment since `route` commands might use it.
+ );
+ deprecated(
+ diagnostics,
+ rawEnv,
+ "experimental_services",
+ `The "experimental_services" field is no longer supported. Simply rename the [experimental_services] field to [services].`,
+ true
+ );
+ experimental(diagnostics, rawEnv, "unsafe");
+ experimental(diagnostics, rawEnv, "services");
+ const route2 = normalizeAndValidateRoute(diagnostics, topLevelEnv, rawEnv);
+ const account_id = inheritableInLegacyEnvironments(
+ diagnostics,
+ isLegacyEnv2,
+ topLevelEnv,
+ mutateEmptyStringAccountIDValue(diagnostics, rawEnv),
+ "account_id",
+ isString,
+ void 0,
+ void 0
+ );
+ const routes = validateRoutes(diagnostics, topLevelEnv, rawEnv);
+ const workers_dev = inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "workers_dev",
+ isBoolean,
+ void 0
+ );
+ const { deprecatedUpload, ...build5 } = normalizeAndValidateBuild(
+ diagnostics,
+ rawEnv,
+ rawEnv.build ?? topLevelEnv?.build ?? {},
+ configPath
+ );
+ const environment = {
+ // Inherited fields
+ account_id,
+ compatibility_date: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "compatibility_date",
+ isString,
+ void 0
+ ),
+ compatibility_flags: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "compatibility_flags",
+ isStringArray,
+ []
+ ),
+ jsx_factory: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "jsx_factory",
+ isString,
+ "React.createElement"
+ ),
+ jsx_fragment: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "jsx_fragment",
+ isString,
+ "React.Fragment"
+ ),
+ tsconfig: validateAndNormalizeTsconfig(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ configPath
+ ),
+ rules: validateAndNormalizeRules(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ deprecatedUpload?.rules,
+ envName
+ ),
+ name: inheritableInLegacyEnvironments(
+ diagnostics,
+ isLegacyEnv2,
+ topLevelEnv,
+ rawEnv,
+ "name",
+ isValidName,
+ appendEnvName(envName),
+ void 0
+ ),
+ main: normalizeAndValidateMainField(
+ configPath,
+ inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "main",
+ isString,
+ void 0
+ ),
+ deprecatedUpload
+ ),
+ base_dir: normalizeAndValidateBaseDirField(
+ configPath,
+ inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "base_dir",
+ isString,
+ void 0
+ )
+ ),
+ route: route2,
+ routes,
+ triggers: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "triggers",
+ isObjectWith("crons"),
+ { crons: [] }
+ ),
+ usage_model: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "usage_model",
+ isOneOf("bundled", "unbound"),
+ void 0
+ ),
+ placement: normalizeAndValidatePlacement(diagnostics, topLevelEnv, rawEnv),
+ build: build5,
+ workers_dev,
+ // Not inherited fields
+ vars: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "vars",
+ validateVars(envName),
+ {}
+ ),
+ define: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "define",
+ validateDefines(envName),
+ {}
+ ),
+ durable_objects: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "durable_objects",
+ validateBindingsProperty(envName, validateDurableObjectBinding),
+ {
+ bindings: []
+ }
+ ),
+ kv_namespaces: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "kv_namespaces",
+ validateBindingArray(envName, validateKVBinding),
+ []
+ ),
+ send_email: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "send_email",
+ validateBindingArray(envName, validateSendEmailBinding),
+ []
+ ),
+ queues: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "queues",
+ validateQueues(envName),
+ { producers: [], consumers: [] }
+ ),
+ r2_buckets: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "r2_buckets",
+ validateBindingArray(envName, validateR2Binding),
+ []
+ ),
+ d1_databases: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "d1_databases",
+ validateBindingArray(envName, validateD1Binding),
+ []
+ ),
+ constellation: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "constellation",
+ validateBindingArray(envName, validateConstellationBinding),
+ []
+ ),
+ services: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "services",
+ validateBindingArray(envName, validateServiceBinding),
+ []
+ ),
+ analytics_engine_datasets: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "analytics_engine_datasets",
+ validateBindingArray(envName, validateAnalyticsEngineBinding),
+ []
+ ),
+ dispatch_namespaces: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "dispatch_namespaces",
+ validateBindingArray(envName, validateWorkerNamespaceBinding),
+ []
+ ),
+ mtls_certificates: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "mtls_certificates",
+ validateBindingArray(envName, validateMTlsCertificateBinding),
+ []
+ ),
+ tail_consumers: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "tail_consumers",
+ validateTailConsumers,
+ void 0
+ ),
+ unsafe: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "unsafe",
+ validateUnsafeSettings(envName),
+ {}
+ ),
+ browser: notInheritable(
+ diagnostics,
+ topLevelEnv,
+ rawConfig,
+ rawEnv,
+ envName,
+ "browser",
+ validateBrowserBinding(envName),
+ void 0
+ ),
+ zone_id: rawEnv.zone_id,
+ logfwdr: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "logfwdr",
+ validateCflogfwdrObject(envName),
+ {
+ bindings: []
+ }
+ ),
+ no_bundle: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "no_bundle",
+ isBoolean,
+ void 0
+ ),
+ minify: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "minify",
+ isBoolean,
+ void 0
+ ),
+ node_compat: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "node_compat",
+ isBoolean,
+ void 0
+ ),
+ first_party_worker: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "first_party_worker",
+ isBoolean,
+ void 0
+ ),
+ logpush: inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "logpush",
+ isBoolean,
+ void 0
+ )
+ };
+ return environment;
+}
+__name(normalizeAndValidateEnvironment, "normalizeAndValidateEnvironment");
+function validateAndNormalizeTsconfig(diagnostics, topLevelEnv, rawEnv, configPath) {
+ const tsconfig = inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "tsconfig",
+ isString,
+ void 0
+ );
+ return configPath && tsconfig ? import_node_path6.default.relative(
+ process.cwd(),
+ import_node_path6.default.join(import_node_path6.default.dirname(configPath), tsconfig)
+ ) : tsconfig;
+}
+__name(validateAndNormalizeTsconfig, "validateAndNormalizeTsconfig");
+var validateAndNormalizeRules = /* @__PURE__ */ __name((diagnostics, topLevelEnv, rawEnv, deprecatedRules, envName) => {
+ if (topLevelEnv === void 0) {
+ if (rawEnv.rules && deprecatedRules) {
+ diagnostics.errors.push(
+ `You cannot configure both [rules] and [build.upload.rules] in your wrangler.toml. Delete the \`build.upload\` section.`
+ );
+ } else if (deprecatedRules) {
+ diagnostics.warnings.push(
+ `Deprecation: The \`build.upload.rules\` config field is no longer used, the rules should be specified via the \`rules\` config field. Delete the \`build.upload\` field from the configuration file, and add this:
+\`\`\`
+` + import_toml3.default.stringify({ rules: deprecatedRules }) + "```"
+ );
+ }
+ }
+ return inheritable(
+ diagnostics,
+ topLevelEnv,
+ rawEnv,
+ "rules",
+ validateRules(envName),
+ deprecatedRules ?? []
+ );
+}, "validateAndNormalizeRules");
+var validateRules = /* @__PURE__ */ __name((envName) => (diagnostics, field, envValue, config) => {
+ if (!envValue) {
+ return true;
+ }
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (!Array.isArray(envValue)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
+ envValue
+ )}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ for (let i = 0; i < envValue.length; i++) {
+ isValid = validateRule(diagnostics, `${fieldPath}[${i}]`, envValue[i], config) && isValid;
+ }
+ return isValid;
+}, "validateRules");
+var validateRule = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"${field}" should be an object but got ${JSON.stringify(value)}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ const rule = value;
+ if (!isRequiredProperty(rule, "type", "string", [
+ "ESModule",
+ "CommonJS",
+ "CompiledWasm",
+ "Text",
+ "Data"
+ ])) {
+ diagnostics.errors.push(
+ `bindings should have a string "type" field, which contains one of "ESModule", "CommonJS", "CompiledWasm", "Text", or "Data".`
+ );
+ isValid = false;
+ }
+ isValid = validateTypedArray(diagnostics, `${field}.globs`, rule.globs, "string") && isValid;
+ if (!isOptionalProperty(rule, "fallthrough", "boolean")) {
+ diagnostics.errors.push(
+ `the field "fallthrough", when present, should be a boolean.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateRule");
+var validateDefines = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
+ let isValid = true;
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (typeof value === "object" && value !== null) {
+ for (const varName in value) {
+ if (typeof value[varName] !== "string") {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.${varName}" should be a string but got ${JSON.stringify(
+ value[varName]
+ )}.`
+ );
+ isValid = false;
+ }
+ }
+ } else {
+ if (value !== void 0) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
+ value
+ )}.
+`
+ );
+ isValid = false;
+ }
+ }
+ const configDefines = Object.keys(config?.define ?? {});
+ if (configDefines.length > 0) {
+ if (typeof value === "object" && value !== null) {
+ const configEnvDefines = config === void 0 ? [] : Object.keys(value);
+ for (const varName of configDefines) {
+ if (!(varName in value)) {
+ diagnostics.warnings.push(
+ `"define.${varName}" exists at the top level, but not on "${fieldPath}".
+This is not what you probably want, since "define" configuration is not inherited by environments.
+Please add "define.${varName}" to "env.${envName}".`
+ );
+ }
+ }
+ for (const varName of configEnvDefines) {
+ if (!configDefines.includes(varName)) {
+ diagnostics.warnings.push(
+ `"${varName}" exists on "env.${envName}", but not on the top level.
+This is not what you probably want, since "define" configuration within environments can only override existing top level "define" configuration
+Please remove "${fieldPath}.${varName}", or add "define.${varName}".`
+ );
+ }
+ }
+ }
+ }
+ return isValid;
+}, "validateDefines");
+var validateVars = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
+ let isValid = true;
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ const configVars = Object.keys(config?.vars ?? {});
+ if (configVars.length > 0) {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
+ value
+ )}.
+`
+ );
+ isValid = false;
+ } else {
+ for (const varName of configVars) {
+ if (!(varName in value)) {
+ diagnostics.warnings.push(
+ `"vars.${varName}" exists at the top level, but not on "${fieldPath}".
+This is not what you probably want, since "vars" configuration is not inherited by environments.
+Please add "vars.${varName}" to "env.${envName}".`
+ );
+ }
+ }
+ }
+ }
+ return isValid;
+}, "validateVars");
+var validateBindingsProperty = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, value, config) => {
+ let isValid = true;
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (value !== void 0) {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ } else if (!hasProperty(value, "bindings")) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" is missing the required "bindings" property.`
+ );
+ isValid = false;
+ } else if (!Array.isArray(value.bindings)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.bindings" should be an array but got ${JSON.stringify(
+ value.bindings
+ )}.`
+ );
+ isValid = false;
+ } else {
+ for (let i = 0; i < value.bindings.length; i++) {
+ const binding = value.bindings[i];
+ const bindingDiagnostics = new Diagnostics(
+ `"${fieldPath}.bindings[${i}]": ${JSON.stringify(binding)}`
+ );
+ isValid = validateBinding(
+ bindingDiagnostics,
+ `${fieldPath}.bindings[${i}]`,
+ binding,
+ config
+ ) && isValid;
+ diagnostics.addChild(bindingDiagnostics);
+ }
+ }
+ const configBindingNames = getBindingNames(
+ config?.[field]
+ );
+ if (isValid && configBindingNames.length > 0) {
+ const envBindingNames = new Set(getBindingNames(value));
+ const missingBindings = configBindingNames.filter(
+ (name) => !envBindingNames.has(name)
+ );
+ if (missingBindings.length > 0) {
+ diagnostics.warnings.push(
+ `The following bindings are at the top level, but not on "env.${envName}".
+This is not what you probably want, since "${field}" configuration is not inherited by environments.
+Please add a binding for each to "${fieldPath}.bindings":
+` + missingBindings.map((name) => `- ${name}`).join("\n")
+ );
+ }
+ }
+ }
+ return isValid;
+}, "validateBindingsProperty");
+var validateUnsafeSettings = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ if (!hasProperty(value, "bindings") && !hasProperty(value, "metadata") && !hasProperty(value, "capnp")) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should contain at least one of "bindings", "metadata" or "capnp" properties but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ if (hasProperty(value, "bindings") && value.bindings !== void 0) {
+ const validateBindingsFn = validateBindingsProperty(
+ envName,
+ validateUnsafeBinding
+ );
+ const valid = validateBindingsFn(diagnostics, field, value, config);
+ if (!valid) {
+ return false;
+ }
+ }
+ if (hasProperty(value, "metadata") && value.metadata !== void 0 && (typeof value.metadata !== "object" || value.metadata === null || Array.isArray(value.metadata))) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.metadata" should be an object but got ${JSON.stringify(
+ value.metadata
+ )}.`
+ );
+ return false;
+ }
+ if (hasProperty(value, "capnp") && value.capnp !== void 0) {
+ if (typeof value.capnp !== "object" || value.capnp === null || Array.isArray(value.capnp)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.capnp" should be an object but got ${JSON.stringify(
+ value.capnp
+ )}.`
+ );
+ return false;
+ }
+ if (hasProperty(value.capnp, "compiled_schema")) {
+ if (hasProperty(value.capnp, "base_path") || hasProperty(value.capnp, "source_schemas")) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.capnp" cannot contain both "compiled_schema" and one of "base_path" or "source_schemas".`
+ );
+ return false;
+ }
+ if (typeof value.capnp.compiled_schema !== "string") {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.capnp.compiled_schema", when present, should be a string but got ${JSON.stringify(
+ value.capnp.compiled_schema
+ )}.`
+ );
+ return false;
+ }
+ } else {
+ if (!isRequiredProperty(value.capnp, "base_path", "string")) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.capnp.base_path", when present, should be a string but got ${JSON.stringify(
+ value.capnp.base_path
+ )}`
+ );
+ }
+ if (!validateTypedArray(
+ diagnostics,
+ `${fieldPath}.capnp.source_schemas`,
+ value.capnp.source_schemas,
+ "string"
+ )) {
+ return false;
+ }
+ }
+ }
+ return true;
+}, "validateUnsafeSettings");
+var validateDurableObjectBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "name", "string")) {
+ diagnostics.errors.push(`binding should have a string "name" field.`);
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "class_name", "string")) {
+ diagnostics.errors.push(`binding should have a string "class_name" field.`);
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "script_name", "string")) {
+ diagnostics.errors.push(
+ `the field "script_name", when present, should be a string.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "environment", "string")) {
+ diagnostics.errors.push(
+ `the field "environment", when present, should be a string.`
+ );
+ isValid = false;
+ }
+ if ("environment" in value && !("script_name" in value)) {
+ diagnostics.errors.push(
+ `binding should have a "script_name" field if "environment" is present.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateDurableObjectBinding");
+var validateCflogfwdrObject = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, topLevelEnv) => {
+ const bindingsValidation = validateBindingsProperty(
+ envName,
+ validateCflogfwdrBinding
+ );
+ if (!bindingsValidation(diagnostics, field, value, topLevelEnv))
+ return false;
+ const v = value;
+ if (v?.schema !== void 0) {
+ diagnostics.errors.push(
+ `"${field}" binding "schema" property has been replaced with the "unsafe.capnp" object, which expects a "base_path" and an array of "source_schemas" to compile, or a "compiled_schema" property.`
+ );
+ return false;
+ }
+ return true;
+}, "validateCflogfwdrObject");
+var validateCflogfwdrBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `Expected "${field}" to be an object but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "name", "string")) {
+ diagnostics.errors.push(`binding should have a string "name" field.`);
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "destination", "string")) {
+ diagnostics.errors.push(
+ `binding should have a string "destination" field.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateCflogfwdrBinding");
+var validateBrowserBinding = /* @__PURE__ */ __name((envName) => (diagnostics, field, value, config) => {
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(`binding should have a string "binding" field.`);
+ isValid = false;
+ }
+ return isValid;
+}, "validateBrowserBinding");
+var validateUnsafeBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `Expected ${field} to be an object but got ${JSON.stringify(value)}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "name", "string")) {
+ diagnostics.errors.push(`binding should have a string "name" field.`);
+ isValid = false;
+ }
+ if (isRequiredProperty(value, "type", "string")) {
+ const safeBindings = [
+ "plain_text",
+ "json",
+ "wasm_module",
+ "data_blob",
+ "text_blob",
+ "browser",
+ "kv_namespace",
+ "durable_object_namespace",
+ "d1_database",
+ "constellation",
+ "r2_bucket",
+ "service",
+ "logfwdr",
+ "mtls_certificate"
+ ];
+ if (safeBindings.includes(value.type)) {
+ diagnostics.warnings.push(
+ `The binding type "${value.type}" is directly supported by wrangler.
+Consider migrating this unsafe binding to a format for '${value.type}' bindings that is supported by wrangler for optimal support.
+For more details, see https://developers.cloudflare.com/workers/cli-wrangler/configuration`
+ );
+ }
+ } else {
+ diagnostics.errors.push(`binding should have a string "type" field.`);
+ isValid = false;
+ }
+ return isValid;
+}, "validateUnsafeBinding");
+var validateBindingArray = /* @__PURE__ */ __name((envName, validateBinding) => (diagnostics, field, envValue, config) => {
+ if (envValue === void 0) {
+ return true;
+ }
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (!Array.isArray(envValue)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an array but got ${JSON.stringify(
+ envValue
+ )}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ for (let i = 0; i < envValue.length; i++) {
+ isValid = validateBinding(
+ diagnostics,
+ `${fieldPath}[${i}]`,
+ envValue[i],
+ config
+ ) && isValid;
+ }
+ const configValue = config?.[field];
+ if (Array.isArray(configValue)) {
+ const configBindingNames = configValue.map((value) => value.binding);
+ if (configBindingNames.length > 0) {
+ const envBindingNames = new Set(envValue.map((value) => value.binding));
+ for (const configBindingName of configBindingNames) {
+ if (!envBindingNames.has(configBindingName)) {
+ diagnostics.warnings.push(
+ `There is a ${field} binding with name "${configBindingName}" at the top level, but not on "env.${envName}".
+This is not what you probably want, since "${field}" configuration is not inherited by environments.
+Please add a binding for "${configBindingName}" to "env.${envName}.${field}.bindings".`
+ );
+ }
+ }
+ }
+ }
+ return isValid;
+}, "validateBindingArray");
+var validateKVBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"kv_namespaces" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "id", "string") || value.id.length === 0) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "id" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "preview_id", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a string "preview_id" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateKVBinding");
+var validateSendEmailBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"send_email" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "name", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "name" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "destination_address", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a string "destination_address" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "allowed_destination_addresses", "object")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a []string "allowed_destination_addresses" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if ("destination_address" in value && "allowed_destination_addresses" in value) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have either a "destination_address" or "allowed_destination_addresses" field, but not both.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateSendEmailBinding");
+var validateQueueBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"queue" bindings should be objects, but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ if (!validateAdditionalProperties(diagnostics, field, Object.keys(value), [
+ "binding",
+ "queue"
+ ])) {
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "queue", "string") || value.queue.length === 0) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "queue" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateQueueBinding");
+var validateR2Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"r2_buckets" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "bucket_name", "string") || value.bucket_name.length === 0) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "bucket_name" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "preview_bucket_name", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a string "preview_bucket_name" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "jurisdiction", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a string "jurisdiction" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateR2Binding");
+var validateD1Binding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"d1_databases" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (
+ // TODO: allow name only, where we look up the ID dynamically
+ // !isOptionalProperty(value, "database_name", "string") &&
+ !isRequiredProperty(value, "database_id", "string")
+ ) {
+ diagnostics.errors.push(
+ `"${field}" bindings must have a "database_id" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "preview_database_id", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a string "preview_database_id" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (isValid && !process.env.NO_D1_WARNING) {
+ diagnostics.warnings.push(
+ "D1 Bindings are currently in alpha to allow the API to evolve before general availability.\nPlease report any issues to https://github.com/cloudflare/workers-sdk/issues/new/choose\nNote: Run this command with the environment variable NO_D1_WARNING=true to hide this message\n\nFor example: `export NO_D1_WARNING=true && wrangler `"
+ );
+ }
+ return isValid;
+}, "validateD1Binding");
+var validateConstellationBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"constellation" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "project_id", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings must have a "project_id" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (isValid && getConstellationWarningFromEnv() === void 0) {
+ diagnostics.warnings.push(
+ "Constellation Bindings are currently in beta to allow the API to evolve before general availability.\nPlease report any issues to https://github.com/cloudflare/workers-sdk/issues/new/choose\nNote: Run this command with the environment variable NO_CONSTELLATION_WARNING=true to hide this message\n\nFor example: `export NO_CONSTELLATION_WARNING=true && wrangler `"
+ );
+ }
+ return isValid;
+}, "validateConstellationBinding");
+var validateBindingsHaveUniqueNames = /* @__PURE__ */ __name((diagnostics, {
+ durable_objects,
+ kv_namespaces,
+ r2_buckets,
+ analytics_engine_datasets,
+ text_blobs,
+ browser,
+ unsafe,
+ vars,
+ define: define2,
+ wasm_modules,
+ data_blobs
+}) => {
+ let hasDuplicates = false;
+ const bindingsGroupedByType = {
+ "Durable Object": getBindingNames(durable_objects),
+ "KV Namespace": getBindingNames(kv_namespaces),
+ "R2 Bucket": getBindingNames(r2_buckets),
+ "Analytics Engine Dataset": getBindingNames(analytics_engine_datasets),
+ "Text Blob": getBindingNames(text_blobs),
+ Browser: getBindingNames(browser),
+ Unsafe: getBindingNames(unsafe),
+ "Environment Variable": getBindingNames(vars),
+ Definition: getBindingNames(define2),
+ "WASM Module": getBindingNames(wasm_modules),
+ "Data Blob": getBindingNames(data_blobs)
+ };
+ const bindingsGroupedByName = {};
+ for (const bindingType in bindingsGroupedByType) {
+ const bindingNames = bindingsGroupedByType[bindingType];
+ for (const bindingName of bindingNames) {
+ if (!(bindingName in bindingsGroupedByName)) {
+ bindingsGroupedByName[bindingName] = [];
+ }
+ bindingsGroupedByName[bindingName].push(bindingType);
+ }
+ }
+ for (const bindingName in bindingsGroupedByName) {
+ const bindingTypes = bindingsGroupedByName[bindingName];
+ if (bindingTypes.length < 2) {
+ continue;
+ }
+ hasDuplicates = true;
+ const sameType = bindingTypes.filter((type, i) => bindingTypes.indexOf(type) !== i).filter(
+ (type, i, duplicateBindingTypes) => duplicateBindingTypes.indexOf(type) === i
+ );
+ const differentTypes = bindingTypes.filter(
+ (type, i) => bindingTypes.indexOf(type) === i
+ );
+ if (differentTypes.length > 1) {
+ diagnostics.errors.push(
+ `${bindingName} assigned to ${ENGLISH.format(differentTypes)} bindings.`
+ );
+ }
+ sameType.forEach((bindingType) => {
+ diagnostics.errors.push(
+ `${bindingName} assigned to multiple ${bindingType} bindings.`
+ );
+ });
+ }
+ if (hasDuplicates) {
+ const problem = "Bindings must have unique names, so that they can all be referenced in the worker.";
+ const resolution = "Please change your bindings to have unique names.";
+ diagnostics.errors.push(`${problem}
+${resolution}`);
+ }
+ return !hasDuplicates;
+}, "validateBindingsHaveUniqueNames");
+var validateServiceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"services" bindings should be objects, but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "service", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "service" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "environment", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "environment" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateServiceBinding");
+var validateAnalyticsEngineBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"analytics_engine" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isOptionalProperty(value, "dataset", "string") || value.dataset?.length === 0) {
+ diagnostics.errors.push(
+ `"${field}" bindings should, optionally, have a string "dataset" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateAnalyticsEngineBinding");
+var validateWorkerNamespaceBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"${field}" binding should be objects, but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "namespace", "string")) {
+ diagnostics.errors.push(
+ `"${field}" should have a string "namespace" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (hasProperty(value, "outbound")) {
+ if (!validateWorkerNamespaceOutbound(
+ diagnostics,
+ `${field}.outbound`,
+ value.outbound ?? {}
+ )) {
+ diagnostics.errors.push(`"${field}" has an invalid outbound definition.`);
+ isValid = false;
+ }
+ }
+ return isValid;
+}, "validateWorkerNamespaceBinding");
+function validateWorkerNamespaceOutbound(diagnostics, field, value) {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"${field}" should be an object, but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ let isValid = true;
+ isValid = isValid && validateRequiredProperty(
+ diagnostics,
+ field,
+ "service",
+ value.service,
+ "string"
+ );
+ isValid = isValid && validateOptionalProperty(
+ diagnostics,
+ field,
+ "environment",
+ value.environment,
+ "string"
+ );
+ isValid = isValid && validateOptionalTypedArray(
+ diagnostics,
+ `${field}.parameters`,
+ value.parameters,
+ "string"
+ );
+ return isValid;
+}
+__name(validateWorkerNamespaceOutbound, "validateWorkerNamespaceOutbound");
+var validateMTlsCertificateBinding = /* @__PURE__ */ __name((diagnostics, field, value) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"mtls_certificates" bindings should be objects, but got ${JSON.stringify(
+ value
+ )}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!isRequiredProperty(value, "binding", "string")) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "binding" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "certificate_id", "string") || value.certificate_id.length === 0) {
+ diagnostics.errors.push(
+ `"${field}" bindings should have a string "certificate_id" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ isValid = false;
+ }
+ return isValid;
+}, "validateMTlsCertificateBinding");
+function validateQueues(envName) {
+ return (diagnostics, field, value, config) => {
+ const fieldPath = config === void 0 ? `${field}` : `env.${envName}.${field}`;
+ if (typeof value !== "object" || Array.isArray(value) || value === null) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}" should be an object but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!validateAdditionalProperties(
+ diagnostics,
+ fieldPath,
+ Object.keys(value),
+ ["consumers", "producers"]
+ )) {
+ isValid = false;
+ }
+ if (hasProperty(value, "consumers")) {
+ const consumers2 = value.consumers;
+ if (!Array.isArray(consumers2)) {
+ diagnostics.errors.push(
+ `The field "${fieldPath}.consumers" should be an array but got ${JSON.stringify(
+ consumers2
+ )}.`
+ );
+ isValid = false;
+ }
+ for (let i = 0; i < consumers2.length; i++) {
+ const consumer = consumers2[i];
+ const consumerPath = `${fieldPath}.consumers[${i}]`;
+ if (!validateConsumer(diagnostics, consumerPath, consumer, config)) {
+ isValid = false;
+ }
+ }
+ }
+ if (hasProperty(value, "producers")) {
+ if (!validateBindingArray(envName, validateQueueBinding)(
+ diagnostics,
+ `${field}.producers`,
+ value.producers,
+ config
+ )) {
+ isValid = false;
+ }
+ }
+ return isValid;
+ };
+}
+__name(validateQueues, "validateQueues");
+var validateConsumer = /* @__PURE__ */ __name((diagnostics, field, value, _config) => {
+ if (typeof value !== "object" || value === null) {
+ diagnostics.errors.push(
+ `"${field}" should be a objects, but got ${JSON.stringify(value)}`
+ );
+ return false;
+ }
+ let isValid = true;
+ if (!validateAdditionalProperties(diagnostics, field, Object.keys(value), [
+ "queue",
+ "max_batch_size",
+ "max_batch_timeout",
+ "max_retries",
+ "dead_letter_queue",
+ "max_concurrency"
+ ])) {
+ isValid = false;
+ }
+ if (!isRequiredProperty(value, "queue", "string")) {
+ diagnostics.errors.push(
+ `"${field}" should have a string "queue" field but got ${JSON.stringify(
+ value
+ )}.`
+ );
+ }
+ const options14 = [
+ { key: "max_batch_size", type: "number" },
+ { key: "max_batch_timeout", type: "number" },
+ { key: "max_retries", type: "number" },
+ { key: "dead_letter_queue", type: "string" },
+ { key: "max_concurrency", type: "number" }
+ ];
+ for (const optionalOpt of options14) {
+ if (!isOptionalProperty(value, optionalOpt.key, optionalOpt.type)) {
+ diagnostics.errors.push(
+ `"${field}" should, optionally, have a ${optionalOpt.type} "${optionalOpt.key}" field but got ${JSON.stringify(value)}.`
+ );
+ isValid = false;
+ }
+ }
+ return isValid;
+}, "validateConsumer");
+
+// src/config/index.ts
+function readConfig(configPath, args) {
+ let rawConfig = {};
+ if (!configPath) {
+ configPath = findWranglerToml(process.cwd(), args.experimentalJsonConfig);
+ }
+ if (configPath?.endsWith("toml")) {
+ rawConfig = parseTOML(readFileSync5(configPath), configPath);
+ } else if (configPath?.endsWith("json")) {
+ rawConfig = parseJSONC(readFileSync5(configPath), configPath);
+ }
+ const { config, diagnostics } = normalizeAndValidateConfig(
+ rawConfig,
+ configPath,
+ args
+ );
+ if (diagnostics.hasWarnings()) {
+ logger.warn(diagnostics.renderWarnings());
+ }
+ if (diagnostics.hasErrors()) {
+ throw new Error(diagnostics.renderErrors());
+ }
+ return config;
+}
+__name(readConfig, "readConfig");
+function findWranglerToml(referencePath = process.cwd(), preferJson = false) {
+ if (preferJson) {
+ return findUpSync(`wrangler.json`, { cwd: referencePath }) ?? findUpSync(`wrangler.toml`, { cwd: referencePath });
+ }
+ return findUpSync(`wrangler.toml`, { cwd: referencePath });
+}
+__name(findWranglerToml, "findWranglerToml");
+function printBindings(bindings) {
+ const truncate2 = /* @__PURE__ */ __name((item) => {
+ const s = typeof item === "string" ? item : JSON.stringify(item);
+ const maxLength = 40;
+ if (s.length < maxLength) {
+ return s;
+ }
+ return `${s.substring(0, maxLength - 3)}...`;
+ }, "truncate");
+ const output = [];
+ const {
+ data_blobs,
+ durable_objects,
+ kv_namespaces,
+ send_email,
+ queues: queues2,
+ d1_databases,
+ constellation: constellation2,
+ r2_buckets,
+ logfwdr,
+ services,
+ analytics_engine_datasets,
+ text_blobs,
+ browser,
+ unsafe,
+ vars,
+ wasm_modules,
+ dispatch_namespaces,
+ mtls_certificates
+ } = bindings;
+ if (data_blobs !== void 0 && Object.keys(data_blobs).length > 0) {
+ output.push({
+ type: "Data Blobs",
+ entries: Object.entries(data_blobs).map(([key, value]) => ({
+ key,
+ value: truncate2(value)
+ }))
+ });
+ }
+ if (durable_objects !== void 0 && durable_objects.bindings.length > 0) {
+ output.push({
+ type: "Durable Objects",
+ entries: durable_objects.bindings.map(
+ ({ name, class_name, script_name, environment }) => {
+ let value = class_name;
+ if (script_name) {
+ value += ` (defined in ${script_name})`;
+ }
+ if (environment) {
+ value += ` - ${environment}`;
+ }
+ return {
+ key: name,
+ value
+ };
+ }
+ )
+ });
+ }
+ if (kv_namespaces !== void 0 && kv_namespaces.length > 0) {
+ output.push({
+ type: "KV Namespaces",
+ entries: kv_namespaces.map(({ binding, id }) => {
+ return {
+ key: binding,
+ value: id
+ };
+ })
+ });
+ }
+ if (send_email !== void 0 && send_email.length > 0) {
+ output.push({
+ type: "Send Email",
+ entries: send_email.map(
+ ({ name, destination_address, allowed_destination_addresses }) => {
+ return {
+ key: name,
+ value: destination_address || allowed_destination_addresses?.join(", ") || "unrestricted"
+ };
+ }
+ )
+ });
+ }
+ if (queues2 !== void 0 && queues2.length > 0) {
+ output.push({
+ type: "Queues",
+ entries: queues2.map(({ binding, queue_name }) => {
+ return {
+ key: binding,
+ value: queue_name
+ };
+ })
+ });
+ }
+ if (d1_databases !== void 0 && d1_databases.length > 0) {
+ output.push({
+ type: "D1 Databases",
+ entries: d1_databases.map(
+ ({ binding, database_name, database_id, preview_database_id }) => {
+ let databaseValue = `${database_id}`;
+ if (database_name) {
+ databaseValue = `${database_name} (${database_id})`;
+ }
+ if (preview_database_id && database_id !== "local") {
+ databaseValue += `, Preview: (${preview_database_id})`;
+ }
+ return {
+ key: binding,
+ value: databaseValue
+ };
+ }
+ )
+ });
+ }
+ if (constellation2 !== void 0 && constellation2.length > 0) {
+ output.push({
+ type: "Constellation Projects",
+ entries: constellation2.map(({ binding, project_id }) => {
+ return {
+ key: binding,
+ value: project_id
+ };
+ })
+ });
+ }
+ if (r2_buckets !== void 0 && r2_buckets.length > 0) {
+ output.push({
+ type: "R2 Buckets",
+ entries: r2_buckets.map(({ binding, bucket_name, jurisdiction }) => {
+ if (jurisdiction !== void 0) {
+ bucket_name += ` (${jurisdiction})`;
+ }
+ return {
+ key: binding,
+ value: bucket_name
+ };
+ })
+ });
+ }
+ if (logfwdr !== void 0 && logfwdr.bindings.length > 0) {
+ output.push({
+ type: "logfwdr",
+ entries: logfwdr.bindings.map((binding) => {
+ return {
+ key: binding.name,
+ value: binding.destination
+ };
+ })
+ });
+ }
+ if (services !== void 0 && services.length > 0) {
+ output.push({
+ type: "Services",
+ entries: services.map(({ binding, service, environment }) => {
+ let value = service;
+ if (environment) {
+ value += ` - ${environment}`;
+ }
+ return {
+ key: binding,
+ value
+ };
+ })
+ });
+ }
+ if (analytics_engine_datasets !== void 0 && analytics_engine_datasets.length > 0) {
+ output.push({
+ type: "Analytics Engine Datasets",
+ entries: analytics_engine_datasets.map(({ binding, dataset }) => {
+ return {
+ key: binding,
+ value: dataset ?? binding
+ };
+ })
+ });
+ }
+ if (text_blobs !== void 0 && Object.keys(text_blobs).length > 0) {
+ output.push({
+ type: "Text Blobs",
+ entries: Object.entries(text_blobs).map(([key, value]) => ({
+ key,
+ value: truncate2(value)
+ }))
+ });
+ }
+ if (browser !== void 0) {
+ output.push({
+ type: "Browser",
+ entries: [{ key: "Name", value: browser.binding }]
+ });
+ }
+ if (unsafe?.bindings !== void 0 && unsafe.bindings.length > 0) {
+ output.push({
+ type: "Unsafe",
+ entries: unsafe.bindings.map(({ name, type }) => ({
+ key: type,
+ value: name
+ }))
+ });
+ }
+ if (vars !== void 0 && Object.keys(vars).length > 0) {
+ output.push({
+ type: "Vars",
+ entries: Object.entries(vars).map(([key, value]) => {
+ let parsedValue;
+ if (typeof value === "string") {
+ parsedValue = `"${truncate2(value)}"`;
+ } else if (typeof value === "object") {
+ parsedValue = JSON.stringify(value, null, 1);
+ } else {
+ parsedValue = `${truncate2(`${value}`)}`;
+ }
+ return {
+ key,
+ value: parsedValue
+ };
+ })
+ });
+ }
+ if (wasm_modules !== void 0 && Object.keys(wasm_modules).length > 0) {
+ output.push({
+ type: "Wasm Modules",
+ entries: Object.entries(wasm_modules).map(([key, value]) => ({
+ key,
+ value: truncate2(value)
+ }))
+ });
+ }
+ if (dispatch_namespaces !== void 0 && dispatch_namespaces.length > 0) {
+ output.push({
+ type: "dispatch namespaces",
+ entries: dispatch_namespaces.map(({ binding, namespace, outbound }) => {
+ return {
+ key: binding,
+ value: outbound ? `${namespace} (outbound -> ${outbound.service})` : namespace
+ };
+ })
+ });
+ }
+ if (mtls_certificates !== void 0 && mtls_certificates.length > 0) {
+ output.push({
+ type: "mTLS Certificates",
+ entries: mtls_certificates.map(({ binding, certificate_id }) => {
+ return {
+ key: binding,
+ value: certificate_id
+ };
+ })
+ });
+ }
+ if (unsafe?.metadata !== void 0) {
+ output.push({
+ type: "Unsafe Metadata",
+ entries: Object.entries(unsafe.metadata).map(([key, value]) => ({
+ key,
+ value: `${value}`
+ }))
+ });
+ }
+ if (output.length === 0) {
+ return;
+ }
+ const message = [
+ `Your worker has access to the following bindings:`,
+ ...output.map((bindingGroup) => {
+ return [
+ `- ${bindingGroup.type}:`,
+ bindingGroup.entries.map(({ key, value }) => ` - ${key}: ${value}`)
+ ];
+ }).flat(2)
+ ].join("\n");
+ logger.log(message);
+}
+__name(printBindings, "printBindings");
+function withConfig(handler15) {
+ return (t2) => {
+ return handler15({ ...t2, config: readConfig(t2.config, t2) });
+ };
+}
+__name(withConfig, "withConfig");
+function tryLoadDotEnv(path45) {
+ try {
+ const parsed = import_dotenv.default.parse(import_node_fs4.default.readFileSync(path45));
+ return { path: path45, parsed };
+ } catch (e2) {
+ logger.debug(`Failed to load .env file "${path45}":`, e2);
+ }
+}
+__name(tryLoadDotEnv, "tryLoadDotEnv");
+function loadDotEnv(path45, env5) {
+ if (env5 === void 0) {
+ return tryLoadDotEnv(path45);
+ } else {
+ return tryLoadDotEnv(`${path45}.${env5}`) ?? tryLoadDotEnv(path45);
+ }
+}
+__name(loadDotEnv, "loadDotEnv");
+
+// src/deployment-bundle/entry.ts
+init_import_meta_url();
+var import_node_path13 = __toESM(require("node:path"));
+
+// src/paths.ts
+init_import_meta_url();
+var import_node_console = require("node:console");
+var import_node_path7 = require("node:path");
+function toUrlPath(filePath) {
+ (0, import_node_console.assert)(
+ !/^[a-z]:/i.test(filePath),
+ "Tried to convert a Windows file path with a drive to a URL path."
+ );
+ return filePath.replace(/\\/g, "/");
+}
+__name(toUrlPath, "toUrlPath");
+function readableRelative(to) {
+ const relativePath = (0, import_node_path7.relative)(process.cwd(), to);
+ if (
+ // No directory nesting, return as-is
+ (0, import_node_path7.basename)(relativePath) === relativePath || // Outside current directory
+ relativePath.startsWith(".")
+ ) {
+ return relativePath;
+ } else {
+ return "./" + relativePath;
+ }
+}
+__name(readableRelative, "readableRelative");
+function getBasePath() {
+ return (0, import_node_path7.resolve)(__dirname, "..");
+}
+__name(getBasePath, "getBasePath");
+
+// src/deployment-bundle/guess-worker-format.ts
+init_import_meta_url();
+var import_node_path9 = __toESM(require("node:path"));
+var esbuild2 = __toESM(require("esbuild"));
+
+// src/deployment-bundle/bundle.ts
+init_import_meta_url();
+var fs5 = __toESM(require("node:fs"));
+var import_node_module = require("node:module");
+var path8 = __toESM(require("node:path"));
+var import_node_globals_polyfill = __toESM(require("@esbuild-plugins/node-globals-polyfill"));
+var import_node_modules_polyfill = __toESM(require("@esbuild-plugins/node-modules-polyfill"));
+var esbuild = __toESM(require("esbuild"));
+var import_tmp_promise = __toESM(require_tmp_promise());
+
+// src/module-collection.ts
+init_import_meta_url();
+var import_node_crypto3 = __toESM(require("node:crypto"));
+var import_promises = require("node:fs/promises");
+var import_node_path8 = __toESM(require("node:path"));
+var import_chalk3 = __toESM(require_chalk());
+var import_glob_to_regexp = __toESM(require_glob_to_regexp());
+function flipObject(obj) {
+ return Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));
+}
+__name(flipObject, "flipObject");
+var RuleTypeToModuleType = {
+ ESModule: "esm",
+ CommonJS: "commonjs",
+ CompiledWasm: "compiled-wasm",
+ Data: "buffer",
+ Text: "text"
+};
+var ModuleTypeToRuleType = flipObject(RuleTypeToModuleType);
+var DEFAULT_MODULE_RULES = [
+ { type: "Text", globs: ["**/*.txt", "**/*.html"] },
+ { type: "Data", globs: ["**/*.bin"] },
+ { type: "CompiledWasm", globs: ["**/*.wasm", "**/*.wasm?module"] }
+];
+function parseRules(userRules = []) {
+ const rules = [...userRules, ...DEFAULT_MODULE_RULES];
+ const completedRuleLocations = {};
+ let index = 0;
+ const rulesToRemove = [];
+ for (const rule of rules) {
+ if (rule.type in completedRuleLocations) {
+ if (rules[completedRuleLocations[rule.type]].fallthrough !== false) {
+ if (index < userRules.length) {
+ logger.warn(
+ `The module rule at position ${index} (${JSON.stringify(
+ rule
+ )}) has the same type as a previous rule (at position ${completedRuleLocations[rule.type]}, ${JSON.stringify(
+ rules[completedRuleLocations[rule.type]]
+ )}). This rule will be ignored. To the previous rule, add \`fallthrough = true\` to allow this one to also be used, or \`fallthrough = false\` to silence this warning.`
+ );
+ } else {
+ logger.warn(
+ `The default module rule ${JSON.stringify(
+ rule
+ )} has the same type as a previous rule (at position ${completedRuleLocations[rule.type]}, ${JSON.stringify(
+ rules[completedRuleLocations[rule.type]]
+ )}). This rule will be ignored. To the previous rule, add \`fallthrough = true\` to allow the default one to also be used, or \`fallthrough = false\` to silence this warning.`
+ );
+ }
+ }
+ rulesToRemove.push(rule);
+ }
+ if (!(rule.type in completedRuleLocations) && rule.fallthrough !== true) {
+ completedRuleLocations[rule.type] = index;
+ }
+ index++;
+ }
+ rulesToRemove.forEach((rule) => rules.splice(rules.indexOf(rule), 1));
+ return { rules, removedRules: rulesToRemove };
+}
+__name(parseRules, "parseRules");
+async function matchFiles(files, relativeTo, {
+ rules,
+ removedRules
+}) {
+ const modules = [];
+ const moduleNames = /* @__PURE__ */ new Set();
+ for (const rule of rules) {
+ for (const glob of rule.globs) {
+ const regexp = (0, import_glob_to_regexp.default)(glob, {
+ globstar: true
+ });
+ const newModules = await Promise.all(
+ files.filter((f) => regexp.test(f)).map(async (name) => {
+ const filePath = import_node_path8.default.join(relativeTo, name);
+ const fileContent = await (0, import_promises.readFile)(filePath);
+ return {
+ name,
+ filePath,
+ content: fileContent,
+ type: RuleTypeToModuleType[rule.type]
+ };
+ })
+ );
+ for (const module2 of newModules) {
+ if (!moduleNames.has(module2.name)) {
+ moduleNames.add(module2.name);
+ modules.push(module2);
+ } else {
+ logger.warn(
+ `Ignoring duplicate module: ${import_chalk3.default.blue(
+ module2.name
+ )} (${import_chalk3.default.green(module2.type ?? "")})`
+ );
+ }
+ }
+ }
+ }
+ for (const rule of removedRules) {
+ for (const glob of rule.globs) {
+ const regexp = (0, import_glob_to_regexp.default)(glob);
+ for (const file of files) {
+ if (regexp.test(file)) {
+ throw new Error(
+ `The file ${file} matched a module rule in your configuration (${JSON.stringify(
+ rule
+ )}), but was ignored because a previous rule with the same type was not marked as \`fallthrough = true\`.`
+ );
+ }
+ }
+ }
+ }
+ return modules;
+}
+__name(matchFiles, "matchFiles");
+function createModuleCollector(props) {
+ const { rules, removedRules } = parseRules(props.rules);
+ const modules = [];
+ return {
+ modules,
+ plugin: {
+ name: "wrangler-module-collector",
+ setup(build5) {
+ build5.onStart(() => {
+ modules.splice(0);
+ });
+ const rulesMatchers = rules.flatMap((rule) => {
+ return rule.globs.map((glob) => {
+ const regex = (0, import_glob_to_regexp.default)(glob);
+ return {
+ regex,
+ rule
+ };
+ });
+ });
+ if (props.wrangler1xlegacyModuleReferences.fileNames.size > 0) {
+ build5.onResolve(
+ {
+ filter: new RegExp(
+ "^(" + [...props.wrangler1xlegacyModuleReferences.fileNames].map((name) => name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|") + ")$"
+ )
+ },
+ async (args) => {
+ if (args.kind !== "import-statement" && args.kind !== "require-call") {
+ return;
+ }
+ logger.warn(
+ `Deprecation: detected a legacy module import in "./${import_node_path8.default.relative(
+ process.cwd(),
+ args.importer
+ )}". This will stop working in the future. Replace references to "${args.path}" with "./${args.path}";`
+ );
+ const filePath = import_node_path8.default.join(
+ props.wrangler1xlegacyModuleReferences.rootDirectory,
+ args.path
+ );
+ const fileContent = await (0, import_promises.readFile)(filePath);
+ const fileHash = import_node_crypto3.default.createHash("sha1").update(fileContent).digest("hex");
+ const fileName = `./${fileHash}-${import_node_path8.default.basename(args.path)}`;
+ const { rule } = rulesMatchers.find(({ regex }) => regex.test(fileName)) || {};
+ if (rule) {
+ modules.push({
+ name: fileName,
+ filePath,
+ content: fileContent,
+ type: RuleTypeToModuleType[rule.type]
+ });
+ return {
+ path: fileName,
+ // change the reference to the changed module
+ external: props.format === "modules",
+ // mark it as external in the bundle
+ namespace: `wrangler-module-${rule.type}`,
+ // just a tag, this isn't strictly necessary
+ watchFiles: [filePath]
+ // we also add the file to esbuild's watch list
+ };
+ }
+ }
+ );
+ }
+ rules?.forEach((rule) => {
+ if (rule.type === "ESModule" || rule.type === "CommonJS")
+ return;
+ rule.globs.forEach((glob) => {
+ build5.onResolve(
+ { filter: (0, import_glob_to_regexp.default)(glob) },
+ async (args) => {
+ const filePath = import_node_path8.default.join(args.resolveDir, args.path);
+ const fileContent = await (0, import_promises.readFile)(filePath);
+ const fileHash = import_node_crypto3.default.createHash("sha1").update(fileContent).digest("hex");
+ const fileName = props.preserveFileNames ? filePath : `./${fileHash}-${import_node_path8.default.basename(args.path)}`;
+ modules.push({
+ name: fileName,
+ filePath,
+ content: fileContent,
+ type: RuleTypeToModuleType[rule.type]
+ });
+ return {
+ path: fileName,
+ // change the reference to the changed module
+ external: props.format === "modules",
+ // mark it as external in the bundle
+ namespace: `wrangler-module-${rule.type}`,
+ // just a tag, this isn't strictly necessary
+ watchFiles: [filePath]
+ // we also add the file to esbuild's watch list
+ };
+ }
+ );
+ if (props.format === "service-worker") {
+ build5.onLoad(
+ { filter: (0, import_glob_to_regexp.default)(glob) },
+ async (args) => {
+ return {
+ // We replace the the module with an identifier
+ // that we'll separately add to the form upload
+ // as part of [wasm_modules]/[text_blobs]/[data_blobs]. This identifier has to be a valid
+ // JS identifier, so we replace all non alphanumeric characters
+ // with an underscore.
+ contents: `export default ${args.path.replace(
+ /[^a-zA-Z0-9_$]/g,
+ "_"
+ )};`
+ };
+ }
+ );
+ }
+ });
+ });
+ removedRules.forEach((rule) => {
+ rule.globs.forEach((glob) => {
+ build5.onResolve(
+ { filter: (0, import_glob_to_regexp.default)(glob) },
+ async (args) => {
+ throw new Error(
+ `The file ${args.path} matched a module rule in your configuration (${JSON.stringify(
+ rule
+ )}), but was ignored because a previous rule with the same type was not marked as \`fallthrough = true\`.`
+ );
+ }
+ );
+ });
+ });
+ }
+ }
+ };
+}
+__name(createModuleCollector, "createModuleCollector");
+
+// src/utils/dedent.ts
+init_import_meta_url();
+var import_node_assert3 = __toESM(require("node:assert"));
+function dedent(strings, ...values) {
+ const raw = String.raw({ raw: strings }, ...values);
+ let lines = raw.split("\n");
+ (0, import_node_assert3.default)(lines.length > 0);
+ if (lines[lines.length - 1].trim() === "") {
+ lines = lines.slice(0, lines.length - 1);
+ }
+ let minIndent = "";
+ let minIndentLength = Infinity;
+ for (const line of lines.slice(1)) {
+ const indent = line.match(/^[ \t]*/)?.[0];
+ if (indent != null && indent.length < minIndentLength) {
+ minIndent = indent;
+ minIndentLength = indent.length;
+ }
+ }
+ if (lines.length > 0 && lines[0].trim() === "")
+ lines = lines.slice(1);
+ lines = lines.map(
+ (line) => line.startsWith(minIndent) ? line.substring(minIndent.length) : line
+ );
+ return lines.join("\n");
+}
+__name(dedent, "dedent");
+
+// src/deployment-bundle/entry-point-from-metafile.ts
+init_import_meta_url();
+var import_node_assert4 = __toESM(require("node:assert"));
+function getEntryPointFromMetafile(entryFile, metafile) {
+ const entryPoints = Object.entries(metafile.outputs).filter(
+ ([_path, output]) => output.entryPoint !== void 0
+ );
+ if (entryPoints.length !== 1) {
+ const entryPointList = entryPoints.map(([_input, output]) => output.entryPoint).join("\n");
+ (0, import_node_assert4.default)(
+ entryPoints.length > 0,
+ `Cannot find entry-point "${entryFile}" in generated bundle.
+${entryPointList}`
+ );
+ (0, import_node_assert4.default)(
+ entryPoints.length < 2,
+ `More than one entry-point found for generated bundle.
+${entryPointList}`
+ );
+ }
+ const [relativePath, entryPoint] = entryPoints[0];
+ return {
+ relativePath,
+ exports: entryPoint.exports,
+ dependencies: entryPoint.inputs
+ };
+}
+__name(getEntryPointFromMetafile, "getEntryPointFromMetafile");
+
+// src/deployment-bundle/esbuild-plugins/cloudflare-internal.ts
+init_import_meta_url();
+var cloudflareInternalPlugin = {
+ name: "Cloudflare internal imports plugin",
+ setup(pluginBuild) {
+ pluginBuild.onResolve({ filter: /^cloudflare:.*/ }, () => {
+ return { external: true };
+ });
+ }
+};
+
+// src/deployment-bundle/esbuild-plugins/config-provider.ts
+init_import_meta_url();
+function configProviderPlugin(config) {
+ return {
+ name: "middleware config provider plugin",
+ setup(build5) {
+ build5.onResolve({ filter: /^config:/ }, (args) => ({
+ path: args.path,
+ namespace: "wrangler-config"
+ }));
+ build5.onLoad(
+ { filter: /.*/, namespace: "wrangler-config" },
+ async (args) => {
+ const middleware = args.path.split("config:middleware/")[1];
+ if (!config[middleware]) {
+ throw new Error(`No config found for ${middleware}`);
+ }
+ return {
+ loader: "json",
+ contents: JSON.stringify(config[middleware])
+ };
+ }
+ );
+ }
+ };
+}
+__name(configProviderPlugin, "configProviderPlugin");
+
+// src/deployment-bundle/esbuild-plugins/nodejs-compat.ts
+init_import_meta_url();
+var nodejsCompatPlugin = {
+ name: "nodejs_compat imports plugin",
+ setup(pluginBuild) {
+ pluginBuild.onResolve({ filter: /node:.*/ }, () => {
+ return { external: true };
+ });
+ }
+};
+
+// src/deployment-bundle/bundle.ts
+var COMMON_ESBUILD_OPTIONS = {
+ // Our workerd runtime uses the same V8 version as recent Chrome, which is highly ES2022 compliant: https://kangax.github.io/compat-table/es2016plus/
+ target: "es2022",
+ loader: { ".js": "jsx", ".mjs": "jsx", ".cjs": "jsx" }
+};
+var nodeBuiltinResolveErrorText = new RegExp(
+ '^Could not resolve "(' + import_node_module.builtinModules.join("|") + "|" + import_node_module.builtinModules.map((module2) => "node:" + module2).join("|") + ')"$'
+);
+function isBuildFailure(err) {
+ return typeof err === "object" && err !== null && "errors" in err && "warnings" in err;
+}
+__name(isBuildFailure, "isBuildFailure");
+function rewriteNodeCompatBuildFailure(errors, forPages = false) {
+ for (const error of errors) {
+ const match = nodeBuiltinResolveErrorText.exec(error.text);
+ if (match !== null) {
+ const issue = `The package "${match[1]}" wasn't found on the file system but is built into node.`;
+ const instructionForUser = `${forPages ? 'Add the "nodejs_compat" compatibility flag to your Pages project' : 'Add "node_compat = true" to your wrangler.toml file'} to enable Node.js compatibility.`;
+ error.notes = [
+ {
+ location: null,
+ text: `${issue}
+${instructionForUser}`
+ }
+ ];
+ }
+ }
+}
+__name(rewriteNodeCompatBuildFailure, "rewriteNodeCompatBuildFailure");
+async function bundleWorker(entry, destination, options14) {
+ const {
+ bundle = true,
+ serveAssetsFromWorker,
+ doBindings,
+ jsxFactory,
+ jsxFragment,
+ entryName,
+ rules,
+ watch: watch6,
+ tsconfig,
+ minify,
+ legacyNodeCompat,
+ nodejsCompat,
+ checkFetch,
+ assets,
+ workerDefinitions,
+ services,
+ targetConsumer,
+ testScheduled,
+ inject: injectOption,
+ loader,
+ sourcemap,
+ plugins,
+ disableModuleCollection,
+ isOutfile,
+ forPages,
+ additionalModules = [],
+ local
+ } = options14;
+ const unsafeTmpDir = await import_tmp_promise.default.dir({ unsafeCleanup: true });
+ const tmpDirPath = fs5.realpathSync(unsafeTmpDir.path);
+ const entryDirectory = path8.dirname(entry.file);
+ let moduleCollector = createModuleCollector({
+ wrangler1xlegacyModuleReferences: {
+ rootDirectory: entryDirectory,
+ fileNames: new Set(
+ fs5.readdirSync(entryDirectory, { withFileTypes: true }).filter(
+ (dirEntry) => dirEntry.isFile() && dirEntry.name !== path8.basename(entry.file)
+ ).map((dirEnt) => dirEnt.name)
+ )
+ },
+ format: entry.format,
+ rules
+ });
+ if (disableModuleCollection) {
+ moduleCollector = {
+ modules: [],
+ plugin: {
+ name: moduleCollector.plugin.name,
+ setup: () => {
+ }
+ }
+ };
+ }
+ const checkedFetchFileToInject = path8.join(tmpDirPath, "checked-fetch.js");
+ if (checkFetch && !fs5.existsSync(checkedFetchFileToInject)) {
+ fs5.mkdirSync(tmpDirPath, {
+ recursive: true
+ });
+ fs5.writeFileSync(
+ checkedFetchFileToInject,
+ fs5.readFileSync(path8.resolve(getBasePath(), "templates/checked-fetch.js"))
+ );
+ }
+ const middlewareToLoad = [
+ {
+ name: "scheduled",
+ path: "templates/middleware/middleware-scheduled.ts",
+ active: targetConsumer === "dev" && !!testScheduled
+ },
+ // In Miniflare 3, we bind the user's worker as a service binding in a
+ // special entry worker that handles things like injecting `Request.cf`,
+ // live-reload, and the pretty-error page.
+ //
+ // Unfortunately, due to a bug in `workerd`, errors thrown asynchronously by
+ // native APIs don't have `stack`s. This means Miniflare can't extract the
+ // `stack` trace from dispatching to the user worker service binding by
+ // `try/catch`.
+ //
+ // As a stop-gap solution, if the `MF-Experimental-Error-Stack` header is
+ // truthy on responses, the body will be interpreted as a JSON-error of the
+ // form `{ message?: string, name?: string, stack?: string }`.
+ //
+ // This middleware wraps the user's worker in a `try/catch`, and rewrites
+ // errors in this format so a pretty-error page can be shown.
+ {
+ name: "miniflare3-json-error",
+ path: "templates/middleware/middleware-miniflare3-json-error.ts",
+ active: targetConsumer === "dev" && local
+ },
+ {
+ name: "serve-static-assets",
+ path: "templates/middleware/middleware-serve-static-assets.ts",
+ active: serveAssetsFromWorker,
+ config: {
+ spaMode: typeof assets === "object" ? assets.serve_single_page_app : false,
+ cacheControl: typeof assets === "object" ? {
+ browserTTL: assets.browser_TTL || 172800,
+ bypassCache: assets.bypassCache
+ } : {}
+ }
+ },
+ {
+ name: "multiworker-dev",
+ path: "templates/middleware/middleware-multiworker-dev.ts",
+ active: targetConsumer === "dev" && !!(workerDefinitions && Object.keys(workerDefinitions).length > 0 && services && services.length > 0),
+ config: {
+ workers: Object.fromEntries(
+ (services || []).map((serviceBinding) => [
+ serviceBinding.binding,
+ workerDefinitions?.[serviceBinding.service] || null
+ ])
+ )
+ }
+ }
+ ];
+ let initialBuildResult;
+ const initialBuildResultPromise = new Promise(
+ (resolve18) => initialBuildResult = resolve18
+ );
+ const buildResultPlugin = {
+ name: "Initial build result plugin",
+ setup(build5) {
+ build5.onEnd(initialBuildResult);
+ }
+ };
+ const inject = injectOption ?? [];
+ if (checkFetch)
+ inject.push(checkedFetchFileToInject);
+ const activeMiddleware = middlewareToLoad.filter(
+ // We dynamically filter the middleware depending on where we are bundling for
+ (m) => m.active
+ );
+ let inputEntry = entry;
+ if (activeMiddleware.length > 0 || process.env.EXPERIMENTAL_MIDDLEWARE === "true") {
+ inputEntry = await applyMiddlewareLoaderFacade(
+ entry,
+ tmpDirPath,
+ activeMiddleware,
+ doBindings
+ );
+ if (inputEntry.inject !== void 0)
+ inject.push(...inputEntry.inject);
+ }
+ const buildOptions2 = {
+ entryPoints: [inputEntry.file],
+ bundle,
+ absWorkingDir: entry.directory,
+ outdir: destination,
+ entryNames: entryName || path8.parse(entry.file).name,
+ ...isOutfile ? {
+ outdir: void 0,
+ outfile: destination,
+ entryNames: void 0
+ } : {},
+ inject,
+ external: bundle ? ["__STATIC_CONTENT_MANIFEST"] : void 0,
+ format: entry.format === "modules" ? "esm" : "iife",
+ target: COMMON_ESBUILD_OPTIONS.target,
+ sourcemap: sourcemap ?? true,
+ // Include a reference to the output folder in the sourcemap.
+ // This is omitted by default, but we need it to properly resolve source paths in error output.
+ sourceRoot: destination,
+ minify,
+ metafile: true,
+ conditions: ["workerd", "worker", "browser"],
+ ...{
+ define: {
+ // use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
+ // when we do a build of wrangler. (re: https://github.com/cloudflare/workers-sdk/issues/1477)
+ "process.env.NODE_ENV": `"${process.env["NODE_ENV"]}"`,
+ ...legacyNodeCompat ? { global: "globalThis" } : {},
+ ...options14.define
+ }
+ },
+ loader: {
+ ...COMMON_ESBUILD_OPTIONS.loader,
+ ...loader || {}
+ },
+ plugins: [
+ moduleCollector.plugin,
+ ...legacyNodeCompat ? [(0, import_node_globals_polyfill.default)({ buffer: true }), (0, import_node_modules_polyfill.default)()] : [],
+ ...nodejsCompat ? [nodejsCompatPlugin] : [],
+ cloudflareInternalPlugin,
+ buildResultPlugin,
+ ...plugins || [],
+ configProviderPlugin(
+ Object.fromEntries(
+ middlewareToLoad.filter((m) => m.config !== void 0).map((m) => [m.name, m.config])
+ )
+ )
+ ],
+ ...jsxFactory && { jsxFactory },
+ ...jsxFragment && { jsxFragment },
+ ...tsconfig && { tsconfig },
+ // The default logLevel is "warning". So that we can rewrite errors before
+ // logging, we disable esbuild's default logging, and log build failures
+ // ourselves.
+ logLevel: "silent"
+ };
+ let result;
+ let stop;
+ try {
+ if (watch6) {
+ const ctx = await esbuild.context(buildOptions2);
+ await ctx.watch();
+ result = await initialBuildResultPromise;
+ if (result.errors.length > 0) {
+ throw new Error("Failed to build");
+ }
+ stop = /* @__PURE__ */ __name(async function() {
+ await ctx.dispose();
+ }, "stop");
+ } else {
+ result = await esbuild.build(buildOptions2);
+ }
+ } catch (e2) {
+ if (!legacyNodeCompat && isBuildFailure(e2))
+ rewriteNodeCompatBuildFailure(e2.errors, forPages);
+ throw e2;
+ }
+ const entryPoint = getEntryPointFromMetafile(entry.file, result.metafile);
+ const bundleType = entryPoint.exports.length > 0 ? "esm" : "commonjs";
+ const sourceMapPath = Object.keys(result.metafile.outputs).filter(
+ (_path) => _path.includes(".map")
+ )[0];
+ const resolvedEntryPointPath = path8.resolve(
+ entry.directory,
+ entryPoint.relativePath
+ );
+ const modules = dedupeModulesByName([
+ ...moduleCollector.modules,
+ ...additionalModules
+ ]);
+ for (const module2 of modules) {
+ const modulePath = path8.join(
+ path8.dirname(resolvedEntryPointPath),
+ module2.name
+ );
+ fs5.mkdirSync(path8.dirname(modulePath), { recursive: true });
+ fs5.writeFileSync(modulePath, module2.content);
+ }
+ return {
+ modules,
+ dependencies: entryPoint.dependencies,
+ resolvedEntryPointPath,
+ bundleType,
+ stop,
+ sourceMapPath,
+ sourceMapMetadata: {
+ tmpDir: tmpDirPath,
+ entryDirectory: entry.directory
+ },
+ moduleCollector
+ };
+}
+__name(bundleWorker, "bundleWorker");
+async function applyMiddlewareLoaderFacade(entry, tmpDirPath, middleware, doBindings) {
+ const middlewareIdentifiers = middleware.map((m, index) => [
+ `__MIDDLEWARE_${index}__`,
+ path8.resolve(getBasePath(), m.path)
+ ]);
+ const dynamicFacadePath = path8.join(
+ tmpDirPath,
+ "middleware-insertion-facade.js"
+ );
+ const imports = middlewareIdentifiers.map(
+ ([id, middlewarePath]) => (
+ /*javascript*/
+ `import * as ${id} from "${prepareFilePath(
+ middlewarePath
+ )}";`
+ )
+ ).join("\n");
+ const middlewareFns = middlewareIdentifiers.map(([m]) => `${m}.default`);
+ if (entry.format === "modules") {
+ const middlewareWrappers = middlewareIdentifiers.map(([m]) => `${m}.wrap`).join(",");
+ const durableObjects = doBindings.filter((b) => !b.script_name).map(
+ (b) => (
+ /*javascript*/
+ `export const ${b.class_name} = maskDurableObjectDefinition(OTHER_EXPORTS.${b.class_name});`
+ )
+ ).join("\n");
+ await fs5.promises.writeFile(
+ dynamicFacadePath,
+ dedent`
+ import worker, * as OTHER_EXPORTS from "${prepareFilePath(entry.file)}";
+ ${imports}
+ const envWrappers = [${middlewareWrappers}].filter(Boolean);
+ const facade = {
+ ...worker,
+ envWrappers,
+ middleware: [
+ ${middlewareFns.join(",")},
+ ...(worker.middleware ? worker.middleware : []),
+ ].filter(Boolean)
+ }
+ export * from "${prepareFilePath(entry.file)}";
+
+ const maskDurableObjectDefinition = (cls) =>
+ class extends cls {
+ constructor(state, env) {
+ let wrappedEnv = env
+ for (const wrapFn of envWrappers) {
+ wrappedEnv = wrapFn(wrappedEnv)
+ }
+ super(state, wrappedEnv);
+ }
+ };
+ ${durableObjects}
+
+ export default facade;
+ `
+ );
+ const targetPathLoader = path8.join(
+ tmpDirPath,
+ "middleware-loader.entry.ts"
+ );
+ const loaderPath = path8.resolve(
+ getBasePath(),
+ "templates/middleware/loader-modules.ts"
+ );
+ const baseLoader = await fs5.promises.readFile(loaderPath, "utf-8");
+ const transformedLoader = baseLoader.replaceAll("__ENTRY_POINT__", prepareFilePath(dynamicFacadePath)).replace(
+ "./common",
+ prepareFilePath(
+ path8.resolve(getBasePath(), "templates/middleware/common.ts")
+ )
+ );
+ await fs5.promises.writeFile(targetPathLoader, transformedLoader);
+ return {
+ ...entry,
+ file: targetPathLoader
+ };
+ } else {
+ const loaderSwPath = path8.resolve(
+ getBasePath(),
+ "templates/middleware/loader-sw.ts"
+ );
+ await fs5.promises.writeFile(
+ dynamicFacadePath,
+ dedent`
+ import { __facade_registerInternal__ } from "${prepareFilePath(loaderSwPath)}";
+ ${imports}
+ __facade_registerInternal__([${middlewareFns}])
+ `
+ );
+ return {
+ ...entry,
+ inject: [dynamicFacadePath]
+ };
+ }
+}
+__name(applyMiddlewareLoaderFacade, "applyMiddlewareLoaderFacade");
+function dedupeModulesByName(modules) {
+ return Object.values(
+ modules.reduce((moduleMap, module2) => {
+ moduleMap[module2.name] = module2;
+ return moduleMap;
+ }, {})
+ );
+}
+__name(dedupeModulesByName, "dedupeModulesByName");
+function prepareFilePath(filePath) {
+ return JSON.stringify(filePath).slice(1, -1);
+}
+__name(prepareFilePath, "prepareFilePath");
+
+// src/deployment-bundle/guess-worker-format.ts
+async function guessWorkerFormat(entryFile, entryWorkingDirectory, hint, tsconfig) {
+ const result = await esbuild2.build({
+ ...COMMON_ESBUILD_OPTIONS,
+ entryPoints: [entryFile],
+ absWorkingDir: entryWorkingDirectory,
+ metafile: true,
+ bundle: false,
+ write: false,
+ ...tsconfig && { tsconfig }
+ });
+ const metafile = result.metafile;
+ const { exports: exports2 } = getEntryPointFromMetafile(entryFile, metafile);
+ let guessedWorkerFormat;
+ if (exports2.length > 0) {
+ if (exports2.includes("default")) {
+ guessedWorkerFormat = "modules";
+ } else {
+ logger.warn(
+ `The entrypoint ${import_node_path9.default.relative(
+ process.cwd(),
+ entryFile
+ )} has exports like an ES Module, but hasn't defined a default export like a module worker normally would. Building the worker using "service-worker" format...`
+ );
+ guessedWorkerFormat = "service-worker";
+ }
+ } else {
+ guessedWorkerFormat = "service-worker";
+ }
+ if (hint) {
+ if (hint !== guessedWorkerFormat) {
+ if (hint === "service-worker") {
+ throw new Error(
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have a `default` export like a module worker. Please pass `--format modules`, or simply remove the configuration."
+ );
+ } else {
+ throw new Error(
+ "You configured this worker to be 'modules', but the file you are trying to build doesn't export a handler. Please pass `--format service-worker`, or simply remove the configuration."
+ );
+ }
+ }
+ }
+ return guessedWorkerFormat;
+}
+__name(guessWorkerFormat, "guessWorkerFormat");
+
+// src/deployment-bundle/run-custom-build.ts
+init_import_meta_url();
+var import_node_fs5 = require("node:fs");
+var import_node_path12 = __toESM(require("node:path"));
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/index.js
+init_import_meta_url();
+var import_node_buffer = require("node:buffer");
+var import_node_path11 = __toESM(require("node:path"), 1);
+var import_node_child_process = __toESM(require("node:child_process"), 1);
+var import_node_process3 = __toESM(require("node:process"), 1);
+var import_cross_spawn = __toESM(require_cross_spawn(), 1);
+
+// ../../node_modules/.pnpm/strip-final-newline@3.0.0/node_modules/strip-final-newline/index.js
+init_import_meta_url();
+function stripFinalNewline(input) {
+ const LF = typeof input === "string" ? "\n" : "\n".charCodeAt();
+ const CR = typeof input === "string" ? "\r" : "\r".charCodeAt();
+ if (input[input.length - 1] === LF) {
+ input = input.slice(0, -1);
+ }
+ if (input[input.length - 1] === CR) {
+ input = input.slice(0, -1);
+ }
+ return input;
+}
+__name(stripFinalNewline, "stripFinalNewline");
+
+// ../../node_modules/.pnpm/npm-run-path@5.1.0/node_modules/npm-run-path/index.js
+init_import_meta_url();
+var import_node_process2 = __toESM(require("node:process"), 1);
+var import_node_path10 = __toESM(require("node:path"), 1);
+var import_node_url5 = __toESM(require("node:url"), 1);
+
+// ../../node_modules/.pnpm/path-key@4.0.0/node_modules/path-key/index.js
+init_import_meta_url();
+function pathKey(options14 = {}) {
+ const {
+ env: env5 = process.env,
+ platform = process.platform
+ } = options14;
+ if (platform !== "win32") {
+ return "PATH";
+ }
+ return Object.keys(env5).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
+}
+__name(pathKey, "pathKey");
+
+// ../../node_modules/.pnpm/npm-run-path@5.1.0/node_modules/npm-run-path/index.js
+function npmRunPath(options14 = {}) {
+ const {
+ cwd: cwd2 = import_node_process2.default.cwd(),
+ path: path_ = import_node_process2.default.env[pathKey()],
+ execPath = import_node_process2.default.execPath
+ } = options14;
+ let previous;
+ const cwdString = cwd2 instanceof URL ? import_node_url5.default.fileURLToPath(cwd2) : cwd2;
+ let cwdPath = import_node_path10.default.resolve(cwdString);
+ const result = [];
+ while (previous !== cwdPath) {
+ result.push(import_node_path10.default.join(cwdPath, "node_modules/.bin"));
+ previous = cwdPath;
+ cwdPath = import_node_path10.default.resolve(cwdPath, "..");
+ }
+ result.push(import_node_path10.default.resolve(cwdString, execPath, ".."));
+ return [...result, path_].join(import_node_path10.default.delimiter);
+}
+__name(npmRunPath, "npmRunPath");
+function npmRunPathEnv({ env: env5 = import_node_process2.default.env, ...options14 } = {}) {
+ env5 = { ...env5 };
+ const path45 = pathKey({ env: env5 });
+ options14.path = env5[path45];
+ env5[path45] = npmRunPath(options14);
+ return env5;
+}
+__name(npmRunPathEnv, "npmRunPathEnv");
+
+// ../../node_modules/.pnpm/onetime@6.0.0/node_modules/onetime/index.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/mimic-fn@4.0.0/node_modules/mimic-fn/index.js
+init_import_meta_url();
+var copyProperty = /* @__PURE__ */ __name((to, from, property, ignoreNonConfigurable) => {
+ if (property === "length" || property === "prototype") {
+ return;
+ }
+ if (property === "arguments" || property === "caller") {
+ return;
+ }
+ const toDescriptor = Object.getOwnPropertyDescriptor(to, property);
+ const fromDescriptor = Object.getOwnPropertyDescriptor(from, property);
+ if (!canCopyProperty(toDescriptor, fromDescriptor) && ignoreNonConfigurable) {
+ return;
+ }
+ Object.defineProperty(to, property, fromDescriptor);
+}, "copyProperty");
+var canCopyProperty = /* @__PURE__ */ __name(function(toDescriptor, fromDescriptor) {
+ return toDescriptor === void 0 || toDescriptor.configurable || toDescriptor.writable === fromDescriptor.writable && toDescriptor.enumerable === fromDescriptor.enumerable && toDescriptor.configurable === fromDescriptor.configurable && (toDescriptor.writable || toDescriptor.value === fromDescriptor.value);
+}, "canCopyProperty");
+var changePrototype = /* @__PURE__ */ __name((to, from) => {
+ const fromPrototype = Object.getPrototypeOf(from);
+ if (fromPrototype === Object.getPrototypeOf(to)) {
+ return;
+ }
+ Object.setPrototypeOf(to, fromPrototype);
+}, "changePrototype");
+var wrappedToString = /* @__PURE__ */ __name((withName, fromBody) => `/* Wrapped ${withName}*/
+${fromBody}`, "wrappedToString");
+var toStringDescriptor = Object.getOwnPropertyDescriptor(Function.prototype, "toString");
+var toStringName = Object.getOwnPropertyDescriptor(Function.prototype.toString, "name");
+var changeToString = /* @__PURE__ */ __name((to, from, name) => {
+ const withName = name === "" ? "" : `with ${name.trim()}() `;
+ const newToString = wrappedToString.bind(null, withName, from.toString());
+ Object.defineProperty(newToString, "name", toStringName);
+ Object.defineProperty(to, "toString", { ...toStringDescriptor, value: newToString });
+}, "changeToString");
+function mimicFunction(to, from, { ignoreNonConfigurable = false } = {}) {
+ const { name } = to;
+ for (const property of Reflect.ownKeys(from)) {
+ copyProperty(to, from, property, ignoreNonConfigurable);
+ }
+ changePrototype(to, from);
+ changeToString(to, from, name);
+ return to;
+}
+__name(mimicFunction, "mimicFunction");
+
+// ../../node_modules/.pnpm/onetime@6.0.0/node_modules/onetime/index.js
+var calledFunctions = /* @__PURE__ */ new WeakMap();
+var onetime = /* @__PURE__ */ __name((function_, options14 = {}) => {
+ if (typeof function_ !== "function") {
+ throw new TypeError("Expected a function");
+ }
+ let returnValue;
+ let callCount = 0;
+ const functionName = function_.displayName || function_.name || "";
+ const onetime2 = /* @__PURE__ */ __name(function(...arguments_) {
+ calledFunctions.set(onetime2, ++callCount);
+ if (callCount === 1) {
+ returnValue = function_.apply(this, arguments_);
+ function_ = null;
+ } else if (options14.throw === true) {
+ throw new Error(`Function \`${functionName}\` can only be called once`);
+ }
+ return returnValue;
+ }, "onetime");
+ mimicFunction(onetime2, function_);
+ calledFunctions.set(onetime2, callCount);
+ return onetime2;
+}, "onetime");
+onetime.callCount = (function_) => {
+ if (!calledFunctions.has(function_)) {
+ throw new Error(`The given function \`${function_.name}\` is not wrapped by the \`onetime\` package`);
+ }
+ return calledFunctions.get(function_);
+};
+var onetime_default = onetime;
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/error.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/main.js
+init_import_meta_url();
+var import_os2 = require("os");
+
+// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/realtime.js
+init_import_meta_url();
+var getRealtimeSignals = /* @__PURE__ */ __name(function() {
+ const length = SIGRTMAX - SIGRTMIN + 1;
+ return Array.from({ length }, getRealtimeSignal);
+}, "getRealtimeSignals");
+var getRealtimeSignal = /* @__PURE__ */ __name(function(value, index) {
+ return {
+ name: `SIGRT${index + 1}`,
+ number: SIGRTMIN + index,
+ action: "terminate",
+ description: "Application-specific signal (realtime)",
+ standard: "posix"
+ };
+}, "getRealtimeSignal");
+var SIGRTMIN = 34;
+var SIGRTMAX = 64;
+
+// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/signals.js
+init_import_meta_url();
+var import_os = require("os");
+
+// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/core.js
+init_import_meta_url();
+var SIGNALS = [
+ {
+ name: "SIGHUP",
+ number: 1,
+ action: "terminate",
+ description: "Terminal closed",
+ standard: "posix"
+ },
+ {
+ name: "SIGINT",
+ number: 2,
+ action: "terminate",
+ description: "User interruption with CTRL-C",
+ standard: "ansi"
+ },
+ {
+ name: "SIGQUIT",
+ number: 3,
+ action: "core",
+ description: "User interruption with CTRL-\\",
+ standard: "posix"
+ },
+ {
+ name: "SIGILL",
+ number: 4,
+ action: "core",
+ description: "Invalid machine instruction",
+ standard: "ansi"
+ },
+ {
+ name: "SIGTRAP",
+ number: 5,
+ action: "core",
+ description: "Debugger breakpoint",
+ standard: "posix"
+ },
+ {
+ name: "SIGABRT",
+ number: 6,
+ action: "core",
+ description: "Aborted",
+ standard: "ansi"
+ },
+ {
+ name: "SIGIOT",
+ number: 6,
+ action: "core",
+ description: "Aborted",
+ standard: "bsd"
+ },
+ {
+ name: "SIGBUS",
+ number: 7,
+ action: "core",
+ description: "Bus error due to misaligned, non-existing address or paging error",
+ standard: "bsd"
+ },
+ {
+ name: "SIGEMT",
+ number: 7,
+ action: "terminate",
+ description: "Command should be emulated but is not implemented",
+ standard: "other"
+ },
+ {
+ name: "SIGFPE",
+ number: 8,
+ action: "core",
+ description: "Floating point arithmetic error",
+ standard: "ansi"
+ },
+ {
+ name: "SIGKILL",
+ number: 9,
+ action: "terminate",
+ description: "Forced termination",
+ standard: "posix",
+ forced: true
+ },
+ {
+ name: "SIGUSR1",
+ number: 10,
+ action: "terminate",
+ description: "Application-specific signal",
+ standard: "posix"
+ },
+ {
+ name: "SIGSEGV",
+ number: 11,
+ action: "core",
+ description: "Segmentation fault",
+ standard: "ansi"
+ },
+ {
+ name: "SIGUSR2",
+ number: 12,
+ action: "terminate",
+ description: "Application-specific signal",
+ standard: "posix"
+ },
+ {
+ name: "SIGPIPE",
+ number: 13,
+ action: "terminate",
+ description: "Broken pipe or socket",
+ standard: "posix"
+ },
+ {
+ name: "SIGALRM",
+ number: 14,
+ action: "terminate",
+ description: "Timeout or timer",
+ standard: "posix"
+ },
+ {
+ name: "SIGTERM",
+ number: 15,
+ action: "terminate",
+ description: "Termination",
+ standard: "ansi"
+ },
+ {
+ name: "SIGSTKFLT",
+ number: 16,
+ action: "terminate",
+ description: "Stack is empty or overflowed",
+ standard: "other"
+ },
+ {
+ name: "SIGCHLD",
+ number: 17,
+ action: "ignore",
+ description: "Child process terminated, paused or unpaused",
+ standard: "posix"
+ },
+ {
+ name: "SIGCLD",
+ number: 17,
+ action: "ignore",
+ description: "Child process terminated, paused or unpaused",
+ standard: "other"
+ },
+ {
+ name: "SIGCONT",
+ number: 18,
+ action: "unpause",
+ description: "Unpaused",
+ standard: "posix",
+ forced: true
+ },
+ {
+ name: "SIGSTOP",
+ number: 19,
+ action: "pause",
+ description: "Paused",
+ standard: "posix",
+ forced: true
+ },
+ {
+ name: "SIGTSTP",
+ number: 20,
+ action: "pause",
+ description: 'Paused using CTRL-Z or "suspend"',
+ standard: "posix"
+ },
+ {
+ name: "SIGTTIN",
+ number: 21,
+ action: "pause",
+ description: "Background process cannot read terminal input",
+ standard: "posix"
+ },
+ {
+ name: "SIGBREAK",
+ number: 21,
+ action: "terminate",
+ description: "User interruption with CTRL-BREAK",
+ standard: "other"
+ },
+ {
+ name: "SIGTTOU",
+ number: 22,
+ action: "pause",
+ description: "Background process cannot write to terminal output",
+ standard: "posix"
+ },
+ {
+ name: "SIGURG",
+ number: 23,
+ action: "ignore",
+ description: "Socket received out-of-band data",
+ standard: "bsd"
+ },
+ {
+ name: "SIGXCPU",
+ number: 24,
+ action: "core",
+ description: "Process timed out",
+ standard: "bsd"
+ },
+ {
+ name: "SIGXFSZ",
+ number: 25,
+ action: "core",
+ description: "File too big",
+ standard: "bsd"
+ },
+ {
+ name: "SIGVTALRM",
+ number: 26,
+ action: "terminate",
+ description: "Timeout or timer",
+ standard: "bsd"
+ },
+ {
+ name: "SIGPROF",
+ number: 27,
+ action: "terminate",
+ description: "Timeout or timer",
+ standard: "bsd"
+ },
+ {
+ name: "SIGWINCH",
+ number: 28,
+ action: "ignore",
+ description: "Terminal window size changed",
+ standard: "bsd"
+ },
+ {
+ name: "SIGIO",
+ number: 29,
+ action: "terminate",
+ description: "I/O is available",
+ standard: "other"
+ },
+ {
+ name: "SIGPOLL",
+ number: 29,
+ action: "terminate",
+ description: "Watched event",
+ standard: "other"
+ },
+ {
+ name: "SIGINFO",
+ number: 29,
+ action: "ignore",
+ description: "Request for process information",
+ standard: "other"
+ },
+ {
+ name: "SIGPWR",
+ number: 30,
+ action: "terminate",
+ description: "Device running out of power",
+ standard: "systemv"
+ },
+ {
+ name: "SIGSYS",
+ number: 31,
+ action: "core",
+ description: "Invalid system call",
+ standard: "other"
+ },
+ {
+ name: "SIGUNUSED",
+ number: 31,
+ action: "terminate",
+ description: "Invalid system call",
+ standard: "other"
+ }
+];
+
+// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/signals.js
+var getSignals = /* @__PURE__ */ __name(function() {
+ const realtimeSignals = getRealtimeSignals();
+ const signals = [...SIGNALS, ...realtimeSignals].map(normalizeSignal);
+ return signals;
+}, "getSignals");
+var normalizeSignal = /* @__PURE__ */ __name(function({
+ name,
+ number: defaultNumber,
+ description,
+ action,
+ forced = false,
+ standard
+}) {
+ const {
+ signals: { [name]: constantSignal }
+ } = import_os.constants;
+ const supported = constantSignal !== void 0;
+ const number = supported ? constantSignal : defaultNumber;
+ return { name, number, description, supported, action, forced, standard };
+}, "normalizeSignal");
+
+// ../../node_modules/.pnpm/human-signals@3.0.1/node_modules/human-signals/build/src/main.js
+var getSignalsByName = /* @__PURE__ */ __name(function() {
+ const signals = getSignals();
+ return signals.reduce(getSignalByName, {});
+}, "getSignalsByName");
+var getSignalByName = /* @__PURE__ */ __name(function(signalByNameMemo, { name, number, description, supported, action, forced, standard }) {
+ return {
+ ...signalByNameMemo,
+ [name]: { name, number, description, supported, action, forced, standard }
+ };
+}, "getSignalByName");
+var signalsByName = getSignalsByName();
+var getSignalsByNumber = /* @__PURE__ */ __name(function() {
+ const signals = getSignals();
+ const length = SIGRTMAX + 1;
+ const signalsA = Array.from({ length }, (value, number) => getSignalByNumber(number, signals));
+ return Object.assign({}, ...signalsA);
+}, "getSignalsByNumber");
+var getSignalByNumber = /* @__PURE__ */ __name(function(number, signals) {
+ const signal = findSignalByNumber(number, signals);
+ if (signal === void 0) {
+ return {};
+ }
+ const { name, description, supported, action, forced, standard } = signal;
+ return {
+ [number]: {
+ name,
+ number,
+ description,
+ supported,
+ action,
+ forced,
+ standard
+ }
+ };
+}, "getSignalByNumber");
+var findSignalByNumber = /* @__PURE__ */ __name(function(number, signals) {
+ const signal = signals.find(({ name }) => import_os2.constants.signals[name] === number);
+ if (signal !== void 0) {
+ return signal;
+ }
+ return signals.find((signalA) => signalA.number === number);
+}, "findSignalByNumber");
+var signalsByNumber = getSignalsByNumber();
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/error.js
+var getErrorPrefix = /* @__PURE__ */ __name(({ timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled }) => {
+ if (timedOut) {
+ return `timed out after ${timeout} milliseconds`;
+ }
+ if (isCanceled) {
+ return "was canceled";
+ }
+ if (errorCode !== void 0) {
+ return `failed with ${errorCode}`;
+ }
+ if (signal !== void 0) {
+ return `was killed with ${signal} (${signalDescription})`;
+ }
+ if (exitCode !== void 0) {
+ return `failed with exit code ${exitCode}`;
+ }
+ return "failed";
+}, "getErrorPrefix");
+var makeError = /* @__PURE__ */ __name(({
+ stdout,
+ stderr,
+ all: all2,
+ error,
+ signal,
+ exitCode,
+ command: command2,
+ escapedCommand,
+ timedOut,
+ isCanceled,
+ killed,
+ parsed: { options: { timeout } }
+}) => {
+ exitCode = exitCode === null ? void 0 : exitCode;
+ signal = signal === null ? void 0 : signal;
+ const signalDescription = signal === void 0 ? void 0 : signalsByName[signal].description;
+ const errorCode = error && error.code;
+ const prefix = getErrorPrefix({ timedOut, timeout, errorCode, signal, signalDescription, exitCode, isCanceled });
+ const execaMessage = `Command ${prefix}: ${command2}`;
+ const isError = Object.prototype.toString.call(error) === "[object Error]";
+ const shortMessage = isError ? `${execaMessage}
+${error.message}` : execaMessage;
+ const message = [shortMessage, stderr, stdout].filter(Boolean).join("\n");
+ if (isError) {
+ error.originalMessage = error.message;
+ error.message = message;
+ } else {
+ error = new Error(message);
+ }
+ error.shortMessage = shortMessage;
+ error.command = command2;
+ error.escapedCommand = escapedCommand;
+ error.exitCode = exitCode;
+ error.signal = signal;
+ error.signalDescription = signalDescription;
+ error.stdout = stdout;
+ error.stderr = stderr;
+ if (all2 !== void 0) {
+ error.all = all2;
+ }
+ if ("bufferedData" in error) {
+ delete error.bufferedData;
+ }
+ error.failed = true;
+ error.timedOut = Boolean(timedOut);
+ error.isCanceled = isCanceled;
+ error.killed = killed && !timedOut;
+ return error;
+}, "makeError");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stdio.js
+init_import_meta_url();
+var aliases = ["stdin", "stdout", "stderr"];
+var hasAlias = /* @__PURE__ */ __name((options14) => aliases.some((alias) => options14[alias] !== void 0), "hasAlias");
+var normalizeStdio = /* @__PURE__ */ __name((options14) => {
+ if (!options14) {
+ return;
+ }
+ const { stdio } = options14;
+ if (stdio === void 0) {
+ return aliases.map((alias) => options14[alias]);
+ }
+ if (hasAlias(options14)) {
+ throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${aliases.map((alias) => `\`${alias}\``).join(", ")}`);
+ }
+ if (typeof stdio === "string") {
+ return stdio;
+ }
+ if (!Array.isArray(stdio)) {
+ throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof stdio}\``);
+ }
+ const length = Math.max(stdio.length, aliases.length);
+ return Array.from({ length }, (value, index) => stdio[index]);
+}, "normalizeStdio");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/kill.js
+init_import_meta_url();
+var import_node_os3 = __toESM(require("node:os"), 1);
+var import_signal_exit = __toESM(require_signal_exit(), 1);
+var DEFAULT_FORCE_KILL_TIMEOUT = 1e3 * 5;
+var spawnedKill = /* @__PURE__ */ __name((kill, signal = "SIGTERM", options14 = {}) => {
+ const killResult = kill(signal);
+ setKillTimeout(kill, signal, options14, killResult);
+ return killResult;
+}, "spawnedKill");
+var setKillTimeout = /* @__PURE__ */ __name((kill, signal, options14, killResult) => {
+ if (!shouldForceKill(signal, options14, killResult)) {
+ return;
+ }
+ const timeout = getForceKillAfterTimeout(options14);
+ const t2 = setTimeout(() => {
+ kill("SIGKILL");
+ }, timeout);
+ if (t2.unref) {
+ t2.unref();
+ }
+}, "setKillTimeout");
+var shouldForceKill = /* @__PURE__ */ __name((signal, { forceKillAfterTimeout }, killResult) => isSigterm(signal) && forceKillAfterTimeout !== false && killResult, "shouldForceKill");
+var isSigterm = /* @__PURE__ */ __name((signal) => signal === import_node_os3.default.constants.signals.SIGTERM || typeof signal === "string" && signal.toUpperCase() === "SIGTERM", "isSigterm");
+var getForceKillAfterTimeout = /* @__PURE__ */ __name(({ forceKillAfterTimeout = true }) => {
+ if (forceKillAfterTimeout === true) {
+ return DEFAULT_FORCE_KILL_TIMEOUT;
+ }
+ if (!Number.isFinite(forceKillAfterTimeout) || forceKillAfterTimeout < 0) {
+ throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${forceKillAfterTimeout}\` (${typeof forceKillAfterTimeout})`);
+ }
+ return forceKillAfterTimeout;
+}, "getForceKillAfterTimeout");
+var spawnedCancel = /* @__PURE__ */ __name((spawned, context2) => {
+ const killResult = spawned.kill();
+ if (killResult) {
+ context2.isCanceled = true;
+ }
+}, "spawnedCancel");
+var timeoutKill = /* @__PURE__ */ __name((spawned, signal, reject) => {
+ spawned.kill(signal);
+ reject(Object.assign(new Error("Timed out"), { timedOut: true, signal }));
+}, "timeoutKill");
+var setupTimeout = /* @__PURE__ */ __name((spawned, { timeout, killSignal = "SIGTERM" }, spawnedPromise) => {
+ if (timeout === 0 || timeout === void 0) {
+ return spawnedPromise;
+ }
+ let timeoutId;
+ const timeoutPromise = new Promise((resolve18, reject) => {
+ timeoutId = setTimeout(() => {
+ timeoutKill(spawned, killSignal, reject);
+ }, timeout);
+ });
+ const safeSpawnedPromise = spawnedPromise.finally(() => {
+ clearTimeout(timeoutId);
+ });
+ return Promise.race([timeoutPromise, safeSpawnedPromise]);
+}, "setupTimeout");
+var validateTimeout = /* @__PURE__ */ __name(({ timeout }) => {
+ if (timeout !== void 0 && (!Number.isFinite(timeout) || timeout < 0)) {
+ throw new TypeError(`Expected the \`timeout\` option to be a non-negative integer, got \`${timeout}\` (${typeof timeout})`);
+ }
+}, "validateTimeout");
+var setExitHandler = /* @__PURE__ */ __name(async (spawned, { cleanup, detached }, timedPromise) => {
+ if (!cleanup || detached) {
+ return timedPromise;
+ }
+ const removeExitHandler = (0, import_signal_exit.default)(() => {
+ spawned.kill();
+ });
+ return timedPromise.finally(() => {
+ removeExitHandler();
+ });
+}, "setExitHandler");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stream.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/is-stream@3.0.0/node_modules/is-stream/index.js
+init_import_meta_url();
+function isStream(stream2) {
+ return stream2 !== null && typeof stream2 === "object" && typeof stream2.pipe === "function";
+}
+__name(isStream, "isStream");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/stream.js
+var import_get_stream = __toESM(require_get_stream(), 1);
+var import_merge_stream = __toESM(require_merge_stream(), 1);
+var handleInput = /* @__PURE__ */ __name((spawned, input) => {
+ if (input === void 0 || spawned.stdin === void 0) {
+ return;
+ }
+ if (isStream(input)) {
+ input.pipe(spawned.stdin);
+ } else {
+ spawned.stdin.end(input);
+ }
+}, "handleInput");
+var makeAllStream = /* @__PURE__ */ __name((spawned, { all: all2 }) => {
+ if (!all2 || !spawned.stdout && !spawned.stderr) {
+ return;
+ }
+ const mixed = (0, import_merge_stream.default)();
+ if (spawned.stdout) {
+ mixed.add(spawned.stdout);
+ }
+ if (spawned.stderr) {
+ mixed.add(spawned.stderr);
+ }
+ return mixed;
+}, "makeAllStream");
+var getBufferedData = /* @__PURE__ */ __name(async (stream2, streamPromise) => {
+ if (!stream2) {
+ return;
+ }
+ stream2.destroy();
+ try {
+ return await streamPromise;
+ } catch (error) {
+ return error.bufferedData;
+ }
+}, "getBufferedData");
+var getStreamPromise = /* @__PURE__ */ __name((stream2, { encoding, buffer, maxBuffer }) => {
+ if (!stream2 || !buffer) {
+ return;
+ }
+ if (encoding) {
+ return (0, import_get_stream.default)(stream2, { encoding, maxBuffer });
+ }
+ return import_get_stream.default.buffer(stream2, { maxBuffer });
+}, "getStreamPromise");
+var getSpawnedResult = /* @__PURE__ */ __name(async ({ stdout, stderr, all: all2 }, { encoding, buffer, maxBuffer }, processDone) => {
+ const stdoutPromise = getStreamPromise(stdout, { encoding, buffer, maxBuffer });
+ const stderrPromise = getStreamPromise(stderr, { encoding, buffer, maxBuffer });
+ const allPromise = getStreamPromise(all2, { encoding, buffer, maxBuffer: maxBuffer * 2 });
+ try {
+ return await Promise.all([processDone, stdoutPromise, stderrPromise, allPromise]);
+ } catch (error) {
+ return Promise.all([
+ { error, signal: error.signal, timedOut: error.timedOut },
+ getBufferedData(stdout, stdoutPromise),
+ getBufferedData(stderr, stderrPromise),
+ getBufferedData(all2, allPromise)
+ ]);
+ }
+}, "getSpawnedResult");
+var validateInputSync = /* @__PURE__ */ __name(({ input }) => {
+ if (isStream(input)) {
+ throw new TypeError("The `input` option cannot be a stream in sync mode");
+ }
+}, "validateInputSync");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/promise.js
+init_import_meta_url();
+var nativePromisePrototype = (async () => {
+})().constructor.prototype;
+var descriptors = ["then", "catch", "finally"].map((property) => [
+ property,
+ Reflect.getOwnPropertyDescriptor(nativePromisePrototype, property)
+]);
+var mergePromise = /* @__PURE__ */ __name((spawned, promise) => {
+ for (const [property, descriptor2] of descriptors) {
+ const value = typeof promise === "function" ? (...args) => Reflect.apply(descriptor2.value, promise(), args) : descriptor2.value.bind(promise);
+ Reflect.defineProperty(spawned, property, { ...descriptor2, value });
+ }
+ return spawned;
+}, "mergePromise");
+var getSpawnedPromise = /* @__PURE__ */ __name((spawned) => new Promise((resolve18, reject) => {
+ spawned.on("exit", (exitCode, signal) => {
+ resolve18({ exitCode, signal });
+ });
+ spawned.on("error", (error) => {
+ reject(error);
+ });
+ if (spawned.stdin) {
+ spawned.stdin.on("error", (error) => {
+ reject(error);
+ });
+ }
+}), "getSpawnedPromise");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/lib/command.js
+init_import_meta_url();
+var normalizeArgs = /* @__PURE__ */ __name((file, args = []) => {
+ if (!Array.isArray(args)) {
+ return [file];
+ }
+ return [file, ...args];
+}, "normalizeArgs");
+var NO_ESCAPE_REGEXP = /^[\w.-]+$/;
+var DOUBLE_QUOTES_REGEXP = /"/g;
+var escapeArg = /* @__PURE__ */ __name((arg) => {
+ if (typeof arg !== "string" || NO_ESCAPE_REGEXP.test(arg)) {
+ return arg;
+ }
+ return `"${arg.replace(DOUBLE_QUOTES_REGEXP, '\\"')}"`;
+}, "escapeArg");
+var joinCommand = /* @__PURE__ */ __name((file, args) => normalizeArgs(file, args).join(" "), "joinCommand");
+var getEscapedCommand = /* @__PURE__ */ __name((file, args) => normalizeArgs(file, args).map((arg) => escapeArg(arg)).join(" "), "getEscapedCommand");
+var SPACES_REGEXP = / +/g;
+var parseCommand = /* @__PURE__ */ __name((command2) => {
+ const tokens = [];
+ for (const token of command2.trim().split(SPACES_REGEXP)) {
+ const previousToken = tokens[tokens.length - 1];
+ if (previousToken && previousToken.endsWith("\\")) {
+ tokens[tokens.length - 1] = `${previousToken.slice(0, -1)} ${token}`;
+ } else {
+ tokens.push(token);
+ }
+ }
+ return tokens;
+}, "parseCommand");
+
+// ../../node_modules/.pnpm/execa@6.1.0/node_modules/execa/index.js
+var DEFAULT_MAX_BUFFER = 1e3 * 1e3 * 100;
+var getEnv = /* @__PURE__ */ __name(({ env: envOption, extendEnv, preferLocal, localDir, execPath }) => {
+ const env5 = extendEnv ? { ...import_node_process3.default.env, ...envOption } : envOption;
+ if (preferLocal) {
+ return npmRunPathEnv({ env: env5, cwd: localDir, execPath });
+ }
+ return env5;
+}, "getEnv");
+var handleArguments = /* @__PURE__ */ __name((file, args, options14 = {}) => {
+ const parsed = import_cross_spawn.default._parse(file, args, options14);
+ file = parsed.command;
+ args = parsed.args;
+ options14 = parsed.options;
+ options14 = {
+ maxBuffer: DEFAULT_MAX_BUFFER,
+ buffer: true,
+ stripFinalNewline: true,
+ extendEnv: true,
+ preferLocal: false,
+ localDir: options14.cwd || import_node_process3.default.cwd(),
+ execPath: import_node_process3.default.execPath,
+ encoding: "utf8",
+ reject: true,
+ cleanup: true,
+ all: false,
+ windowsHide: true,
+ ...options14
+ };
+ options14.env = getEnv(options14);
+ options14.stdio = normalizeStdio(options14);
+ if (import_node_process3.default.platform === "win32" && import_node_path11.default.basename(file, ".exe") === "cmd") {
+ args.unshift("/q");
+ }
+ return { file, args, options: options14, parsed };
+}, "handleArguments");
+var handleOutput = /* @__PURE__ */ __name((options14, value, error) => {
+ if (typeof value !== "string" && !import_node_buffer.Buffer.isBuffer(value)) {
+ return error === void 0 ? void 0 : "";
+ }
+ if (options14.stripFinalNewline) {
+ return stripFinalNewline(value);
+ }
+ return value;
+}, "handleOutput");
+function execa(file, args, options14) {
+ const parsed = handleArguments(file, args, options14);
+ const command2 = joinCommand(file, args);
+ const escapedCommand = getEscapedCommand(file, args);
+ validateTimeout(parsed.options);
+ let spawned;
+ try {
+ spawned = import_node_child_process.default.spawn(parsed.file, parsed.args, parsed.options);
+ } catch (error) {
+ const dummySpawned = new import_node_child_process.default.ChildProcess();
+ const errorPromise = Promise.reject(makeError({
+ error,
+ stdout: "",
+ stderr: "",
+ all: "",
+ command: command2,
+ escapedCommand,
+ parsed,
+ timedOut: false,
+ isCanceled: false,
+ killed: false
+ }));
+ return mergePromise(dummySpawned, errorPromise);
+ }
+ const spawnedPromise = getSpawnedPromise(spawned);
+ const timedPromise = setupTimeout(spawned, parsed.options, spawnedPromise);
+ const processDone = setExitHandler(spawned, parsed.options, timedPromise);
+ const context2 = { isCanceled: false };
+ spawned.kill = spawnedKill.bind(null, spawned.kill.bind(spawned));
+ spawned.cancel = spawnedCancel.bind(null, spawned, context2);
+ const handlePromise = /* @__PURE__ */ __name(async () => {
+ const [{ error, exitCode, signal, timedOut }, stdoutResult, stderrResult, allResult] = await getSpawnedResult(spawned, parsed.options, processDone);
+ const stdout = handleOutput(parsed.options, stdoutResult);
+ const stderr = handleOutput(parsed.options, stderrResult);
+ const all2 = handleOutput(parsed.options, allResult);
+ if (error || exitCode !== 0 || signal !== null) {
+ const returnedError = makeError({
+ error,
+ exitCode,
+ signal,
+ stdout,
+ stderr,
+ all: all2,
+ command: command2,
+ escapedCommand,
+ parsed,
+ timedOut,
+ isCanceled: context2.isCanceled || (parsed.options.signal ? parsed.options.signal.aborted : false),
+ killed: spawned.killed
+ });
+ if (!parsed.options.reject) {
+ return returnedError;
+ }
+ throw returnedError;
+ }
+ return {
+ command: command2,
+ escapedCommand,
+ exitCode: 0,
+ stdout,
+ stderr,
+ all: all2,
+ failed: false,
+ timedOut: false,
+ isCanceled: false,
+ killed: false
+ };
+ }, "handlePromise");
+ const handlePromiseOnce = onetime_default(handlePromise);
+ handleInput(spawned, parsed.options.input);
+ spawned.all = makeAllStream(spawned, parsed.options);
+ return mergePromise(spawned, handlePromiseOnce);
+}
+__name(execa, "execa");
+function execaSync(file, args, options14) {
+ const parsed = handleArguments(file, args, options14);
+ const command2 = joinCommand(file, args);
+ const escapedCommand = getEscapedCommand(file, args);
+ validateInputSync(parsed.options);
+ let result;
+ try {
+ result = import_node_child_process.default.spawnSync(parsed.file, parsed.args, parsed.options);
+ } catch (error) {
+ throw makeError({
+ error,
+ stdout: "",
+ stderr: "",
+ all: "",
+ command: command2,
+ escapedCommand,
+ parsed,
+ timedOut: false,
+ isCanceled: false,
+ killed: false
+ });
+ }
+ const stdout = handleOutput(parsed.options, result.stdout, result.error);
+ const stderr = handleOutput(parsed.options, result.stderr, result.error);
+ if (result.error || result.status !== 0 || result.signal !== null) {
+ const error = makeError({
+ stdout,
+ stderr,
+ error: result.error,
+ signal: result.signal,
+ exitCode: result.status,
+ command: command2,
+ escapedCommand,
+ parsed,
+ timedOut: result.error && result.error.code === "ETIMEDOUT",
+ isCanceled: false,
+ killed: result.signal !== null
+ });
+ if (!parsed.options.reject) {
+ return error;
+ }
+ throw error;
+ }
+ return {
+ command: command2,
+ escapedCommand,
+ exitCode: 0,
+ stdout,
+ stderr,
+ failed: false,
+ timedOut: false,
+ isCanceled: false,
+ killed: false
+ };
+}
+__name(execaSync, "execaSync");
+function execaCommand(command2, options14) {
+ const [file, ...args] = parseCommand(command2);
+ return execa(file, args, options14);
+}
+__name(execaCommand, "execaCommand");
+function execaCommandSync(command2, options14) {
+ const [file, ...args] = parseCommand(command2);
+ return execaSync(file, args, options14);
+}
+__name(execaCommandSync, "execaCommandSync");
+
+// src/deployment-bundle/run-custom-build.ts
+async function runCustomBuild(expectedEntryAbsolute, expectedEntryRelative, build5) {
+ if (build5.command) {
+ logger.log("Running custom build:", build5.command);
+ await execaCommand(build5.command, {
+ shell: true,
+ // we keep these two as "inherit" so that
+ // logs are still visible.
+ stdout: "inherit",
+ stderr: "inherit",
+ ...build5.cwd && { cwd: build5.cwd }
+ });
+ assertEntryPointExists(
+ expectedEntryAbsolute,
+ expectedEntryRelative,
+ `The expected output file at "${expectedEntryRelative}" was not found after running custom build: ${build5.command}.
+The \`main\` property in wrangler.toml should point to the file generated by the custom build.`
+ );
+ } else {
+ assertEntryPointExists(
+ expectedEntryAbsolute,
+ expectedEntryRelative,
+ `The entry-point file at "${expectedEntryRelative}" was not found.`
+ );
+ }
+}
+__name(runCustomBuild, "runCustomBuild");
+function assertEntryPointExists(expectedEntryAbsolute, expectedEntryRelative, errorMessage) {
+ if (!fileExists(expectedEntryAbsolute)) {
+ throw new Error(
+ getMissingEntryPointMessage(
+ errorMessage,
+ expectedEntryAbsolute,
+ expectedEntryRelative
+ )
+ );
+ }
+}
+__name(assertEntryPointExists, "assertEntryPointExists");
+function getMissingEntryPointMessage(message, absoluteEntryPointPath, relativeEntryPointPath) {
+ if ((0, import_node_fs5.existsSync)(absoluteEntryPointPath) && (0, import_node_fs5.statSync)(absoluteEntryPointPath).isDirectory()) {
+ message += `
+The provided entry-point path, "${relativeEntryPointPath}", points to a directory, rather than a file.
+`;
+ const possiblePaths = [];
+ for (const basenamePath of [
+ "worker",
+ "dist/worker",
+ "index",
+ "dist/index"
+ ]) {
+ for (const extension of [".ts", ".tsx", ".js", ".jsx"]) {
+ const filePath = basenamePath + extension;
+ if (fileExists(import_node_path12.default.resolve(absoluteEntryPointPath, filePath))) {
+ possiblePaths.push(import_node_path12.default.join(relativeEntryPointPath, filePath));
+ }
+ }
+ }
+ if (possiblePaths.length > 0) {
+ message += `
+Did you mean to set the main field to${possiblePaths.length > 1 ? " one of" : ""}:
+\`\`\`
+` + possiblePaths.map((filePath) => `main = "./${filePath}"
+`).join("") + "```";
+ }
+ }
+ return message;
+}
+__name(getMissingEntryPointMessage, "getMissingEntryPointMessage");
+function fileExists(filePath) {
+ const SOURCE_FILE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
+ if (import_node_path12.default.extname(filePath) !== "") {
+ return (0, import_node_fs5.existsSync)(filePath);
+ }
+ const base = import_node_path12.default.join(import_node_path12.default.dirname(filePath), import_node_path12.default.basename(filePath));
+ for (const ext of SOURCE_FILE_EXTENSIONS) {
+ if ((0, import_node_fs5.existsSync)(base + ext)) {
+ return true;
+ }
+ }
+ return false;
+}
+__name(fileExists, "fileExists");
+
+// src/deployment-bundle/entry.ts
+async function getEntry(args, config, command2) {
+ let file;
+ let directory = process.cwd();
+ if (args.script) {
+ file = import_node_path13.default.resolve(args.script);
+ } else if (config.main === void 0) {
+ if (config.site?.["entry-point"]) {
+ directory = import_node_path13.default.resolve(import_node_path13.default.dirname(config.configPath ?? "."));
+ file = import_node_path13.default.extname(config.site?.["entry-point"]) ? import_node_path13.default.resolve(config.site?.["entry-point"]) : (
+ // site.entry-point could be a directory
+ import_node_path13.default.resolve(config.site?.["entry-point"], "index.js")
+ );
+ } else if (args.assets || config.assets) {
+ file = import_node_path13.default.resolve(getBasePath(), "templates/no-op-worker.js");
+ } else {
+ throw new Error(
+ `Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler ${command2} path/to/script\`) or the \`main\` config field.`
+ );
+ }
+ } else {
+ directory = import_node_path13.default.resolve(import_node_path13.default.dirname(config.configPath ?? "."));
+ file = import_node_path13.default.resolve(directory, config.main);
+ }
+ const relativeFile = import_node_path13.default.relative(directory, file) || ".";
+ await runCustomBuild(file, relativeFile, config.build);
+ const format8 = await guessWorkerFormat(
+ file,
+ directory,
+ args.format ?? config.build?.upload?.format,
+ config.tsconfig
+ );
+ const { localBindings, remoteBindings } = partitionDurableObjectBindings(config);
+ if (command2 === "dev" && remoteBindings.length > 0) {
+ logger.warn(
+ "WARNING: You have Durable Object bindings that are not defined locally in the worker being developed.\nBe aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances.\nRemote Durable Objects that are affected:\n" + remoteBindings.map((b) => `- ${JSON.stringify(b)}`).join("\n")
+ );
+ }
+ if (format8 === "service-worker" && localBindings.length > 0) {
+ const errorMessage = "You seem to be trying to use Durable Objects in a Worker written as a service-worker.";
+ const addScriptName = "You can use Durable Objects defined in other Workers by specifying a `script_name` in your wrangler.toml, where `script_name` is the name of the Worker that implements that Durable Object. For example:";
+ const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
+ const migrateText = "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
+ const migrateUrl = "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
+ throw new Error(
+ `${errorMessage}
+${addScriptName}
+${addScriptNameExamples}
+${migrateText}
+${migrateUrl}`
+ );
+ }
+ return {
+ file,
+ directory,
+ format: format8,
+ moduleRoot: args.moduleRoot ?? config.base_dir ?? import_node_path13.default.dirname(file),
+ name: config.name ?? "worker"
+ };
+}
+__name(getEntry, "getEntry");
+function partitionDurableObjectBindings(config) {
+ const localBindings = [];
+ const remoteBindings = [];
+ for (const binding of config.durable_objects.bindings) {
+ if (binding.script_name === void 0) {
+ localBindings.push(binding);
+ } else {
+ remoteBindings.push(binding);
+ }
+ }
+ return { localBindings, remoteBindings };
+}
+__name(partitionDurableObjectBindings, "partitionDurableObjectBindings");
+function generateAddScriptNameExamples(localBindings) {
+ function exampleScriptName(binding_name) {
+ return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
+ }
+ __name(exampleScriptName, "exampleScriptName");
+ return localBindings.map(({ name, class_name }) => {
+ const script_name = exampleScriptName(name);
+ const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
+ const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
+ return `${currentBinding} ==> ${fixedBinding}`;
+ }).join("\n");
+}
+__name(generateAddScriptNameExamples, "generateAddScriptNameExamples");
+
+// src/dev/dev.tsx
+init_import_meta_url();
+var import_node_child_process6 = require("node:child_process");
+var import_node_fs26 = __toESM(require("node:fs"));
+var path41 = __toESM(require("node:path"));
+var util = __toESM(require("node:util"));
+var import_chokidar4 = require("chokidar");
+
+// ../../node_modules/.pnpm/clipboardy@3.0.0/node_modules/clipboardy/index.js
+init_import_meta_url();
+var import_node_process4 = __toESM(require("node:process"), 1);
+var import_is_wsl = __toESM(require_is_wsl(), 1);
+
+// ../../node_modules/.pnpm/clipboardy@3.0.0/node_modules/clipboardy/lib/termux.js
+init_import_meta_url();
+var import_execa2 = __toESM(require_execa(), 1);
+var handler = /* @__PURE__ */ __name((error) => {
+ if (error.code === "ENOENT") {
+ throw new Error("Couldn't find the termux-api scripts. You can install them with: apt install termux-api");
+ }
+ throw error;
+}, "handler");
+var clipboard = {
+ copy: async (options14) => {
+ try {
+ await (0, import_execa2.default)("termux-clipboard-set", options14);
+ } catch (error) {
+ handler(error);
+ }
+ },
+ paste: async (options14) => {
+ try {
+ const { stdout } = await (0, import_execa2.default)("termux-clipboard-get", options14);
+ return stdout;
+ } catch (error) {
+ handler(error);
+ }
+ },
+ copySync: (options14) => {
+ try {
+ import_execa2.default.sync("termux-clipboard-set", options14);
+ } catch (error) {
+ handler(error);
+ }
+ },
+ pasteSync: (options14) => {
+ try {
+ return import_execa2.default.sync("termux-clipboard-get", options14).stdout;
+ } catch (error) {
+ handler(error);
+ }
+ }
+};
+var termux_default = clipboard;
+
+// ../../node_modules/.pnpm/clipboardy@3.0.0/node_modules/clipboardy/lib/linux.js
+init_import_meta_url();
+var import_node_path14 = __toESM(require("node:path"), 1);
+var import_node_url6 = require("node:url");
+var import_execa3 = __toESM(require_execa(), 1);
+var __dirname3 = import_node_path14.default.dirname((0, import_node_url6.fileURLToPath)(import_meta_url));
+var xsel = "xsel";
+var xselFallback = import_node_path14.default.join(__dirname3, "../fallbacks/linux/xsel");
+var copyArguments = ["--clipboard", "--input"];
+var pasteArguments = ["--clipboard", "--output"];
+var makeError2 = /* @__PURE__ */ __name((xselError, fallbackError) => {
+ let error;
+ if (xselError.code === "ENOENT") {
+ error = new Error("Couldn't find the `xsel` binary and fallback didn't work. On Debian/Ubuntu you can install xsel with: sudo apt install xsel");
+ } else {
+ error = new Error("Both xsel and fallback failed");
+ error.xselError = xselError;
+ }
+ error.fallbackError = fallbackError;
+ return error;
+}, "makeError");
+var xselWithFallback = /* @__PURE__ */ __name(async (argumentList, options14) => {
+ try {
+ const { stdout } = await (0, import_execa3.default)(xsel, argumentList, options14);
+ return stdout;
+ } catch (xselError) {
+ try {
+ const { stdout } = await (0, import_execa3.default)(xselFallback, argumentList, options14);
+ return stdout;
+ } catch (fallbackError) {
+ throw makeError2(xselError, fallbackError);
+ }
+ }
+}, "xselWithFallback");
+var xselWithFallbackSync = /* @__PURE__ */ __name((argumentList, options14) => {
+ try {
+ return import_execa3.default.sync(xsel, argumentList, options14).stdout;
+ } catch (xselError) {
+ try {
+ return import_execa3.default.sync(xselFallback, argumentList, options14).stdout;
+ } catch (fallbackError) {
+ throw makeError2(xselError, fallbackError);
+ }
+ }
+}, "xselWithFallbackSync");
+var clipboard2 = {
+ copy: async (options14) => {
+ await xselWithFallback(copyArguments, options14);
+ },
+ copySync: (options14) => {
+ xselWithFallbackSync(copyArguments, options14);
+ },
+ paste: (options14) => xselWithFallback(pasteArguments, options14),
+ pasteSync: (options14) => xselWithFallbackSync(pasteArguments, options14)
+};
+var linux_default = clipboard2;
+
+// ../../node_modules/.pnpm/clipboardy@3.0.0/node_modules/clipboardy/lib/macos.js
+init_import_meta_url();
+var import_execa4 = __toESM(require_execa(), 1);
+var env2 = {
+ LC_CTYPE: "UTF-8"
+};
+var clipboard3 = {
+ copy: async (options14) => (0, import_execa4.default)("pbcopy", { ...options14, env: env2 }),
+ paste: async (options14) => {
+ const { stdout } = await (0, import_execa4.default)("pbpaste", { ...options14, env: env2 });
+ return stdout;
+ },
+ copySync: (options14) => import_execa4.default.sync("pbcopy", { ...options14, env: env2 }),
+ pasteSync: (options14) => import_execa4.default.sync("pbpaste", { ...options14, env: env2 }).stdout
+};
+var macos_default = clipboard3;
+
+// ../../node_modules/.pnpm/clipboardy@3.0.0/node_modules/clipboardy/lib/windows.js
+init_import_meta_url();
+var import_node_path15 = __toESM(require("node:path"), 1);
+var import_node_url7 = require("node:url");
+var import_execa5 = __toESM(require_execa(), 1);
+var import_arch = __toESM(require_arch(), 1);
+var __dirname4 = import_node_path15.default.dirname((0, import_node_url7.fileURLToPath)(import_meta_url));
+var binarySuffix = (0, import_arch.default)() === "x64" ? "x86_64" : "i686";
+var windowBinaryPath = import_node_path15.default.join(__dirname4, `../fallbacks/windows/clipboard_${binarySuffix}.exe`);
+var clipboard4 = {
+ copy: async (options14) => (0, import_execa5.default)(windowBinaryPath, ["--copy"], options14),
+ paste: async (options14) => {
+ const { stdout } = await (0, import_execa5.default)(windowBinaryPath, ["--paste"], options14);
+ return stdout;
+ },
+ copySync: (options14) => import_execa5.default.sync(windowBinaryPath, ["--copy"], options14),
+ pasteSync: (options14) => import_execa5.default.sync(windowBinaryPath, ["--paste"], options14).stdout
+};
+var windows_default = clipboard4;
+
+// ../../node_modules/.pnpm/clipboardy@3.0.0/node_modules/clipboardy/index.js
+var platformLib = (() => {
+ switch (import_node_process4.default.platform) {
+ case "darwin":
+ return macos_default;
+ case "win32":
+ return windows_default;
+ case "android":
+ if (import_node_process4.default.env.PREFIX !== "/data/data/com.termux/files/usr") {
+ throw new Error("You need to install Termux for this module to work on Android: https://termux.com");
+ }
+ return termux_default;
+ default:
+ if (import_is_wsl.default) {
+ return windows_default;
+ }
+ return linux_default;
+ }
+})();
+var clipboard5 = {};
+clipboard5.write = async (text) => {
+ if (typeof text !== "string") {
+ throw new TypeError(`Expected a string, got ${typeof text}`);
+ }
+ await platformLib.copy({ input: text });
+};
+clipboard5.read = async () => platformLib.paste({ stripFinalNewline: false });
+clipboard5.writeSync = (text) => {
+ if (typeof text !== "string") {
+ throw new TypeError(`Expected a string, got ${typeof text}`);
+ }
+ platformLib.copySync({ input: text });
+};
+clipboard5.readSync = () => platformLib.pasteSync({ stripFinalNewline: false });
+var clipboardy_default = clipboard5;
+
+// src/dev/dev.tsx
+var import_command_exists2 = __toESM(require_command_exists2());
+var import_ink12 = __toESM(require_build2());
+var import_react19 = __toESM(require_react());
+
+// ../../node_modules/.pnpm/react-error-boundary@3.1.4_react@17.0.2/node_modules/react-error-boundary/dist/react-error-boundary.esm.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/@babel+runtime@7.22.5/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/@babel+runtime@7.22.5/node_modules/@babel/runtime/helpers/esm/setPrototypeOf.js
+init_import_meta_url();
+function _setPrototypeOf(o, p) {
+ _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : /* @__PURE__ */ __name(function _setPrototypeOf2(o2, p2) {
+ o2.__proto__ = p2;
+ return o2;
+ }, "_setPrototypeOf");
+ return _setPrototypeOf(o, p);
+}
+__name(_setPrototypeOf, "_setPrototypeOf");
+
+// ../../node_modules/.pnpm/@babel+runtime@7.22.5/node_modules/@babel/runtime/helpers/esm/inheritsLoose.js
+function _inheritsLoose(subClass, superClass) {
+ subClass.prototype = Object.create(superClass.prototype);
+ subClass.prototype.constructor = subClass;
+ _setPrototypeOf(subClass, superClass);
+}
+__name(_inheritsLoose, "_inheritsLoose");
+
+// ../../node_modules/.pnpm/react-error-boundary@3.1.4_react@17.0.2/node_modules/react-error-boundary/dist/react-error-boundary.esm.js
+var React = __toESM(require_react());
+var changedArray = /* @__PURE__ */ __name(function changedArray2(a, b) {
+ if (a === void 0) {
+ a = [];
+ }
+ if (b === void 0) {
+ b = [];
+ }
+ return a.length !== b.length || a.some(function(item, index) {
+ return !Object.is(item, b[index]);
+ });
+}, "changedArray");
+var initialState = {
+ error: null
+};
+var ErrorBoundary = /* @__PURE__ */ function(_React$Component) {
+ _inheritsLoose(ErrorBoundary2, _React$Component);
+ function ErrorBoundary2() {
+ var _this;
+ for (var _len = arguments.length, _args = new Array(_len), _key = 0; _key < _len; _key++) {
+ _args[_key] = arguments[_key];
+ }
+ _this = _React$Component.call.apply(_React$Component, [this].concat(_args)) || this;
+ _this.state = initialState;
+ _this.resetErrorBoundary = function() {
+ var _this$props;
+ for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
+ args[_key2] = arguments[_key2];
+ }
+ _this.props.onReset == null ? void 0 : (_this$props = _this.props).onReset.apply(_this$props, args);
+ _this.reset();
+ };
+ return _this;
+ }
+ __name(ErrorBoundary2, "ErrorBoundary");
+ ErrorBoundary2.getDerivedStateFromError = /* @__PURE__ */ __name(function getDerivedStateFromError(error) {
+ return {
+ error
+ };
+ }, "getDerivedStateFromError");
+ var _proto = ErrorBoundary2.prototype;
+ _proto.reset = /* @__PURE__ */ __name(function reset() {
+ this.setState(initialState);
+ }, "reset");
+ _proto.componentDidCatch = /* @__PURE__ */ __name(function componentDidCatch(error, info) {
+ var _this$props$onError, _this$props2;
+ (_this$props$onError = (_this$props2 = this.props).onError) == null ? void 0 : _this$props$onError.call(_this$props2, error, info);
+ }, "componentDidCatch");
+ _proto.componentDidUpdate = /* @__PURE__ */ __name(function componentDidUpdate(prevProps, prevState) {
+ var error = this.state.error;
+ var resetKeys = this.props.resetKeys;
+ if (error !== null && prevState.error !== null && changedArray(prevProps.resetKeys, resetKeys)) {
+ var _this$props$onResetKe, _this$props3;
+ (_this$props$onResetKe = (_this$props3 = this.props).onResetKeysChange) == null ? void 0 : _this$props$onResetKe.call(_this$props3, prevProps.resetKeys, resetKeys);
+ this.reset();
+ }
+ }, "componentDidUpdate");
+ _proto.render = /* @__PURE__ */ __name(function render7() {
+ var error = this.state.error;
+ var _this$props4 = this.props, fallbackRender = _this$props4.fallbackRender, FallbackComponent = _this$props4.FallbackComponent, fallback = _this$props4.fallback;
+ if (error !== null) {
+ var _props = {
+ error,
+ resetErrorBoundary: this.resetErrorBoundary
+ };
+ if (/* @__PURE__ */ React.isValidElement(fallback)) {
+ return fallback;
+ } else if (typeof fallbackRender === "function") {
+ return fallbackRender(_props);
+ } else if (FallbackComponent) {
+ return /* @__PURE__ */ React.createElement(FallbackComponent, _props);
+ } else {
+ throw new Error("react-error-boundary requires either a fallback, fallbackRender, or FallbackComponent prop");
+ }
+ }
+ return this.props.children;
+ }, "render");
+ return ErrorBoundary2;
+}(React.Component);
+function withErrorBoundary(Component2, errorBoundaryProps) {
+ var Wrapped = /* @__PURE__ */ __name(function Wrapped2(props) {
+ return /* @__PURE__ */ React.createElement(ErrorBoundary, errorBoundaryProps, /* @__PURE__ */ React.createElement(Component2, props));
+ }, "Wrapped");
+ var name = Component2.displayName || Component2.name || "Unknown";
+ Wrapped.displayName = "withErrorBoundary(" + name + ")";
+ return Wrapped;
+}
+__name(withErrorBoundary, "withErrorBoundary");
+function useErrorHandler(givenError) {
+ var _React$useState = React.useState(null), error = _React$useState[0], setError = _React$useState[1];
+ if (givenError != null)
+ throw givenError;
+ if (error != null)
+ throw error;
+ return setError;
+}
+__name(useErrorHandler, "useErrorHandler");
+
+// src/dev/dev.tsx
+var import_signal_exit5 = __toESM(require_signal_exit());
+var import_tmp_promise3 = __toESM(require_tmp_promise());
+var import_undici17 = __toESM(require_undici());
+
+// src/dev-registry.ts
+init_import_meta_url();
+var import_http = __toESM(require("http"));
+var import_net = __toESM(require("net"));
+var import_body_parser = __toESM(require_body_parser());
+var import_express = __toESM(require_express2());
+var import_http_terminator = __toESM(require_src5());
+var import_undici5 = __toESM(require_undici());
+var DEV_REGISTRY_PORT = "6284";
+var DEV_REGISTRY_HOST = `http://localhost:${DEV_REGISTRY_PORT}`;
+var server;
+var terminator;
+async function isPortAvailable() {
+ return new Promise((resolve18, reject) => {
+ const netServer = import_net.default.createServer().once("error", (err) => {
+ netServer.close();
+ if (err.code === "EADDRINUSE") {
+ resolve18(false);
+ } else {
+ reject(err);
+ }
+ }).once("listening", () => {
+ netServer.close();
+ resolve18(true);
+ });
+ netServer.listen(DEV_REGISTRY_PORT);
+ });
+}
+__name(isPortAvailable, "isPortAvailable");
+var jsonBodyParser = import_body_parser.default.json();
+async function startWorkerRegistry() {
+ if (await isPortAvailable() && !server) {
+ const app = (0, import_express.default)();
+ let workers = {};
+ app.get("/workers", async (req, res) => {
+ res.json(workers);
+ }).post("/workers/:workerId", jsonBodyParser, async (req, res) => {
+ workers[req.params.workerId] = req.body;
+ res.json(null);
+ }).delete(`/workers/:workerId`, async (req, res) => {
+ delete workers[req.params.workerId];
+ res.json(null);
+ }).delete("/workers", async (req, res) => {
+ workers = {};
+ res.json(null);
+ });
+ server = import_http.default.createServer(app);
+ terminator = (0, import_http_terminator.createHttpTerminator)({ server });
+ server.listen(DEV_REGISTRY_PORT);
+ server.once("error", (err) => {
+ if (err.code !== "EADDRINUSE") {
+ throw err;
+ }
+ });
+ server.on("close", () => {
+ server = null;
+ });
+ }
+}
+__name(startWorkerRegistry, "startWorkerRegistry");
+async function stopWorkerRegistry() {
+ await terminator?.terminate();
+ server = null;
+}
+__name(stopWorkerRegistry, "stopWorkerRegistry");
+async function registerWorker(name, definition) {
+ await startWorkerRegistry();
+ try {
+ return await (0, import_undici5.fetch)(`${DEV_REGISTRY_HOST}/workers/${name}`, {
+ method: "POST",
+ headers: {
+ "Content-Type": "application/json"
+ },
+ body: JSON.stringify(definition)
+ });
+ } catch (e2) {
+ if (!["ECONNRESET", "ECONNREFUSED"].includes(
+ e2.cause?.code || "___"
+ )) {
+ logger.error("Failed to register worker in local service registry", e2);
+ } else {
+ logger.debug("Failed to register worker in local service registry", e2);
+ }
+ }
+}
+__name(registerWorker, "registerWorker");
+async function unregisterWorker(name) {
+ try {
+ await (0, import_undici5.fetch)(`${DEV_REGISTRY_HOST}/workers/${name}`, {
+ method: "DELETE"
+ });
+ } catch (e2) {
+ if (!["ECONNRESET", "ECONNREFUSED"].includes(
+ e2.cause?.code || "___"
+ )) {
+ throw e2;
+ }
+ }
+}
+__name(unregisterWorker, "unregisterWorker");
+async function getRegisteredWorkers() {
+ try {
+ const response = await (0, import_undici5.fetch)(`${DEV_REGISTRY_HOST}/workers`);
+ return await response.json();
+ } catch (e2) {
+ if (!["ECONNRESET", "ECONNREFUSED"].includes(
+ e2.cause?.code || "___"
+ )) {
+ throw e2;
+ }
+ }
+}
+__name(getRegisteredWorkers, "getRegisteredWorkers");
+async function getBoundRegisteredWorkers({
+ services,
+ durableObjects
+}) {
+ const serviceNames = (services || []).map(
+ (serviceBinding) => serviceBinding.service
+ );
+ const durableObjectServices = (durableObjects || { bindings: [] }).bindings.map((durableObjectBinding) => durableObjectBinding.script_name);
+ const workerDefinitions = await getRegisteredWorkers();
+ const filteredWorkers = Object.fromEntries(
+ Object.entries(workerDefinitions || {}).filter(
+ ([key, _value]) => serviceNames.includes(key) || durableObjectServices.includes(key)
+ )
+ );
+ return filteredWorkers;
+}
+__name(getBoundRegisteredWorkers, "getBoundRegisteredWorkers");
+
+// src/inspect.ts
+init_import_meta_url();
+var import_fs6 = require("fs");
+var import_node_assert6 = __toESM(require("node:assert"));
+var import_node_crypto4 = __toESM(require("node:crypto"));
+var import_node_http3 = require("node:http");
+var import_node_os6 = __toESM(require("node:os"));
+var import_node_path16 = __toESM(require("node:path"));
+var import_node_url8 = require("node:url");
+var import_open2 = __toESM(require_open());
+var import_react2 = __toESM(require_react());
+
+// ../../node_modules/.pnpm/ws@8.11.0/node_modules/ws/wrapper.mjs
+init_import_meta_url();
+var import_stream2 = __toESM(require_stream3(), 1);
+var import_receiver = __toESM(require_receiver3(), 1);
+var import_sender = __toESM(require_sender2(), 1);
+var import_websocket = __toESM(require_websocket3(), 1);
+var import_websocket_server = __toESM(require_websocket_server2(), 1);
+var wrapper_default = import_websocket.default;
+
+// src/proxy.ts
+init_import_meta_url();
+var import_node_http2 = require("node:http");
+var import_node_http22 = require("node:http2");
+var import_node_https = require("node:https");
+var import_node_https2 = __toESM(require("node:https"));
+var import_node_os5 = require("node:os");
+var import_http_terminator2 = __toESM(require_src5());
+var import_react = __toESM(require_react());
+var import_serve_static = __toESM(require_serve_static());
+
+// src/https-options.ts
+init_import_meta_url();
+var fs6 = __toESM(require("node:fs"));
+var import_node_os4 = __toESM(require("node:os"));
+var path16 = __toESM(require("node:path"));
+var import_node_util3 = require("node:util");
+var CERT_EXPIRY_DAYS = 30;
+var ONE_DAY_IN_MS = 864e5;
+async function getHttpsOptions() {
+ const certDirectory = path16.join(getGlobalWranglerConfigPath(), "local-cert");
+ const keyPath = path16.join(certDirectory, "key.pem");
+ const certPath = path16.join(certDirectory, "cert.pem");
+ const regenerate = !fs6.existsSync(keyPath) || !fs6.existsSync(certPath) || hasCertificateExpired(keyPath, certPath);
+ if (regenerate) {
+ logger.log("Generating new self-signed certificate...");
+ const { key, cert } = await generateCertificate();
+ try {
+ fs6.mkdirSync(certDirectory, { recursive: true });
+ fs6.writeFileSync(keyPath, key, "utf8");
+ fs6.writeFileSync(certPath, cert, "utf8");
+ } catch (e2) {
+ const message = e2 instanceof Error ? e2.message : `${e2}`;
+ logger.warn(
+ `Unable to cache generated self-signed certificate in ${path16.relative(
+ process.cwd(),
+ certDirectory
+ )}.
+${message}`
+ );
+ }
+ return { key, cert };
+ } else {
+ return {
+ key: fs6.readFileSync(keyPath, "utf8"),
+ cert: fs6.readFileSync(certPath, "utf8")
+ };
+ }
+}
+__name(getHttpsOptions, "getHttpsOptions");
+function hasCertificateExpired(keyPath, certPath) {
+ const keyStat = fs6.statSync(keyPath);
+ const certStat = fs6.statSync(certPath);
+ const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
+ return Date.now() - created > (CERT_EXPIRY_DAYS - 2) * ONE_DAY_IN_MS;
+}
+__name(hasCertificateExpired, "hasCertificateExpired");
+async function generateCertificate() {
+ const generate = (0, import_node_util3.promisify)(
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
+ require("selfsigned").generate
+ );
+ const certAttrs = [{ name: "commonName", value: "localhost" }];
+ const certOptions = {
+ algorithm: "sha256",
+ days: CERT_EXPIRY_DAYS,
+ keySize: 2048,
+ extensions: [
+ { name: "basicConstraints", cA: true },
+ {
+ name: "keyUsage",
+ keyCertSign: true,
+ digitalSignature: true,
+ nonRepudiation: true,
+ keyEncipherment: true,
+ dataEncipherment: true
+ },
+ {
+ name: "extKeyUsage",
+ serverAuth: true,
+ clientAuth: true,
+ codeSigning: true,
+ timeStamping: true
+ },
+ {
+ name: "subjectAltName",
+ altNames: [
+ { type: 2, value: "localhost" },
+ ...getAccessibleHosts().map((ip2) => ({ type: 7, ip: ip2 }))
+ ]
+ }
+ ]
+ };
+ const { private: key, cert } = await generate(certAttrs, certOptions);
+ return { key, cert };
+}
+__name(generateCertificate, "generateCertificate");
+function getAccessibleHosts(ipv4 = false) {
+ const hosts = [];
+ Object.values(import_node_os4.default.networkInterfaces()).forEach(
+ (net3) => net3?.forEach(({ family, address }) => {
+ if (!ipv4 || family === "IPv4")
+ hosts.push(address);
+ })
+ );
+ return hosts;
+}
+__name(getAccessibleHosts, "getAccessibleHosts");
+
+// src/proxy.ts
+function addCfPreviewTokenHeader(headers, previewTokenValue) {
+ headers["cf-workers-preview-token"] = previewTokenValue;
+}
+__name(addCfPreviewTokenHeader, "addCfPreviewTokenHeader");
+async function addCfAccessToken(headers, domain, accessTokenRef) {
+ if (accessTokenRef.current === null) {
+ return;
+ }
+ if (typeof accessTokenRef.current === "string") {
+ headers["cookie"] = `${headers["cookie"]};CF_Authorization=${accessTokenRef.current}`;
+ return;
+ }
+ const token = await getAccessToken(domain);
+ accessTokenRef.current = token;
+ if (token)
+ headers["cookie"] = `${headers["cookie"]};CF_Authorization=${accessTokenRef.current}`;
+}
+__name(addCfAccessToken, "addCfAccessToken");
+function rewriteRemoteHostToLocalHostInHeaders(headers, remoteHost, localPort, localProtocol) {
+ for (const [name, value] of Object.entries(headers)) {
+ if (typeof value === "string" && value.includes(remoteHost)) {
+ headers[name] = value.replaceAll(
+ `https://${remoteHost}`,
+ `${localProtocol}://localhost:${localPort}`
+ ).replaceAll(remoteHost, `localhost:${localPort}`);
+ }
+ }
+}
+__name(rewriteRemoteHostToLocalHostInHeaders, "rewriteRemoteHostToLocalHostInHeaders");
+function writeHead(socket, res) {
+ socket.write(
+ `HTTP/${res.httpVersion} ${res.statusCode} ${res.statusMessage}\r
+`
+ );
+ for (const [key, values] of Object.entries(res.headers)) {
+ if (Array.isArray(values)) {
+ for (const value of values)
+ socket.write(`${key}: ${value}\r
+`);
+ } else {
+ socket.write(`${key}: ${values}\r
+`);
+ }
+ }
+ socket.write("\r\n");
+}
+__name(writeHead, "writeHead");
+async function startPreviewServer({
+ previewToken,
+ assetDirectory,
+ localProtocol,
+ localPort: port2,
+ ip: ip2,
+ onReady
+}) {
+ try {
+ const abortController = new AbortController();
+ const server2 = await createProxyServer(localProtocol);
+ const proxy2 = {
+ server: server2,
+ terminator: (0, import_http_terminator2.createHttpTerminator)({
+ server: server2,
+ gracefulTerminationTimeout: 0
+ })
+ };
+ const streamBufferRef = { current: [] };
+ const requestResponseBufferRef = { current: [] };
+ const accessTokenRef = { current: void 0 };
+ const cleanupListeners = configureProxyServer({
+ proxy: proxy2,
+ previewToken,
+ streamBufferRef,
+ requestResponseBufferRef,
+ retryServerSetup: () => {
+ },
+ // no-op outside of React
+ assetDirectory,
+ localProtocol,
+ port: port2,
+ accessTokenRef
+ });
+ await waitForPortToBeAvailable(port2, {
+ retryPeriod: 200,
+ timeout: 2e3,
+ abortSignal: abortController.signal
+ });
+ proxy2.server.on("listening", () => {
+ const address = proxy2.server.address();
+ const usedPort = address && typeof address === "object" ? address.port : port2;
+ logger.log(`\u2B23 Listening at ${localProtocol}://${ip2}:${usedPort}`);
+ const accessibleHosts = ip2 !== "0.0.0.0" ? [ip2] : getAccessibleHosts2();
+ for (const accessibleHost of accessibleHosts) {
+ logger.log(`- ${localProtocol}://${accessibleHost}:${usedPort}`);
+ }
+ onReady?.(ip2, usedPort);
+ });
+ proxy2.server.listen(port2, ip2);
+ return {
+ stop: () => {
+ abortController.abort();
+ cleanupListeners?.forEach((cleanup) => cleanup());
+ }
+ };
+ } catch (err) {
+ if (err.code !== "ABORT_ERR") {
+ logger.error(`Failed to start server: ${err}`);
+ }
+ logger.error("Failed to create proxy server:", err);
+ }
+}
+__name(startPreviewServer, "startPreviewServer");
+function usePreviewServer({
+ previewToken,
+ assetDirectory,
+ localProtocol,
+ localPort: port2,
+ ip: ip2
+}) {
+ const [proxy2, setProxy] = (0, import_react.useState)();
+ (0, import_react.useEffect)(() => {
+ if (proxy2 === void 0) {
+ createProxyServer(localProtocol).then((server2) => {
+ setProxy({
+ server: server2,
+ terminator: (0, import_http_terminator2.createHttpTerminator)({
+ server: server2,
+ gracefulTerminationTimeout: 0
+ })
+ });
+ }).catch(async (err) => {
+ logger.error("Failed to create proxy server:", err);
+ });
+ }
+ }, [proxy2, localProtocol]);
+ const streamBufferRef = (0, import_react.useRef)([]);
+ const requestResponseBufferRef = (0, import_react.useRef)([]);
+ const accessTokenRef = (0, import_react.useRef)(void 0);
+ const [retryServerSetupSigil, setRetryServerSetupSigil] = (0, import_react.useState)(0);
+ function retryServerSetup() {
+ setRetryServerSetupSigil((x) => x + 1);
+ }
+ __name(retryServerSetup, "retryServerSetup");
+ (0, import_react.useEffect)(() => {
+ const cleanupListeners = configureProxyServer({
+ proxy: proxy2,
+ previewToken,
+ streamBufferRef,
+ requestResponseBufferRef,
+ retryServerSetup,
+ assetDirectory,
+ localProtocol,
+ port: port2,
+ accessTokenRef
+ });
+ return () => {
+ cleanupListeners?.forEach((cleanup) => cleanup());
+ };
+ }, [
+ previewToken,
+ assetDirectory,
+ port2,
+ localProtocol,
+ proxy2,
+ // We use a state value as a sigil to trigger reconnecting the server.
+ // It's not used inside the effect, so react-hooks/exhaustive-deps
+ // doesn't complain if it's not included in the dependency array.
+ // But its presence is critical, so Do NOT remove it from the dependency list.
+ retryServerSetupSigil
+ ]);
+ (0, import_react.useEffect)(() => {
+ const abortController = new AbortController();
+ if (proxy2 === void 0) {
+ return;
+ }
+ waitForPortToBeAvailable(port2, {
+ retryPeriod: 200,
+ timeout: 2e3,
+ abortSignal: abortController.signal
+ }).then(() => {
+ proxy2.server.on("listening", () => {
+ const address = proxy2.server.address();
+ const usedPort = address && typeof address === "object" ? address.port : port2;
+ logger.log(`\u2B23 Listening at ${localProtocol}://${ip2}:${usedPort}`);
+ const accessibleHosts = ip2 !== "0.0.0.0" ? [ip2] : getAccessibleHosts2();
+ for (const accessibleHost of accessibleHosts) {
+ logger.log(`- ${localProtocol}://${accessibleHost}:${usedPort}`);
+ }
+ });
+ proxy2.server.listen(port2, ip2);
+ }).catch((err) => {
+ if (err.code !== "ABORT_ERR") {
+ logger.error(`Failed to start server: ${err}`);
+ }
+ });
+ return () => {
+ abortController.abort();
+ proxy2.terminator.terminate().catch(() => logger.error("Failed to terminate the proxy server."));
+ };
+ }, [port2, ip2, proxy2, localProtocol]);
+}
+__name(usePreviewServer, "usePreviewServer");
+function configureProxyServer({
+ proxy: proxy2,
+ previewToken,
+ streamBufferRef,
+ requestResponseBufferRef,
+ retryServerSetup,
+ port: port2,
+ localProtocol,
+ assetDirectory,
+ accessTokenRef
+}) {
+ if (proxy2 === void 0) {
+ return;
+ }
+ if (!previewToken) {
+ const cleanupListeners2 = [];
+ const bufferStream = /* @__PURE__ */ __name((stream2, headers) => {
+ streamBufferRef.current.push({ stream: stream2, headers });
+ }, "bufferStream");
+ proxy2.server.on("stream", bufferStream);
+ cleanupListeners2.push(() => proxy2.server.off("stream", bufferStream));
+ const bufferRequestResponse = /* @__PURE__ */ __name((request, response) => {
+ requestResponseBufferRef.current.push({ request, response });
+ }, "bufferRequestResponse");
+ proxy2.server.on("request", bufferRequestResponse);
+ cleanupListeners2.push(
+ () => proxy2.server.off("request", bufferRequestResponse)
+ );
+ return cleanupListeners2;
+ }
+ const cleanupListeners = [];
+ logger.debug("PREVIEW URL:", `https://${previewToken.host}`);
+ const remote = (0, import_node_http22.connect)(`https://${previewToken.host}`);
+ cleanupListeners.push(() => remote.destroy());
+ remote.on("close", retryServerSetup);
+ cleanupListeners.push(() => remote.off("close", retryServerSetup));
+ const handleStream = createStreamHandler(
+ previewToken,
+ remote,
+ port2,
+ localProtocol,
+ accessTokenRef
+ );
+ proxy2.server.on("stream", handleStream);
+ cleanupListeners.push(() => proxy2.server.off("stream", handleStream));
+ streamBufferRef.current.forEach(
+ (buffer) => handleStream(buffer.stream, buffer.headers)
+ );
+ streamBufferRef.current = [];
+ const handleRequest = /* @__PURE__ */ __name(async (message, response) => {
+ const { httpVersionMajor, headers, method, url: url3 } = message;
+ if (httpVersionMajor >= 2) {
+ return;
+ }
+ await addCfAccessToken(headers, previewToken.host, accessTokenRef);
+ addCfPreviewTokenHeader(headers, previewToken.value);
+ headers[":method"] = method;
+ headers[":path"] = url3;
+ headers[":authority"] = previewToken.host;
+ headers[":scheme"] = "https";
+ for (const name of Object.keys(headers)) {
+ if (HTTP1_HEADERS.has(name.toLowerCase())) {
+ delete headers[name];
+ }
+ }
+ const request = message.pipe(remote.request(headers));
+ logger.debug(
+ "WORKER REQUEST",
+ (/* @__PURE__ */ new Date()).toLocaleTimeString(),
+ method,
+ url3
+ );
+ logger.debug("HEADERS", JSON.stringify(headers, null, 2));
+ logger.debug("PREVIEW TOKEN", previewToken);
+ request.on("response", (responseHeaders) => {
+ const status = responseHeaders[":status"] ?? 500;
+ logger.log((/* @__PURE__ */ new Date()).toLocaleTimeString(), method, url3, status);
+ rewriteRemoteHostToLocalHostInHeaders(
+ responseHeaders,
+ previewToken.host,
+ port2,
+ localProtocol
+ );
+ for (const name of Object.keys(responseHeaders)) {
+ if (name.startsWith(":")) {
+ delete responseHeaders[name];
+ }
+ }
+ response.writeHead(status, responseHeaders);
+ request.pipe(response, { end: true });
+ });
+ }, "handleRequest");
+ const actualHandleRequest = assetDirectory ? createHandleAssetsRequest(assetDirectory, handleRequest) : handleRequest;
+ proxy2.server.on("request", actualHandleRequest);
+ cleanupListeners.push(() => proxy2.server.off("request", actualHandleRequest));
+ requestResponseBufferRef.current.forEach(
+ ({
+ request,
+ response
+ }) => actualHandleRequest(request, response)
+ );
+ requestResponseBufferRef.current = [];
+ const handleUpgrade = /* @__PURE__ */ __name(async (originalMessage, originalSocket, originalHead) => {
+ const { headers, method, url: url3 } = originalMessage;
+ await addCfAccessToken(headers, previewToken.host, accessTokenRef);
+ addCfPreviewTokenHeader(headers, previewToken.value);
+ headers["host"] = previewToken.host;
+ if (originalHead?.byteLength)
+ originalSocket.unshift(originalHead);
+ const runtimeRequest = import_node_https2.default.request(
+ {
+ hostname: previewToken.host,
+ path: url3,
+ method,
+ headers
+ },
+ (runtimeResponse) => {
+ if (!runtimeResponse.upgrade) {
+ writeHead(originalSocket, runtimeResponse);
+ runtimeResponse.pipe(originalSocket);
+ }
+ }
+ );
+ runtimeRequest.on(
+ "upgrade",
+ (runtimeResponse, runtimeSocket, runtimeHead) => {
+ if (runtimeHead?.byteLength)
+ runtimeSocket.unshift(runtimeHead);
+ writeHead(originalSocket, {
+ httpVersion: "1.1",
+ statusCode: 101,
+ statusMessage: "Switching Protocols",
+ headers: runtimeResponse.headers
+ });
+ runtimeSocket.pipe(originalSocket).pipe(runtimeSocket);
+ }
+ );
+ originalMessage.pipe(runtimeRequest);
+ }, "handleUpgrade");
+ proxy2.server.on("upgrade", handleUpgrade);
+ cleanupListeners.push(() => proxy2.server.off("upgrade", handleUpgrade));
+ return cleanupListeners;
+}
+__name(configureProxyServer, "configureProxyServer");
+function createHandleAssetsRequest(assetDirectory, handleRequest) {
+ const handleAsset = (0, import_serve_static.default)(assetDirectory, {
+ cacheControl: false
+ });
+ return (request, response) => {
+ handleAsset(request, response, () => {
+ handleRequest(request, response);
+ });
+ };
+}
+__name(createHandleAssetsRequest, "createHandleAssetsRequest");
+var HTTP1_HEADERS = /* @__PURE__ */ new Set([
+ "host",
+ "connection",
+ "upgrade",
+ "keep-alive",
+ "proxy-connection",
+ "transfer-encoding",
+ "http2-settings"
+]);
+async function createProxyServer(localProtocol) {
+ const server2 = localProtocol === "https" ? (0, import_node_https.createServer)(await getHttpsOptions()) : (0, import_node_http2.createServer)();
+ return server2.on("upgrade", (req) => {
+ logger.log(
+ (/* @__PURE__ */ new Date()).toLocaleTimeString(),
+ req.method,
+ req.url,
+ 101,
+ "(WebSocket)"
+ );
+ }).on("error", (err) => {
+ logger.error((/* @__PURE__ */ new Date()).toLocaleTimeString(), err);
+ });
+}
+__name(createProxyServer, "createProxyServer");
+function createStreamHandler(previewToken, remote, localPort, localProtocol, accessTokenRef) {
+ return /* @__PURE__ */ __name(async function handleStream(stream2, headers) {
+ await addCfAccessToken(headers, previewToken.host, accessTokenRef);
+ addCfPreviewTokenHeader(headers, previewToken.value);
+ headers[":authority"] = previewToken.host;
+ const request = stream2.pipe(remote.request(headers));
+ request.on("response", (responseHeaders) => {
+ rewriteRemoteHostToLocalHostInHeaders(
+ responseHeaders,
+ previewToken.host,
+ localPort,
+ localProtocol
+ );
+ stream2.respond(responseHeaders);
+ request.pipe(stream2, { end: true });
+ });
+ }, "handleStream");
+}
+__name(createStreamHandler, "createStreamHandler");
+async function waitForPortToBeAvailable(port2, options14) {
+ return new Promise((resolve18, reject) => {
+ options14.abortSignal.addEventListener("abort", () => {
+ const abortError = new Error("waitForPortToBeAvailable() aborted");
+ abortError.code = "ABORT_ERR";
+ doReject(abortError);
+ });
+ const timeout = setTimeout(() => {
+ doReject(new Error(`Timed out waiting for port ${port2}`));
+ }, options14.timeout);
+ const interval2 = setInterval(checkPort, options14.retryPeriod);
+ checkPort();
+ function doResolve() {
+ clearTimeout(timeout);
+ clearInterval(interval2);
+ resolve18();
+ }
+ __name(doResolve, "doResolve");
+ function doReject(err) {
+ clearInterval(interval2);
+ clearTimeout(timeout);
+ reject(err);
+ }
+ __name(doReject, "doReject");
+ function checkPort() {
+ if (port2 === 0) {
+ doResolve();
+ return;
+ }
+ const server2 = (0, import_node_http2.createServer)();
+ const terminator2 = (0, import_http_terminator2.createHttpTerminator)({
+ server: server2,
+ gracefulTerminationTimeout: 0
+ // default 1000
+ });
+ server2.on("error", (err) => {
+ if (err.code !== "EADDRINUSE") {
+ doReject(err);
+ }
+ });
+ server2.listen(
+ port2,
+ () => terminator2.terminate().then(
+ doResolve,
+ () => logger.error("Failed to terminate the port checker.")
+ )
+ );
+ }
+ __name(checkPort, "checkPort");
+ });
+}
+__name(waitForPortToBeAvailable, "waitForPortToBeAvailable");
+function getAccessibleHosts2() {
+ const hosts = [];
+ Object.values((0, import_node_os5.networkInterfaces)()).forEach((net3) => {
+ net3?.forEach(({ family, address }) => {
+ if (family === "IPv4" || family === 4)
+ hosts.push(address);
+ });
+ });
+ return hosts;
+}
+__name(getAccessibleHosts2, "getAccessibleHosts");
+
+// src/sourcemap.ts
+init_import_meta_url();
+var import_node_assert5 = __toESM(require("node:assert"));
+var sourceMappingPrepareStackTrace;
+function getSourceMappedStack(details) {
+ const description = details.exception?.description ?? "";
+ const callFrames = details.stackTrace?.callFrames;
+ if (callFrames === void 0)
+ return description;
+ if (sourceMappingPrepareStackTrace === void 0) {
+ const originalSupport = require.cache["source-map-support"];
+ delete require.cache["source-map-support"];
+ const support = require_source_map_support();
+ require.cache["source-map-support"] = originalSupport;
+ const originalPrepareStackTrace = Error.prepareStackTrace;
+ support.install({
+ environment: "node",
+ // Don't add Node `uncaughtException` handler
+ handleUncaughtExceptions: false,
+ // Don't hook Node `require` function
+ hookRequire: false,
+ // Make sure we're using fresh copies of files each time we source map
+ emptyCacheBetweenOperations: true
+ });
+ sourceMappingPrepareStackTrace = Error.prepareStackTrace;
+ (0, import_node_assert5.default)(sourceMappingPrepareStackTrace !== void 0);
+ Error.prepareStackTrace = originalPrepareStackTrace;
+ }
+ const nameMessage = details.exception?.description?.split("\n")[0] ?? "";
+ const colonIndex = nameMessage.indexOf(":");
+ const error = new Error(nameMessage.substring(colonIndex + 2));
+ error.name = nameMessage.substring(0, colonIndex);
+ const callSites = callFrames.map((frame) => new CallSite(frame));
+ return sourceMappingPrepareStackTrace(error, callSites);
+}
+__name(getSourceMappedStack, "getSourceMappedStack");
+var CallSite = class {
+ constructor(frame) {
+ this.frame = frame;
+ }
+ getThis() {
+ return null;
+ }
+ getTypeName() {
+ return null;
+ }
+ // eslint-disable-next-line @typescript-eslint/ban-types
+ getFunction() {
+ return void 0;
+ }
+ getFunctionName() {
+ return this.frame.functionName;
+ }
+ getMethodName() {
+ return null;
+ }
+ getFileName() {
+ return this.frame.url;
+ }
+ getScriptNameOrSourceURL() {
+ return this.frame.url;
+ }
+ getLineNumber() {
+ return this.frame.lineNumber;
+ }
+ getColumnNumber() {
+ return this.frame.columnNumber;
+ }
+ getEvalOrigin() {
+ return void 0;
+ }
+ isToplevel() {
+ return false;
+ }
+ isEval() {
+ return false;
+ }
+ isNative() {
+ return false;
+ }
+ isConstructor() {
+ return false;
+ }
+ isAsync() {
+ return false;
+ }
+ isPromiseAll() {
+ return false;
+ }
+ isPromiseAny() {
+ return false;
+ }
+ getPromiseIndex() {
+ return null;
+ }
+};
+__name(CallSite, "CallSite");
+
+// src/inspect.ts
+function useInspector(props) {
+ const inspectorIdRef = (0, import_react2.useRef)(import_node_crypto4.default.randomUUID());
+ const [localWebSocket, setLocalWebSocket] = (0, import_react2.useState)();
+ const [remoteWebSocket, setRemoteWebSocket] = (0, import_react2.useState)();
+ const sourceMaps = (0, import_react2.useRef)();
+ sourceMaps.current ??= /* @__PURE__ */ new Map();
+ const allowedSourcePaths = (0, import_react2.useRef)();
+ allowedSourcePaths.current ??= /* @__PURE__ */ new Set();
+ const serverRef = (0, import_react2.useRef)();
+ if (serverRef.current === void 0) {
+ serverRef.current = (0, import_node_http3.createServer)(
+ (req, res) => {
+ switch (req.url) {
+ case "/json/version":
+ res.setHeader("Content-Type", "application/json");
+ res.end(
+ JSON.stringify({
+ Browser: `wrangler/v${version}`,
+ // TODO: (someday): The DevTools protocol should match that of Edge Worker.
+ // This could be exposed by the preview API.
+ "Protocol-Version": "1.3"
+ })
+ );
+ return;
+ case "/json":
+ case "/json/list":
+ {
+ res.setHeader("Content-Type", "application/json");
+ const localHost = `localhost:${props.port}/ws`;
+ const devtoolsFrontendUrl = `devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=${localHost}`;
+ const devtoolsFrontendUrlCompat = `devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${localHost}`;
+ res.end(
+ JSON.stringify([
+ {
+ id: inspectorIdRef.current,
+ type: "node",
+ description: "workers",
+ webSocketDebuggerUrl: `ws://${localHost}`,
+ devtoolsFrontendUrl,
+ devtoolsFrontendUrlCompat,
+ // Below are fields that are visible in the DevTools UI.
+ title: "Cloudflare Worker",
+ faviconUrl: "https://workers.cloudflare.com/favicon.ico",
+ url: "https://" + (remoteWebSocket ? new import_node_url8.URL(remoteWebSocket.url).host : "workers.dev")
+ }
+ ])
+ );
+ }
+ return;
+ default:
+ break;
+ }
+ }
+ );
+ }
+ const server2 = serverRef.current;
+ const wsServerRef = (0, import_react2.useRef)();
+ if (wsServerRef.current === void 0) {
+ wsServerRef.current = new import_websocket_server.default({
+ server: server2,
+ clientTracking: true
+ });
+ }
+ const wsServer = wsServerRef.current;
+ wsServer.on("connection", (ws, req) => {
+ if (wsServer.clients.size > 1) {
+ logger.error(
+ "Tried to open a new devtools window when a previous one was already open."
+ );
+ ws.close(1013, "Too many clients; only one can be connected at a time");
+ } else {
+ remoteWebSocket?.send(
+ JSON.stringify({
+ // This number is arbitrary, and is chosen to be high so as not to conflict with messages that DevTools might actually send.
+ // For completeness, these options don't work: 0, -1, or Number.MAX_SAFE_INTEGER
+ id: 1e8,
+ method: "Debugger.disable"
+ })
+ );
+ const localWs = ws;
+ localWs.isDevTools = /mozilla/i.test(req.headers["user-agent"] ?? "");
+ setLocalWebSocket(localWs);
+ ws.addEventListener("close", () => {
+ setLocalWebSocket(void 0);
+ });
+ }
+ });
+ (0, import_react2.useEffect)(() => {
+ const abortController = new AbortController();
+ async function startInspectorProxy() {
+ await waitForPortToBeAvailable(props.port, {
+ retryPeriod: 200,
+ timeout: 2e3,
+ abortSignal: abortController.signal
+ });
+ server2.listen(props.port);
+ }
+ __name(startInspectorProxy, "startInspectorProxy");
+ startInspectorProxy().catch((err) => {
+ if (err.code !== "ABORT_ERR") {
+ logger.error("Failed to start inspector:", err);
+ }
+ });
+ return () => {
+ server2.close();
+ wsServer.clients.forEach((ws) => ws.close());
+ wsServer.close();
+ abortController.abort();
+ };
+ }, [props.port, server2, wsServer]);
+ const [
+ retryRemoteWebSocketConnectionSigil,
+ setRetryRemoteWebSocketConnectionSigil
+ ] = (0, import_react2.useState)(0);
+ function retryRemoteWebSocketConnection() {
+ setRetryRemoteWebSocketConnectionSigil((x) => x + 1);
+ }
+ __name(retryRemoteWebSocketConnection, "retryRemoteWebSocketConnection");
+ const messageCounterRef = (0, import_react2.useRef)(1);
+ const cfAccessRef = (0, import_react2.useRef)();
+ (0, import_react2.useEffect)(() => {
+ const run = /* @__PURE__ */ __name(async () => {
+ if (props.host && !cfAccessRef.current) {
+ const token = await getAccessToken(props.host);
+ cfAccessRef.current = token;
+ }
+ }, "run");
+ if (props.host)
+ void run();
+ }, [props.host]);
+ (0, import_react2.useEffect)(() => {
+ if (!props.inspectorUrl) {
+ return;
+ }
+ const ws = new wrapper_default(props.inspectorUrl, {
+ headers: {
+ cookie: `CF_Authorization=${cfAccessRef.current}`
+ }
+ });
+ setRemoteWebSocket(ws);
+ let keepAliveInterval;
+ function isClosed() {
+ return ws.readyState === wrapper_default.CLOSED || ws.readyState === wrapper_default.CLOSING;
+ }
+ __name(isClosed, "isClosed");
+ function send(event) {
+ if (!isClosed()) {
+ ws.send(JSON.stringify(event));
+ }
+ }
+ __name(send, "send");
+ function close() {
+ if (!isClosed()) {
+ try {
+ ws.close();
+ } catch (err) {
+ }
+ }
+ }
+ __name(close, "close");
+ if (props.logToTerminal) {
+ ws.addEventListener("message", async (event) => {
+ if (typeof event.data === "string") {
+ const evt = JSON.parse(event.data);
+ if (evt.method === "Runtime.exceptionThrown") {
+ const params = evt.params;
+ const stack = getSourceMappedStack(params.exceptionDetails);
+ logger.error(params.exceptionDetails.text, stack);
+ }
+ if (evt.method === "Runtime.consoleAPICalled") {
+ logConsoleMessage(
+ evt.params
+ );
+ }
+ } else {
+ logger.error("Unrecognised devtools event:", event);
+ }
+ });
+ }
+ ws.addEventListener("open", () => {
+ send({ method: "Runtime.enable", id: messageCounterRef.current });
+ send({ method: "Network.enable", id: messageCounterRef.current++ });
+ keepAliveInterval = setInterval(() => {
+ send({
+ method: "Runtime.getIsolateId",
+ id: messageCounterRef.current++
+ });
+ }, 1e4);
+ });
+ ws.on("unexpected-response", () => {
+ logger.log("Waiting for connection...");
+ retryRemoteWebSocketConnection();
+ });
+ ws.addEventListener("close", () => {
+ clearInterval(keepAliveInterval);
+ });
+ return () => {
+ clearInterval(keepAliveInterval);
+ wsServer.clients.forEach((client) => {
+ client.send(
+ JSON.stringify({
+ // TODO: This doesn't actually work. Must fix.
+ method: "Log.clear",
+ // we can disable the next eslint warning since
+ // we're referencing a ref that stays alive
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ id: messageCounterRef.current++,
+ params: {}
+ })
+ );
+ });
+ close();
+ setRemoteWebSocket(void 0);
+ };
+ }, [
+ props.inspectorUrl,
+ props.logToTerminal,
+ props.sourceMapPath,
+ wsServer,
+ // We use a state value as a sigil to trigger a retry of the
+ // remote websocket connection. It's not used inside the effect,
+ // so react-hooks/exhaustive-deps doesn't complain if it's not
+ // included in the dependency array. But its presence is critical,
+ // so do NOT remove it from the dependency list.
+ retryRemoteWebSocketConnectionSigil
+ ]);
+ const messageBufferRef = (0, import_react2.useRef)([]);
+ (0, import_react2.useEffect)(() => {
+ function bufferMessageFromRemoteSocket(event) {
+ messageBufferRef.current.push(event);
+ }
+ __name(bufferMessageFromRemoteSocket, "bufferMessageFromRemoteSocket");
+ if (remoteWebSocket && !localWebSocket) {
+ remoteWebSocket.addEventListener(
+ "message",
+ bufferMessageFromRemoteSocket
+ );
+ }
+ function sendMessageToRemoteWebSocket(event) {
+ try {
+ const message = JSON.parse(event.data);
+ if (message.method === "Network.loadNetworkResource") {
+ (0, import_node_assert6.default)(sourceMaps.current !== void 0);
+ (0, import_node_assert6.default)(allowedSourcePaths.current !== void 0);
+ const maybeText = maybeHandleNetworkLoadResource(
+ message.params.url,
+ sourceMaps.current,
+ allowedSourcePaths.current,
+ props.sourceMapMetadata?.tmpDir
+ );
+ if (maybeText !== void 0) {
+ sendMessageToLocalWebSocket({
+ data: JSON.stringify({
+ id: message.id,
+ result: { resource: { success: true, text: maybeText } }
+ })
+ });
+ return;
+ }
+ }
+ } catch (e2) {
+ logger.debug(e2);
+ }
+ try {
+ (0, import_node_assert6.default)(
+ remoteWebSocket,
+ "Trying to send a message to an undefined `remoteWebSocket`"
+ );
+ remoteWebSocket.send(event.data);
+ } catch (e2) {
+ if (e2.message !== "WebSocket is not open: readyState 0 (CONNECTING)") {
+ logger.error(e2);
+ }
+ }
+ }
+ __name(sendMessageToRemoteWebSocket, "sendMessageToRemoteWebSocket");
+ function sendMessageToLocalWebSocket(event) {
+ (0, import_node_assert6.default)(
+ localWebSocket,
+ "Trying to send a message to an undefined `localWebSocket`"
+ );
+ try {
+ if (localWebSocket.isDevTools) {
+ const message = JSON.parse(event.data);
+ if (message.method === "Debugger.scriptParsed") {
+ if (message.params.sourceMapURL) {
+ const url3 = new import_node_url8.URL(
+ message.params.sourceMapURL,
+ message.params.url
+ );
+ if (url3.protocol === "file:") {
+ (0, import_node_assert6.default)(sourceMaps.current !== void 0);
+ const name = props.name ?? "worker";
+ const id = import_node_crypto4.default.randomUUID();
+ sourceMaps.current.set(id, (0, import_node_url8.fileURLToPath)(url3));
+ message.params.sourceMapURL = `worker://${name}/${id}`;
+ localWebSocket.send(JSON.stringify(message));
+ return;
+ }
+ }
+ }
+ }
+ } catch (e2) {
+ logger.debug(e2);
+ }
+ localWebSocket.send(event.data);
+ }
+ __name(sendMessageToLocalWebSocket, "sendMessageToLocalWebSocket");
+ if (localWebSocket && remoteWebSocket) {
+ localWebSocket.addEventListener("message", sendMessageToRemoteWebSocket);
+ remoteWebSocket.addEventListener("message", sendMessageToLocalWebSocket);
+ messageBufferRef.current.forEach(sendMessageToLocalWebSocket);
+ messageBufferRef.current = [];
+ }
+ return () => {
+ if (remoteWebSocket) {
+ remoteWebSocket.removeEventListener(
+ "message",
+ bufferMessageFromRemoteSocket
+ );
+ remoteWebSocket.removeEventListener(
+ "message",
+ sendMessageToLocalWebSocket
+ );
+ }
+ if (localWebSocket) {
+ localWebSocket.removeEventListener(
+ "message",
+ sendMessageToRemoteWebSocket
+ );
+ }
+ };
+ }, [
+ localWebSocket,
+ remoteWebSocket,
+ props.name,
+ props.sourceMapMetadata,
+ props.sourceMapPath
+ ]);
+}
+__name(useInspector, "useInspector");
+var mapConsoleAPIMessageTypeToConsoleMethod = {
+ log: "log",
+ debug: "debug",
+ info: "info",
+ warning: "warn",
+ error: "error",
+ dir: "dir",
+ dirxml: "dirxml",
+ table: "table",
+ trace: "trace",
+ clear: "clear",
+ count: "count",
+ assert: "assert",
+ profile: "profile",
+ profileEnd: "profileEnd",
+ timeEnd: "timeEnd",
+ startGroup: "group",
+ startGroupCollapsed: "groupCollapsed",
+ endGroup: "groupEnd"
+};
+function logConsoleMessage(evt) {
+ const args = [];
+ for (const ro2 of evt.args) {
+ switch (ro2.type) {
+ case "string":
+ case "number":
+ case "boolean":
+ case "undefined":
+ case "symbol":
+ case "bigint":
+ args.push(ro2.value);
+ break;
+ case "function":
+ args.push(`[Function: ${ro2.description ?? ""}]`);
+ break;
+ case "object":
+ if (!ro2.preview) {
+ args.push(
+ ro2.subtype === "null" ? "null" : ro2.description ?? ""
+ );
+ } else {
+ args.push(ro2.preview.description ?? "");
+ switch (ro2.preview.subtype) {
+ case "array":
+ args.push(
+ "[ " + ro2.preview.properties.map(({ value }) => {
+ return value;
+ }).join(", ") + (ro2.preview.overflow ? "..." : "") + " ]"
+ );
+ break;
+ case "weakmap":
+ case "map":
+ ro2.preview.entries === void 0 ? args.push("{}") : args.push(
+ "{\n" + ro2.preview.entries.map(({ key, value }) => {
+ return ` ${key?.description ?? ""} => ${value.description}`;
+ }).join(",\n") + (ro2.preview.overflow ? "\n ..." : "") + "\n}"
+ );
+ break;
+ case "weakset":
+ case "set":
+ ro2.preview.entries === void 0 ? args.push("{}") : args.push(
+ "{ " + ro2.preview.entries.map(({ value }) => {
+ return `${value.description}`;
+ }).join(", ") + (ro2.preview.overflow ? ", ..." : "") + " }"
+ );
+ break;
+ case "regexp":
+ break;
+ case "date":
+ break;
+ case "generator":
+ args.push(ro2.preview.properties[0].value || "");
+ break;
+ case "promise":
+ if (ro2.preview.properties[0].value === "pending") {
+ args.push(`{<${ro2.preview.properties[0].value}>}`);
+ } else {
+ args.push(
+ `{<${ro2.preview.properties[0].value}>: ${ro2.preview.properties[1].value}}`
+ );
+ }
+ break;
+ case "node":
+ case "iterator":
+ case "proxy":
+ case "typedarray":
+ case "arraybuffer":
+ case "dataview":
+ case "webassemblymemory":
+ case "wasmvalue":
+ break;
+ case "error":
+ default:
+ args.push(
+ "{\n" + ro2.preview.properties.map(({ name, value }) => {
+ return ` ${name}: ${value}`;
+ }).join(",\n") + (ro2.preview.overflow ? "\n ..." : "") + "\n}"
+ );
+ }
+ }
+ break;
+ default:
+ args.push(ro2.description || ro2.unserializableValue || "\u{1F98B}");
+ break;
+ }
+ }
+ const method = mapConsoleAPIMessageTypeToConsoleMethod[evt.type];
+ if (method in console) {
+ switch (method) {
+ case "dir":
+ console.dir(args);
+ break;
+ case "table":
+ console.table(args);
+ break;
+ default:
+ console[method].apply(console, args);
+ break;
+ }
+ } else {
+ logger.warn(`Unsupported console method: ${method}`);
+ logger.warn("console event:", evt);
+ }
+}
+__name(logConsoleMessage, "logConsoleMessage");
+function maybeHandleNetworkLoadResource(url3, sourceMaps, allowedSourcePaths, tmpDir) {
+ if (typeof url3 === "string")
+ url3 = new import_node_url8.URL(url3);
+ if (url3.protocol !== "worker:")
+ return;
+ const id = url3.pathname.substring(1);
+ const maybeSourceMapFilePath = sourceMaps.get(id);
+ if (maybeSourceMapFilePath !== void 0) {
+ sourceMaps.delete(id);
+ const sourceMap = JSON.parse((0, import_fs6.readFileSync)(maybeSourceMapFilePath, "utf-8"));
+ sourceMap.x_google_ignoreList = sourceMap.sources.map((source, i) => {
+ if (tmpDir !== void 0 && source.includes(tmpDir))
+ return i;
+ if (source.includes("wrangler/templates"))
+ return i;
+ }).filter((i) => i !== void 0);
+ if (!sourceMap.sourcesContent) {
+ const fileURL = (0, import_node_url8.pathToFileURL)(maybeSourceMapFilePath);
+ for (const source of sourceMap.sources) {
+ const sourcePath = (0, import_node_url8.fileURLToPath)(new import_node_url8.URL(source, fileURL));
+ allowedSourcePaths.add(sourcePath);
+ }
+ }
+ return JSON.stringify(sourceMap);
+ }
+ const filePath = import_node_path16.default.resolve(id);
+ if (allowedSourcePaths.has(filePath)) {
+ allowedSourcePaths.delete(filePath);
+ return (0, import_fs6.readFileSync)(filePath, "utf-8");
+ }
+}
+__name(maybeHandleNetworkLoadResource, "maybeHandleNetworkLoadResource");
+var openInspector = /* @__PURE__ */ __name(async (inspectorPort, worker) => {
+ const query = new URLSearchParams();
+ query.set("theme", "systemPreferred");
+ query.set("ws", `localhost:${inspectorPort}/ws`);
+ if (worker)
+ query.set("domain", worker);
+ query.set("debugger", "true");
+ const url3 = `https://devtools.devprod.cloudflare.dev/js_app?${query.toString()}`;
+ const errorMessage = "Failed to open inspector.\nInspector depends on having a Chromium-based browser installed, maybe you need to install one?";
+ let braveBrowser;
+ switch (import_node_os6.default.platform()) {
+ case "darwin":
+ case "win32":
+ braveBrowser = "Brave";
+ break;
+ default:
+ braveBrowser = "brave";
+ }
+ const childProcess2 = await (0, import_open2.default)(url3, {
+ app: [
+ {
+ name: import_open2.default.apps.chrome
+ },
+ {
+ name: braveBrowser
+ },
+ {
+ name: import_open2.default.apps.edge
+ },
+ {
+ name: import_open2.default.apps.firefox
+ }
+ ]
+ });
+ childProcess2.on("error", () => {
+ logger.warn(errorMessage);
+ });
+}, "openInspector");
+
+// src/dev/local.tsx
+init_import_meta_url();
+var import_node_assert8 = __toESM(require("node:assert"));
+var import_chalk4 = __toESM(require_chalk());
+var import_react3 = __toESM(require_react());
+var import_signal_exit2 = __toESM(require_signal_exit());
+var import_undici6 = __toESM(require_undici());
+
+// src/dev/miniflare.ts
+init_import_meta_url();
+var import_node_assert7 = __toESM(require("node:assert"));
+var import_node_fs6 = require("node:fs");
+var import_promises2 = require("node:fs/promises");
+var import_node_path17 = __toESM(require("node:path"));
+var import_miniflare = require("miniflare");
+var EXTERNAL_DURABLE_OBJECTS_WORKER_NAME = "__WRANGLER_EXTERNAL_DURABLE_OBJECTS_WORKER";
+var EXTERNAL_DURABLE_OBJECTS_WORKER_SCRIPT = `
+const HEADER_URL = "X-Miniflare-Durable-Object-URL";
+const HEADER_NAME = "X-Miniflare-Durable-Object-Name";
+const HEADER_ID = "X-Miniflare-Durable-Object-Id";
+
+function createClass({ className, proxyUrl }) {
+ return class {
+ constructor(state) {
+ this.id = state.id.toString();
+ }
+ fetch(request) {
+ if (proxyUrl === undefined) {
+ return new Response(\`[wrangler] Couldn't find \\\`wrangler dev\\\` session for class "\${className}" to proxy to\`, { status: 503 });
+ }
+ const proxyRequest = new Request(proxyUrl, request);
+ proxyRequest.headers.set(HEADER_URL, request.url);
+ proxyRequest.headers.set(HEADER_NAME, className);
+ proxyRequest.headers.set(HEADER_ID, this.id);
+ return fetch(proxyRequest);
+ }
+ }
+}
+
+export default {
+ async fetch(request, env) {
+ const originalUrl = request.headers.get(HEADER_URL);
+ const className = request.headers.get(HEADER_NAME);
+ const idString = request.headers.get(HEADER_ID);
+ if (originalUrl === null || className === null || idString === null) {
+ return new Response("[wrangler] Received Durable Object proxy request with missing headers", { status: 400 });
+ }
+ request = new Request(originalUrl, request);
+ request.headers.delete(HEADER_URL);
+ request.headers.delete(HEADER_NAME);
+ request.headers.delete(HEADER_ID);
+ const ns = env[className];
+ const id = ns.idFromString(idString);
+ const stub = ns.get(id);
+ return stub.fetch(request);
+ }
+}
+`;
+var WranglerLog = class extends import_miniflare.Log {
+ #warnedCompatibilityDateFallback = false;
+ info(message) {
+ if (message.includes(EXTERNAL_DURABLE_OBJECTS_WORKER_NAME))
+ return;
+ super.info(message);
+ }
+ warn(message) {
+ if (message.startsWith("The latest compatibility date supported by")) {
+ if (this.#warnedCompatibilityDateFallback)
+ return;
+ this.#warnedCompatibilityDateFallback = true;
+ }
+ super.warn(message);
+ }
+};
+__name(WranglerLog, "WranglerLog");
+function getName(config) {
+ return config.name ?? "worker";
+}
+__name(getName, "getName");
+var IDENTIFIER_UNSAFE_REGEXP = /[^a-zA-Z0-9_$]/g;
+function getIdentifier(name) {
+ return name.replace(IDENTIFIER_UNSAFE_REGEXP, "_");
+}
+__name(getIdentifier, "getIdentifier");
+function buildLog() {
+ let level = logger.loggerLevel.toUpperCase();
+ if (level === "LOG")
+ level = "INFO";
+ const logLevel = import_miniflare.LogLevel[level];
+ return logLevel === import_miniflare.LogLevel.NONE ? new import_miniflare.NoOpLog() : new WranglerLog(logLevel);
+}
+__name(buildLog, "buildLog");
+async function buildSourceOptions(config) {
+ const scriptPath = (0, import_node_fs6.realpathSync)(config.bundle.path);
+ if (config.format === "modules") {
+ const modulesRoot = import_node_path17.default.dirname(scriptPath);
+ return {
+ modulesRoot,
+ modules: [
+ // Entrypoint
+ {
+ type: "ESModule",
+ path: scriptPath,
+ contents: await (0, import_promises2.readFile)(scriptPath, "utf-8")
+ },
+ // Misc (WebAssembly, etc, ...)
+ ...config.bundle.modules.map((module2) => ({
+ type: ModuleTypeToRuleType[module2.type ?? "esm"],
+ path: import_node_path17.default.resolve(modulesRoot, module2.name),
+ contents: module2.content
+ }))
+ ]
+ };
+ } else {
+ return { scriptPath };
+ }
+}
+__name(buildSourceOptions, "buildSourceOptions");
+function kvNamespaceEntry({ binding, id }) {
+ return [binding, id];
+}
+__name(kvNamespaceEntry, "kvNamespaceEntry");
+function r2BucketEntry({ binding, bucket_name }) {
+ return [binding, bucket_name];
+}
+__name(r2BucketEntry, "r2BucketEntry");
+function d1DatabaseEntry(db) {
+ return [db.binding, db.preview_database_id ?? db.database_id];
+}
+__name(d1DatabaseEntry, "d1DatabaseEntry");
+function queueProducerEntry(queue) {
+ return [queue.binding, queue.queue_name];
+}
+__name(queueProducerEntry, "queueProducerEntry");
+function queueConsumerEntry(consumer) {
+ const options14 = {
+ maxBatchSize: consumer.max_batch_size,
+ maxBatchTimeout: consumer.max_batch_timeout,
+ maxRetires: consumer.max_retries,
+ deadLetterQueue: consumer.dead_letter_queue
+ };
+ return [consumer.queue, options14];
+}
+__name(queueConsumerEntry, "queueConsumerEntry");
+function buildBindingOptions(config) {
+ const bindings = config.bindings;
+ const textBlobBindings = { ...bindings.text_blobs };
+ const dataBlobBindings = { ...bindings.data_blobs };
+ const wasmBindings = { ...bindings.wasm_modules };
+ if (config.format === "service-worker") {
+ const scriptPath = (0, import_node_fs6.realpathSync)(config.bundle.path);
+ const modulesRoot = import_node_path17.default.dirname(scriptPath);
+ for (const { type, name } of config.bundle.modules) {
+ if (type === "text") {
+ textBlobBindings[getIdentifier(name)] = import_node_path17.default.resolve(modulesRoot, name);
+ } else if (type === "buffer") {
+ dataBlobBindings[getIdentifier(name)] = import_node_path17.default.resolve(modulesRoot, name);
+ } else if (type === "compiled-wasm") {
+ wasmBindings[getIdentifier(name)] = import_node_path17.default.resolve(modulesRoot, name);
+ }
+ }
+ }
+ const internalObjects = [];
+ const externalObjects = [];
+ for (const binding of bindings.durable_objects?.bindings ?? []) {
+ const internal = binding.script_name === void 0 || binding.script_name === config.name;
+ (internal ? internalObjects : externalObjects).push(binding);
+ }
+ const externalDurableObjectWorker = {
+ name: EXTERNAL_DURABLE_OBJECTS_WORKER_NAME,
+ // Bind all internal objects, so they're accessible by all other sessions
+ // that proxy requests for our objects to this worker
+ durableObjects: Object.fromEntries(
+ internalObjects.map(({ class_name }) => [
+ class_name,
+ { className: class_name, scriptName: getName(config) }
+ ])
+ ),
+ // Use this worker instead of the user worker if the pathname is
+ // `/${EXTERNAL_DURABLE_OBJECTS_WORKER_NAME}`
+ routes: [`*/${EXTERNAL_DURABLE_OBJECTS_WORKER_NAME}`],
+ // Use in-memory storage for the stub object classes *declared* by this
+ // script. They don't need to persist anything, and would end up using the
+ // incorrect unsafe unique key.
+ unsafeEphemeralDurableObjects: true,
+ modules: true,
+ script: EXTERNAL_DURABLE_OBJECTS_WORKER_SCRIPT + // Add stub object classes that proxy requests to the correct session
+ externalObjects.map(({ class_name, script_name }) => {
+ (0, import_node_assert7.default)(script_name !== void 0);
+ const target = config.workerDefinitions?.[script_name];
+ const targetHasClass = target?.durableObjects.some(
+ ({ className }) => className === class_name
+ );
+ const identifier = getIdentifier(`${script_name}_${class_name}`);
+ const classNameJson = JSON.stringify(class_name);
+ if (target?.host === void 0 || target.port === void 0 || !targetHasClass) {
+ return `export const ${identifier} = createClass({ className: ${classNameJson} });`;
+ } else {
+ const proxyUrl = `http://${target.host}:${target.port}/${EXTERNAL_DURABLE_OBJECTS_WORKER_NAME}`;
+ const proxyUrlJson = JSON.stringify(proxyUrl);
+ return `export const ${identifier} = createClass({ className: ${classNameJson}, proxyUrl: ${proxyUrlJson} });`;
+ }
+ }).join("\n")
+ };
+ const bindingOptions = {
+ bindings: bindings.vars,
+ textBlobBindings,
+ dataBlobBindings,
+ wasmBindings,
+ kvNamespaces: Object.fromEntries(
+ bindings.kv_namespaces?.map(kvNamespaceEntry) ?? []
+ ),
+ r2Buckets: Object.fromEntries(
+ bindings.r2_buckets?.map(r2BucketEntry) ?? []
+ ),
+ d1Databases: Object.fromEntries(
+ bindings.d1_databases?.map(d1DatabaseEntry) ?? []
+ ),
+ queueProducers: Object.fromEntries(
+ bindings.queues?.map(queueProducerEntry) ?? []
+ ),
+ queueConsumers: Object.fromEntries(
+ config.queueConsumers?.map(queueConsumerEntry) ?? []
+ ),
+ durableObjects: Object.fromEntries([
+ ...internalObjects.map(({ name, class_name }) => [name, class_name]),
+ ...externalObjects.map(({ name, class_name, script_name }) => {
+ const identifier = getIdentifier(`${script_name}_${class_name}`);
+ return [
+ name,
+ {
+ className: identifier,
+ scriptName: EXTERNAL_DURABLE_OBJECTS_WORKER_NAME,
+ // Matches the unique key Miniflare will generate for this object in
+ // the target session. We need to do this so workerd generates the
+ // same IDs it would if this were part of the same process. workerd
+ // doesn't allow IDs from Durable Objects with different unique keys
+ // to be used with each other.
+ unsafeUniqueKey: `${script_name}-${class_name}`
+ }
+ ];
+ })
+ ]),
+ serviceBindings: config.serviceBindings
+ // TODO: check multi worker service bindings also supported
+ };
+ return {
+ bindingOptions,
+ internalObjects,
+ externalDurableObjectWorker
+ };
+}
+__name(buildBindingOptions, "buildBindingOptions");
+function buildPersistOptions(localPersistencePath) {
+ if (localPersistencePath !== null) {
+ const v3Path = import_node_path17.default.join(localPersistencePath, "v3");
+ return {
+ cachePersist: import_node_path17.default.join(v3Path, "cache"),
+ durableObjectsPersist: import_node_path17.default.join(v3Path, "do"),
+ kvPersist: import_node_path17.default.join(v3Path, "kv"),
+ r2Persist: import_node_path17.default.join(v3Path, "r2"),
+ d1Persist: import_node_path17.default.join(v3Path, "d1")
+ };
+ }
+}
+__name(buildPersistOptions, "buildPersistOptions");
+function buildSitesOptions({ assetPaths }) {
+ if (assetPaths !== void 0) {
+ const { baseDirectory, assetDirectory, includePatterns, excludePatterns } = assetPaths;
+ return {
+ sitePath: import_node_path17.default.join(baseDirectory, assetDirectory),
+ siteInclude: includePatterns.length > 0 ? includePatterns : void 0,
+ siteExclude: excludePatterns.length > 0 ? excludePatterns : void 0
+ };
+ }
+}
+__name(buildSitesOptions, "buildSitesOptions");
+async function buildMiniflareOptions(log, config) {
+ if (config.crons.length > 0) {
+ logger.warn("Miniflare 3 does not support CRON triggers yet, ignoring...");
+ }
+ const upstream = typeof config.localUpstream === "string" ? `${config.localProtocol}://${config.localUpstream}` : void 0;
+ const sourceOptions = await buildSourceOptions(config);
+ const { bindingOptions, internalObjects, externalDurableObjectWorker } = buildBindingOptions(config);
+ const sitesOptions = buildSitesOptions(config);
+ const persistOptions = buildPersistOptions(config.localPersistencePath);
+ let httpsOptions;
+ if (config.localProtocol === "https") {
+ const cert = await getHttpsOptions();
+ httpsOptions = {
+ httpsKey: cert.key,
+ httpsCert: cert.cert
+ };
+ }
+ const options14 = {
+ host: config.initialIp,
+ port: config.initialPort,
+ inspectorPort: config.inspect ? config.inspectorPort : void 0,
+ liveReload: config.liveReload,
+ upstream,
+ log,
+ verbose: logger.loggerLevel === "debug",
+ ...httpsOptions,
+ ...persistOptions,
+ workers: [
+ {
+ name: getName(config),
+ compatibilityDate: config.compatibilityDate,
+ compatibilityFlags: config.compatibilityFlags,
+ ...sourceOptions,
+ ...bindingOptions,
+ ...sitesOptions
+ },
+ externalDurableObjectWorker
+ ]
+ };
+ return { options: options14, internalObjects };
+}
+__name(buildMiniflareOptions, "buildMiniflareOptions");
+var ReloadedEvent = class extends Event {
+ url;
+ internalDurableObjects;
+ constructor(type, options14) {
+ super(type);
+ this.url = options14.url;
+ this.internalDurableObjects = options14.internalDurableObjects;
+ }
+};
+__name(ReloadedEvent, "ReloadedEvent");
+var ErrorEvent = class extends Event {
+ error;
+ constructor(type, options14) {
+ super(type);
+ this.error = options14.error;
+ }
+};
+__name(ErrorEvent, "ErrorEvent");
+var MiniflareServer = class extends import_miniflare.TypedEventTarget {
+ #log = buildLog();
+ #mf;
+ // `buildMiniflareOptions()` is asynchronous, meaning if multiple bundle
+ // updates were submitted, the second may apply before the first. Therefore,
+ // wrap updates in a mutex, so they're always applied in invocation order.
+ #mutex = new import_miniflare.Mutex();
+ async #onBundleUpdate(config, opts) {
+ if (opts?.signal?.aborted)
+ return;
+ try {
+ const { options: options14, internalObjects } = await buildMiniflareOptions(
+ this.#log,
+ config
+ );
+ if (opts?.signal?.aborted)
+ return;
+ if (this.#mf === void 0) {
+ this.#mf = new import_miniflare.Miniflare(options14);
+ } else {
+ await this.#mf.setOptions(options14);
+ }
+ const url3 = await this.#mf.ready;
+ if (opts?.signal?.aborted)
+ return;
+ const event = new ReloadedEvent("reloaded", {
+ url: url3,
+ internalDurableObjects: internalObjects
+ });
+ this.dispatchEvent(event);
+ } catch (error) {
+ this.dispatchEvent(new ErrorEvent("error", { error }));
+ }
+ }
+ onBundleUpdate(config, opts) {
+ return this.#mutex.runWith(() => this.#onBundleUpdate(config, opts));
+ }
+ #onDispose = async () => {
+ await this.#mf?.dispose();
+ this.#mf = void 0;
+ };
+ onDispose() {
+ return this.#mutex.runWith(this.#onDispose);
+ }
+};
+__name(MiniflareServer, "MiniflareServer");
+
+// src/dev/local.tsx
+async function localPropsToConfigBundle(props) {
+ (0, import_node_assert8.default)(props.bundle !== void 0);
+ const serviceBindings = {};
+ if (props.enablePagesAssetsServiceBinding !== void 0) {
+ const generateASSETSBinding2 = (init_assets(), __toCommonJS(assets_exports)).default;
+ serviceBindings.ASSETS = await generateASSETSBinding2({
+ log: logger,
+ ...props.enablePagesAssetsServiceBinding
+ });
+ }
+ return {
+ name: props.name,
+ bundle: props.bundle,
+ format: props.format,
+ compatibilityDate: props.compatibilityDate,
+ compatibilityFlags: props.compatibilityFlags,
+ inspectorPort: props.runtimeInspectorPort,
+ usageModel: props.usageModel,
+ bindings: props.bindings,
+ workerDefinitions: props.workerDefinitions,
+ assetPaths: props.assetPaths,
+ initialPort: props.initialPort,
+ initialIp: props.initialIp,
+ rules: props.rules,
+ localPersistencePath: props.localPersistencePath,
+ liveReload: props.liveReload,
+ crons: props.crons,
+ queueConsumers: props.queueConsumers,
+ localProtocol: props.localProtocol,
+ localUpstream: props.localUpstream,
+ inspect: props.inspect,
+ serviceBindings
+ };
+}
+__name(localPropsToConfigBundle, "localPropsToConfigBundle");
+function maybeRegisterLocalWorker(event, name) {
+ if (name === void 0)
+ return;
+ let protocol = event.url.protocol;
+ protocol = protocol.substring(0, event.url.protocol.length - 1);
+ if (protocol !== "http" && protocol !== "https")
+ return;
+ const port2 = parseInt(event.url.port);
+ return registerWorker(name, {
+ protocol,
+ mode: "local",
+ port: port2,
+ host: event.url.hostname,
+ durableObjects: event.internalDurableObjects.map((binding) => ({
+ name: binding.name,
+ className: binding.class_name
+ })),
+ durableObjectsHost: event.url.hostname,
+ durableObjectsPort: port2
+ });
+}
+__name(maybeRegisterLocalWorker, "maybeRegisterLocalWorker");
+function Local(props) {
+ const { inspectorUrl } = useLocalWorker(props);
+ useInspector({
+ inspectorUrl,
+ port: props.inspectorPort,
+ logToTerminal: true,
+ sourceMapPath: props.sourceMapPath,
+ name: props.name,
+ sourceMapMetadata: props.bundle?.sourceMapMetadata
+ });
+ return null;
+}
+__name(Local, "Local");
+function useLocalWorker(props) {
+ const miniflareServerRef = (0, import_react3.useRef)();
+ const removeMiniflareServerExitListenerRef = (0, import_react3.useRef)();
+ const [inspectorUrl, setInspectorUrl] = (0, import_react3.useState)();
+ (0, import_react3.useEffect)(() => {
+ if (props.bindings.services && props.bindings.services.length > 0) {
+ logger.warn(
+ "\u2394 Support for service bindings in local mode is experimental and may change."
+ );
+ }
+ }, [props.bindings.services]);
+ (0, import_react3.useEffect)(() => {
+ const externalDurableObjects = (props.bindings.durable_objects?.bindings || []).filter((binding) => binding.script_name);
+ if (externalDurableObjects.length > 0) {
+ logger.warn(
+ "\u2394 Support for external Durable Objects in local mode is experimental and may change."
+ );
+ }
+ }, [props.bindings.durable_objects?.bindings]);
+ (0, import_react3.useEffect)(() => {
+ const abortController = new AbortController();
+ if (!props.bundle || !props.format)
+ return;
+ let server2 = miniflareServerRef.current;
+ if (server2 === void 0) {
+ logger.log(import_chalk4.default.dim("\u2394 Starting local server..."));
+ const newServer = new MiniflareServer();
+ miniflareServerRef.current = server2 = newServer;
+ server2.addEventListener("reloaded", async (event) => {
+ await maybeRegisterLocalWorker(event, props.name);
+ props.onReady?.(event.url.hostname, parseInt(event.url.port));
+ try {
+ const jsonUrl = `http://127.0.0.1:${props.runtimeInspectorPort}/json`;
+ const res = await (0, import_undici6.fetch)(jsonUrl);
+ const body = await res.json();
+ const debuggerUrl = body?.find(
+ ({ id }) => id.startsWith("core:user")
+ )?.webSocketDebuggerUrl;
+ if (debuggerUrl === void 0) {
+ setInspectorUrl(void 0);
+ } else {
+ const url3 = new URL(debuggerUrl);
+ url3.username = `${Date.now()}-${Math.floor(
+ Math.random() * Number.MAX_SAFE_INTEGER
+ )}`;
+ setInspectorUrl(url3.toString());
+ }
+ } catch (error) {
+ logger.error("Error attempting to retrieve debugger URL:", error);
+ }
+ });
+ server2.addEventListener("error", ({ error }) => {
+ if (typeof error === "object" && error !== null && "code" in error && error.code === "ERR_RUNTIME_FAILURE") {
+ logger.error(String(error));
+ } else {
+ logger.error("Error reloading local server:", error);
+ }
+ });
+ removeMiniflareServerExitListenerRef.current = (0, import_signal_exit2.default)(() => {
+ logger.log(import_chalk4.default.dim("\u2394 Shutting down local server..."));
+ void newServer.onDispose();
+ miniflareServerRef.current = void 0;
+ });
+ } else {
+ logger.log(import_chalk4.default.dim("\u2394 Reloading local server..."));
+ }
+ const currentServer = server2;
+ void localPropsToConfigBundle(props).then(
+ (config) => currentServer.onBundleUpdate(config, { signal: abortController.signal })
+ );
+ return () => abortController.abort();
+ }, [props]);
+ (0, import_react3.useEffect)(
+ () => () => {
+ if (miniflareServerRef.current) {
+ logger.log(import_chalk4.default.dim("\u2394 Shutting down local server..."));
+ void miniflareServerRef.current.onDispose().catch(() => {
+ });
+ miniflareServerRef.current = void 0;
+ }
+ removeMiniflareServerExitListenerRef.current?.();
+ removeMiniflareServerExitListenerRef.current = void 0;
+ },
+ []
+ );
+ return { inspectorUrl };
+}
+__name(useLocalWorker, "useLocalWorker");
+
+// src/dev/remote.tsx
+init_import_meta_url();
+var import_promises15 = require("node:fs/promises");
+var import_node_path45 = __toESM(require("node:path"));
+var import_url3 = require("url");
+var import_ink10 = __toESM(require_build2());
+var import_ink_select_input3 = __toESM(require_build3());
+var import_react17 = __toESM(require_react());
+
+// src/create-worker-preview.ts
+init_import_meta_url();
+var import_node_url9 = require("node:url");
+var import_undici8 = __toESM(require_undici());
+
+// src/deployment-bundle/create-worker-upload-form.ts
+init_import_meta_url();
+var import_node_fs10 = require("node:fs");
+var import_undici7 = __toESM(require_undici());
+
+// src/deployment-bundle/capnp.ts
+init_import_meta_url();
+var import_node_child_process2 = require("node:child_process");
+var import_node_fs9 = require("node:fs");
+var import_node_path20 = require("node:path");
+var import_command_exists = __toESM(require_command_exists2());
+function handleUnsafeCapnp(capnp) {
+ if (capnp.compiled_schema) {
+ return (0, import_node_fs9.readFileSync)((0, import_node_path20.resolve)(capnp.compiled_schema));
+ }
+ const { base_path, source_schemas } = capnp;
+ const capnpSchemas = (source_schemas ?? []).map(
+ (x) => (0, import_node_path20.resolve)(base_path, x)
+ );
+ if (!(0, import_command_exists.sync)("capnp")) {
+ throw new Error(
+ "The capnp compiler is required to upload capnp schemas, but is not present."
+ );
+ }
+ const srcPrefix = (0, import_node_path20.resolve)(base_path ?? ".");
+ const capnpProcess = (0, import_node_child_process2.spawnSync)("capnp", [
+ "compile",
+ "-o-",
+ `--src-prefix=${srcPrefix}`,
+ ...capnpSchemas
+ ]);
+ if (capnpProcess.error)
+ throw capnpProcess.error;
+ if (capnpProcess.stderr.length)
+ throw new Error(capnpProcess.stderr.toString());
+ return capnpProcess.stdout;
+}
+__name(handleUnsafeCapnp, "handleUnsafeCapnp");
+
+// src/deployment-bundle/create-worker-upload-form.ts
+function toMimeType(type) {
+ switch (type) {
+ case "esm":
+ return "application/javascript+module";
+ case "commonjs":
+ return "application/javascript";
+ case "compiled-wasm":
+ return "application/wasm";
+ case "buffer":
+ return "application/octet-stream";
+ case "text":
+ return "text/plain";
+ default:
+ throw new TypeError("Unsupported module: " + type);
+ }
+}
+__name(toMimeType, "toMimeType");
+function createWorkerUploadForm(worker) {
+ const formData = new import_undici7.FormData();
+ const {
+ main: main2,
+ bindings,
+ migrations,
+ usage_model,
+ compatibility_date,
+ compatibility_flags,
+ keepVars,
+ logpush,
+ placement,
+ tail_consumers
+ } = worker;
+ let { modules } = worker;
+ const metadataBindings = [];
+ Object.entries(bindings.vars || {})?.forEach(([key, value]) => {
+ if (typeof value === "string") {
+ metadataBindings.push({ name: key, type: "plain_text", text: value });
+ } else {
+ metadataBindings.push({ name: key, type: "json", json: value });
+ }
+ });
+ bindings.kv_namespaces?.forEach(({ id, binding }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "kv_namespace",
+ namespace_id: id
+ });
+ });
+ bindings.send_email?.forEach(
+ ({ name, destination_address, allowed_destination_addresses }) => {
+ metadataBindings.push({
+ name,
+ type: "send_email",
+ destination_address,
+ allowed_destination_addresses
+ });
+ }
+ );
+ bindings.durable_objects?.bindings.forEach(
+ ({ name, class_name, script_name, environment }) => {
+ metadataBindings.push({
+ name,
+ type: "durable_object_namespace",
+ class_name,
+ ...script_name && { script_name },
+ ...environment && { environment }
+ });
+ }
+ );
+ bindings.queues?.forEach(({ binding, queue_name }) => {
+ metadataBindings.push({
+ type: "queue",
+ name: binding,
+ queue_name
+ });
+ });
+ bindings.r2_buckets?.forEach(({ binding, bucket_name, jurisdiction }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "r2_bucket",
+ bucket_name,
+ jurisdiction
+ });
+ });
+ bindings.d1_databases?.forEach(
+ ({ binding, database_id, database_internal_env }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "d1",
+ id: database_id,
+ internalEnv: database_internal_env
+ });
+ }
+ );
+ bindings.constellation?.forEach(({ binding, project_id }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "constellation",
+ project: project_id
+ });
+ });
+ bindings.services?.forEach(({ binding, service, environment }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "service",
+ service,
+ ...environment && { environment }
+ });
+ });
+ bindings.analytics_engine_datasets?.forEach(({ binding, dataset }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "analytics_engine",
+ dataset
+ });
+ });
+ bindings.dispatch_namespaces?.forEach(({ binding, namespace, outbound }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "dispatch_namespace",
+ namespace,
+ ...outbound && {
+ outbound: {
+ worker: {
+ service: outbound.service,
+ environment: outbound.environment
+ },
+ params: outbound.parameters?.map((p) => ({ name: p }))
+ }
+ }
+ });
+ });
+ bindings.mtls_certificates?.forEach(({ binding, certificate_id }) => {
+ metadataBindings.push({
+ name: binding,
+ type: "mtls_certificate",
+ certificate_id
+ });
+ });
+ bindings.logfwdr?.bindings.forEach(({ name, destination }) => {
+ metadataBindings.push({
+ name,
+ type: "logfwdr",
+ destination
+ });
+ });
+ for (const [name, filePath] of Object.entries(bindings.wasm_modules || {})) {
+ metadataBindings.push({
+ name,
+ type: "wasm_module",
+ part: name
+ });
+ formData.set(
+ name,
+ new import_undici7.File([(0, import_node_fs10.readFileSync)(filePath)], filePath, {
+ type: "application/wasm"
+ })
+ );
+ }
+ if (bindings.browser !== void 0) {
+ metadataBindings.push({
+ name: bindings.browser.binding,
+ type: "browser"
+ });
+ }
+ for (const [name, filePath] of Object.entries(bindings.text_blobs || {})) {
+ metadataBindings.push({
+ name,
+ type: "text_blob",
+ part: name
+ });
+ if (name !== "__STATIC_CONTENT_MANIFEST") {
+ formData.set(
+ name,
+ new import_undici7.File([(0, import_node_fs10.readFileSync)(filePath)], filePath, {
+ type: "text/plain"
+ })
+ );
+ }
+ }
+ for (const [name, filePath] of Object.entries(bindings.data_blobs || {})) {
+ metadataBindings.push({
+ name,
+ type: "data_blob",
+ part: name
+ });
+ formData.set(
+ name,
+ new import_undici7.File([(0, import_node_fs10.readFileSync)(filePath)], filePath, {
+ type: "application/octet-stream"
+ })
+ );
+ }
+ if (main2.type === "commonjs") {
+ for (const module2 of Object.values([...modules || []])) {
+ if (module2.name === "__STATIC_CONTENT_MANIFEST") {
+ formData.set(
+ module2.name,
+ new import_undici7.File([module2.content], module2.name, {
+ type: "text/plain"
+ })
+ );
+ modules = modules?.filter((m) => m !== module2);
+ } else if (module2.type === "compiled-wasm" || module2.type === "text" || module2.type === "buffer") {
+ const name = module2.name.replace(/[^a-zA-Z0-9_$]/g, "_");
+ metadataBindings.push({
+ name,
+ type: module2.type === "compiled-wasm" ? "wasm_module" : module2.type === "text" ? "text_blob" : "data_blob",
+ part: name
+ });
+ formData.set(
+ name,
+ new import_undici7.File([module2.content], module2.name, {
+ type: module2.type === "compiled-wasm" ? "application/wasm" : module2.type === "text" ? "text/plain" : "application/octet-stream"
+ })
+ );
+ modules = modules?.filter((m) => m !== module2);
+ }
+ }
+ }
+ if (bindings.unsafe?.bindings) {
+ metadataBindings.push(...bindings.unsafe.bindings);
+ }
+ let capnpSchemaOutputFile;
+ if (bindings.unsafe?.capnp) {
+ const capnpOutput = handleUnsafeCapnp(bindings.unsafe.capnp);
+ capnpSchemaOutputFile = `./capnp-${Date.now()}.compiled`;
+ formData.set(
+ capnpSchemaOutputFile,
+ new import_undici7.File([capnpOutput], capnpSchemaOutputFile, {
+ type: "application/octet-stream"
+ })
+ );
+ }
+ const metadata = {
+ ...main2.type !== "commonjs" ? { main_module: main2.name } : { body_part: main2.name },
+ bindings: metadataBindings,
+ ...compatibility_date && { compatibility_date },
+ ...compatibility_flags && { compatibility_flags },
+ ...usage_model && { usage_model },
+ ...migrations && { migrations },
+ capnp_schema: capnpSchemaOutputFile,
+ ...keepVars && { keep_bindings: ["plain_text", "json"] },
+ ...logpush !== void 0 && { logpush },
+ ...placement && { placement },
+ ...tail_consumers && { tail_consumers }
+ };
+ if (bindings.unsafe?.metadata !== void 0) {
+ for (const key of Object.keys(bindings.unsafe.metadata)) {
+ metadata[key] = bindings.unsafe.metadata[key];
+ }
+ }
+ formData.set("metadata", JSON.stringify(metadata));
+ if (main2.type === "commonjs" && modules && modules.length > 0) {
+ throw new TypeError(
+ "More than one module can only be specified when type = 'esm'"
+ );
+ }
+ for (const module2 of [main2].concat(modules || [])) {
+ formData.set(
+ module2.name,
+ new import_undici7.File([module2.content], module2.name, {
+ type: toMimeType(module2.type ?? main2.type ?? "esm")
+ })
+ );
+ }
+ return formData;
+}
+__name(createWorkerUploadForm, "createWorkerUploadForm");
+
+// src/create-worker-preview.ts
+function randomId() {
+ return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function(c) {
+ const r = Math.random() * 16 | 0, v = c == "x" ? r : r & 3 | 8;
+ return v.toString(16);
+ });
+}
+__name(randomId, "randomId");
+function switchHost(originalUrl, host) {
+ const url3 = new import_node_url9.URL(originalUrl);
+ url3.hostname = host ?? url3.hostname;
+ return url3;
+}
+__name(switchHost, "switchHost");
+async function createPreviewSession(account, ctx, abortSignal) {
+ const { accountId } = account;
+ const initUrl = ctx.zone ? `/zones/${ctx.zone}/workers/edge-preview` : `/accounts/${accountId}/workers/subdomain/edge-preview`;
+ const { exchange_url } = await fetchResult(
+ initUrl,
+ void 0,
+ void 0,
+ abortSignal
+ );
+ const switchedExchangeUrl = switchHost(exchange_url, ctx.host).toString();
+ logger.debug(`-- START EXCHANGE API REQUEST: GET ${switchedExchangeUrl}`);
+ logger.debug("-- END EXCHANGE API REQUEST");
+ const exchangeResponse = await (0, import_undici8.fetch)(switchedExchangeUrl, {
+ signal: abortSignal
+ });
+ const bodyText = await exchangeResponse.text();
+ logger.debug(
+ "-- START EXCHANGE API RESPONSE:",
+ exchangeResponse.statusText,
+ exchangeResponse.status
+ );
+ logger.debug("HEADERS:", JSON.stringify(exchangeResponse.headers, null, 2));
+ logger.debug("RESPONSE:", bodyText);
+ logger.debug("-- END EXCHANGE API RESPONSE");
+ const { inspector_websocket, prewarm, token } = parseJSON(bodyText);
+ const inspector = new import_node_url9.URL(inspector_websocket);
+ inspector.searchParams.append("cf_workers_preview_token", token);
+ return {
+ id: randomId(),
+ value: token,
+ host: ctx.host ?? inspector.host,
+ inspectorUrl: switchHost(inspector.href, ctx.host),
+ prewarmUrl: switchHost(prewarm, ctx.host)
+ };
+}
+__name(createPreviewSession, "createPreviewSession");
+async function createPreviewToken(account, worker, ctx, session, abortSignal) {
+ const { value, host, inspectorUrl, prewarmUrl } = session;
+ const { accountId } = account;
+ const scriptId = worker.name || (ctx.zone ? session.id : host.split(".")[0]);
+ const url3 = ctx.env && !ctx.legacyEnv ? `/accounts/${accountId}/workers/services/${scriptId}/environments/${ctx.env}/edge-preview` : `/accounts/${accountId}/workers/scripts/${scriptId}/edge-preview`;
+ const mode = ctx.zone ? {
+ routes: ctx.routes ? (
+ // extract all the route patterns
+ ctx.routes.map((route2) => {
+ if (typeof route2 === "string") {
+ return route2;
+ }
+ if (route2.custom_domain) {
+ return `${route2.pattern}/*`;
+ }
+ return route2.pattern;
+ })
+ ) : (
+ // if there aren't any patterns, then just match on all routes
+ ["*/*"]
+ )
+ } : { workers_dev: true };
+ const formData = createWorkerUploadForm(worker);
+ formData.set("wrangler-session-config", JSON.stringify(mode));
+ const { preview_token } = await fetchResult(
+ url3,
+ {
+ method: "POST",
+ body: formData,
+ headers: {
+ "cf-preview-upload-config-token": value
+ }
+ },
+ void 0,
+ abortSignal
+ );
+ return {
+ value: preview_token,
+ host: ctx.host ?? (worker.name ? `${worker.name}.${host.split(".").slice(1).join(".")}` : host),
+ inspectorUrl,
+ prewarmUrl
+ };
+}
+__name(createPreviewToken, "createPreviewToken");
+async function createWorkerPreview(init, account, ctx, session, abortSignal) {
+ const token = await createPreviewToken(
+ account,
+ init,
+ ctx,
+ session,
+ abortSignal
+ );
+ const accessToken = await getAccessToken(token.prewarmUrl.hostname);
+ const headers = { "cf-workers-preview-token": token.value };
+ if (accessToken) {
+ headers.cookie = `CF_Authorization=${accessToken}`;
+ }
+ (0, import_undici8.fetch)(token.prewarmUrl.href, {
+ method: "POST",
+ signal: abortSignal,
+ headers
+ }).then(
+ (response) => {
+ if (!response.ok) {
+ logger.warn("worker failed to prewarm: ", response.statusText);
+ }
+ },
+ (err) => {
+ if (err.code !== "ABORT_ERR") {
+ logger.warn("worker failed to prewarm: ", err);
+ }
+ }
+ );
+ return token;
+}
+__name(createWorkerPreview, "createWorkerPreview");
+
+// src/deploy/deploy.ts
+init_import_meta_url();
+var import_node_assert14 = __toESM(require("node:assert"));
+var import_node_fs25 = require("node:fs");
+var import_node_path44 = __toESM(require("node:path"));
+var import_node_url11 = require("node:url");
+var import_chalk14 = __toESM(require_chalk());
+var import_tmp_promise2 = __toESM(require_tmp_promise());
+
+// src/deployment-bundle/bundle-reporter.ts
+init_import_meta_url();
+var import_node_buffer2 = require("node:buffer");
+var import_node_zlib = require("node:zlib");
+var import_chalk5 = __toESM(require_chalk());
+var ONE_KIB_BYTES = 1024;
+var ALLOWED_INITIAL_MAX = ONE_KIB_BYTES * 1024;
+async function getSize(modules) {
+ const gzipSize = (0, import_node_zlib.gzipSync)(
+ await new import_node_buffer2.Blob(modules.map((file) => file.content)).arrayBuffer()
+ ).byteLength;
+ const aggregateSize = new import_node_buffer2.Blob(modules.map((file) => file.content)).size;
+ return { size: aggregateSize, gzipSize };
+}
+__name(getSize, "getSize");
+async function printBundleSize(main2, modules) {
+ const { size, gzipSize } = await getSize([...modules, main2]);
+ const bundleReport = `${(size / ONE_KIB_BYTES).toFixed(2)} KiB / gzip: ${(gzipSize / ONE_KIB_BYTES).toFixed(2)} KiB`;
+ const percentage = gzipSize / ALLOWED_INITIAL_MAX * 100;
+ const colorizedReport = percentage > 90 ? import_chalk5.default.red(bundleReport) : percentage > 70 ? import_chalk5.default.yellow(bundleReport) : import_chalk5.default.green(bundleReport);
+ logger.log(`Total Upload: ${colorizedReport}`);
+ if (gzipSize > ALLOWED_INITIAL_MAX && !process.env.NO_SCRIPT_SIZE_WARNING) {
+ logger.warn(
+ "We recommend keeping your script less than 1MiB (1024 KiB) after gzip. Exceeding past this can affect cold start time"
+ );
+ }
+}
+__name(printBundleSize, "printBundleSize");
+function printOffendingDependencies(dependencies) {
+ const warning = [];
+ const dependenciesSorted = Object.entries(dependencies);
+ dependenciesSorted.sort(
+ ([_adep, aData], [_bdep, bData]) => bData.bytesInOutput - aData.bytesInOutput
+ );
+ const topLargest = dependenciesSorted.slice(0, 5);
+ if (topLargest.length > 0) {
+ warning.push(
+ `Here are the ${topLargest.length} largest dependencies included in your script:`
+ );
+ for (const [dep, data] of topLargest) {
+ warning.push(
+ `- ${dep} - ${(data.bytesInOutput / ONE_KIB_BYTES).toFixed(2)} KiB`
+ );
+ }
+ warning.push("If these are unnecessary, consider removing them");
+ logger.warn(warning.join("\n"));
+ }
+}
+__name(printOffendingDependencies, "printOffendingDependencies");
+
+// src/deployment-bundle/traverse-module-graph.ts
+init_import_meta_url();
+var import_promises3 = require("node:fs/promises");
+var import_node_path21 = __toESM(require("node:path"));
+var import_chalk6 = __toESM(require_chalk());
+async function getFiles(root, relativeTo) {
+ const files = [];
+ for (const file of await (0, import_promises3.readdir)(root, { withFileTypes: true })) {
+ if (file.isDirectory()) {
+ files.push(...await getFiles(import_node_path21.default.join(root, file.name), relativeTo));
+ } else {
+ files.push(
+ import_node_path21.default.relative(relativeTo, import_node_path21.default.join(root, file.name)).replaceAll("\\", "/")
+ );
+ }
+ }
+ return files;
+}
+__name(getFiles, "getFiles");
+async function traverseModuleGraph(entry, rules) {
+ const files = await getFiles(entry.moduleRoot, entry.moduleRoot);
+ const relativeEntryPoint = import_node_path21.default.relative(entry.moduleRoot, entry.file).replaceAll("\\", "/");
+ const modules = (await matchFiles(files, entry.moduleRoot, parseRules(rules))).filter((m) => m.name !== relativeEntryPoint).map((m) => ({
+ ...m,
+ name: m.name
+ }));
+ const bundleType = entry.format === "modules" ? "esm" : "commonjs";
+ if (modules.length > 0) {
+ logger.info(`Attaching additional modules:`);
+ modules.forEach(({ name, type }) => {
+ logger.info(`- ${import_chalk6.default.blue(name)} (${import_chalk6.default.green(type ?? "")})`);
+ });
+ }
+ return {
+ modules,
+ dependencies: {},
+ resolvedEntryPointPath: entry.file,
+ bundleType,
+ stop: void 0,
+ sourceMapPath: void 0,
+ sourceMapMetadata: void 0,
+ moduleCollector: void 0
+ };
+}
+__name(traverseModuleGraph, "traverseModuleGraph");
+
+// src/deployments.ts
+init_import_meta_url();
+var import_url2 = require("url");
+var import_toml6 = __toESM(require_toml());
+var import_chalk12 = __toESM(require_chalk());
+var import_undici16 = __toESM(require_undici());
+
+// src/init.ts
+init_import_meta_url();
+var fs17 = __toESM(require("node:fs"));
+var import_promises14 = require("node:fs/promises");
+var import_node_path43 = __toESM(require("node:path"));
+var import_toml5 = __toESM(require_toml());
+
+// src/git-client.ts
+init_import_meta_url();
+var import_node_fs11 = __toESM(require("node:fs"));
+var import_node_os7 = __toESM(require("node:os"));
+var import_node_path22 = __toESM(require("node:path"));
+
+// ../../node_modules/.pnpm/semiver@1.1.0/node_modules/semiver/dist/semiver.mjs
+init_import_meta_url();
+var fn = new Intl.Collator(0, { numeric: 1 }).compare;
+function semiver_default(a, b, bool) {
+ a = a.split(".");
+ b = b.split(".");
+ return fn(a[0], b[0]) || fn(a[1], b[1]) || (b[2] = b.slice(2).join("."), bool = /[.-]/.test(a[2] = a.slice(2).join(".")), bool == /[.-]/.test(b[2]) ? fn(a[2], b[2]) : bool ? -1 : 1);
+}
+__name(semiver_default, "default");
+
+// src/git-client.ts
+async function isInsideGitRepo(cwd2) {
+ const res = await findUp(".git", { cwd: cwd2, type: "directory" });
+ return res !== void 0;
+}
+__name(isInsideGitRepo, "isInsideGitRepo");
+async function getGitVersioon() {
+ try {
+ const gitVersionExecutionResult = await execa("git", ["--version"]);
+ if (gitVersionExecutionResult.exitCode !== 0) {
+ return null;
+ }
+ const [gitVersion] = /\d+.\d+.\d+/.exec(gitVersionExecutionResult.stdout) || [];
+ return gitVersion ?? null;
+ } catch (err) {
+ return null;
+ }
+}
+__name(getGitVersioon, "getGitVersioon");
+async function initializeGit(cwd2) {
+ try {
+ const { stdout: defaultBranchName } = await execa("git", [
+ "config",
+ "--get",
+ "init.defaultBranch"
+ ]);
+ await execa(
+ "git",
+ ["init", "--initial-branch", defaultBranchName.trim() ?? "main"],
+ {
+ cwd: cwd2
+ }
+ );
+ } catch {
+ await execa("git", ["init"], {
+ cwd: cwd2
+ });
+ }
+}
+__name(initializeGit, "initializeGit");
+async function cloneIntoDirectory(remote, targetDirectory, subdirectory) {
+ const args = ["clone", "--depth", "1"];
+ const gitVersion = await getGitVersioon();
+ if (!gitVersion) {
+ throw new Error("Failed to find git installation");
+ }
+ const useSparseCheckout = subdirectory && semiver_default(gitVersion, "2.26.0") > -1;
+ if (useSparseCheckout) {
+ args.push("--filter=blob:none", "--sparse");
+ }
+ const tagIndex = remote.lastIndexOf("#");
+ if (tagIndex === -1) {
+ args.push(remote);
+ } else {
+ args.push("-b", remote.substring(tagIndex + 1));
+ args.push(remote.substring(0, tagIndex));
+ }
+ const tempDir = import_node_fs11.default.mkdtempSync(
+ import_node_path22.default.join(import_node_os7.default.tmpdir(), `wrangler-generate-repo-`)
+ );
+ args.push(tempDir);
+ await execa("git", args);
+ if (useSparseCheckout) {
+ await execa("git", [`sparse-checkout`, `set`, subdirectory], {
+ cwd: tempDir
+ });
+ }
+ const templatePath = subdirectory !== void 0 ? import_node_path22.default.join(tempDir, subdirectory) : tempDir;
+ try {
+ import_node_fs11.default.renameSync(templatePath, targetDirectory);
+ } catch (err) {
+ if (err.code !== "EXDEV") {
+ logger.debug(err);
+ throw new Error(`Failed to find "${subdirectory}" in ${remote}`);
+ }
+ try {
+ import_node_fs11.default.cpSync(templatePath, targetDirectory, { recursive: true });
+ import_node_fs11.default.rmSync(templatePath, {
+ recursive: true,
+ force: true
+ });
+ } catch (moveErr) {
+ logger.debug(moveErr);
+ throw new Error(`Failed to find "${subdirectory}" in ${remote}`);
+ }
+ }
+ import_node_fs11.default.rmSync(import_node_path22.default.join(targetDirectory, ".git"), {
+ recursive: true,
+ force: true
+ });
+}
+__name(cloneIntoDirectory, "cloneIntoDirectory");
+
+// src/package-manager.ts
+init_import_meta_url();
+var import_node_fs12 = require("node:fs");
+var import_node_path23 = require("node:path");
+var import_node_process5 = require("node:process");
+async function getPackageManager(cwd2) {
+ const [hasYarn, hasNpm, hasPnpm] = await Promise.all([
+ supportsYarn(),
+ supportsNpm(),
+ supportsPnpm()
+ ]);
+ const hasYarnLock = (0, import_node_fs12.existsSync)((0, import_node_path23.join)(cwd2, "yarn.lock"));
+ const hasNpmLock = (0, import_node_fs12.existsSync)((0, import_node_path23.join)(cwd2, "package-lock.json"));
+ const hasPnpmLock = (0, import_node_fs12.existsSync)((0, import_node_path23.join)(cwd2, "pnpm-lock.yaml"));
+ const userAgent = sniffUserAgent();
+ if (hasNpmLock) {
+ if (hasNpm) {
+ logger.log(
+ "Using npm as package manager, as there is already a package-lock.json file."
+ );
+ return { ...NpmPackageManager, cwd: cwd2 };
+ } else if (hasYarn) {
+ logger.log("Using yarn as package manager.");
+ logger.warn(
+ "There is already a package-lock.json file but could not find npm on the PATH."
+ );
+ return { ...YarnPackageManager, cwd: cwd2 };
+ }
+ } else if (hasPnpmLock) {
+ if (hasPnpm) {
+ logger.log(
+ "Using pnpm as package manager, as there is already a pnpm-lock.yaml file."
+ );
+ return { ...PnpmPackageManager, cwd: cwd2 };
+ } else {
+ logger.warn(
+ "There is already a pnpm-lock.yaml file but could not find pnpm on the PATH."
+ );
+ }
+ } else if (hasYarnLock) {
+ if (hasYarn) {
+ logger.log(
+ "Using yarn as package manager, as there is already a yarn.lock file."
+ );
+ return { ...YarnPackageManager, cwd: cwd2 };
+ } else if (hasNpm) {
+ logger.log("Using npm as package manager.");
+ logger.warn(
+ "There is already a yarn.lock file but could not find yarn on the PATH."
+ );
+ return { ...NpmPackageManager, cwd: cwd2 };
+ }
+ }
+ if (userAgent === "npm" && hasNpm) {
+ logger.log("Using npm as package manager.");
+ return { ...NpmPackageManager, cwd: cwd2 };
+ } else if (userAgent === "pnpm" && hasPnpm) {
+ logger.log("Using pnpm as package manager.");
+ return { ...PnpmPackageManager, cwd: cwd2 };
+ } else if (userAgent === "yarn" && hasYarn) {
+ logger.log("Using yarn as package manager.");
+ return { ...YarnPackageManager, cwd: cwd2 };
+ }
+ if (hasNpm) {
+ logger.log("Using npm as package manager.");
+ return { ...NpmPackageManager, cwd: cwd2 };
+ } else if (hasYarn) {
+ logger.log("Using yarn as package manager.");
+ return { ...YarnPackageManager, cwd: cwd2 };
+ } else if (hasPnpm) {
+ logger.log("Using pnpm as package manager.");
+ return { ...PnpmPackageManager, cwd: cwd2 };
+ } else {
+ throw new Error(
+ "Unable to find a package manager. Supported managers are: npm, yarn, and pnpm."
+ );
+ }
+}
+__name(getPackageManager, "getPackageManager");
+var NpmPackageManager = {
+ cwd: process.cwd(),
+ type: "npm",
+ /** Add and install a new devDependency into the local package.json. */
+ async addDevDeps(...packages) {
+ await execa("npm", ["install", ...packages, "--save-dev"], {
+ stdio: "inherit",
+ cwd: this.cwd
+ });
+ },
+ /** Install all the dependencies in the local package.json. */
+ async install() {
+ await execa("npm", ["install"], {
+ stdio: "inherit",
+ cwd: this.cwd
+ });
+ }
+};
+var PnpmPackageManager = {
+ cwd: process.cwd(),
+ type: "pnpm",
+ /** Add and install a new devDependency into the local package.json. */
+ async addDevDeps(...packages) {
+ await execa("pnpm", ["install", ...packages, "--save-dev"], {
+ stdio: "inherit",
+ cwd: this.cwd
+ });
+ },
+ /** Install all the dependencies in the local package.json. */
+ async install() {
+ await execa("pnpm", ["install"], {
+ stdio: "inherit",
+ cwd: this.cwd
+ });
+ }
+};
+var YarnPackageManager = {
+ cwd: process.cwd(),
+ type: "yarn",
+ /** Add and install a new devDependency into the local package.json. */
+ async addDevDeps(...packages) {
+ await execa("yarn", ["add", ...packages, "--dev"], {
+ stdio: "inherit",
+ cwd: this.cwd
+ });
+ },
+ /** Install all the dependencies in the local package.json. */
+ async install() {
+ await execa("yarn", ["install"], {
+ stdio: "inherit",
+ cwd: this.cwd
+ });
+ }
+};
+async function supports(name) {
+ try {
+ execaCommandSync(`${name} --version`, { stdio: "ignore" });
+ return true;
+ } catch {
+ return false;
+ }
+}
+__name(supports, "supports");
+function supportsYarn() {
+ return supports("yarn");
+}
+__name(supportsYarn, "supportsYarn");
+function supportsNpm() {
+ return supports("npm");
+}
+__name(supportsNpm, "supportsNpm");
+function supportsPnpm() {
+ return supports("pnpm");
+}
+__name(supportsPnpm, "supportsPnpm");
+function sniffUserAgent() {
+ const userAgent = import_node_process5.env.npm_config_user_agent;
+ if (userAgent === void 0) {
+ return void 0;
+ }
+ if (userAgent.includes("yarn")) {
+ return "yarn";
+ }
+ if (userAgent.includes("pnpm")) {
+ return "pnpm";
+ }
+ if (userAgent.includes("npm")) {
+ return "npm";
+ }
+}
+__name(sniffUserAgent, "sniffUserAgent");
+
+// src/index.ts
+init_import_meta_url();
+var import_node_os13 = __toESM(require("node:os"));
+var import_toml4 = __toESM(require_toml());
+var import_chalk11 = __toESM(require_chalk());
+
+// ../../node_modules/.pnpm/supports-color@9.2.2/node_modules/supports-color/index.js
+init_import_meta_url();
+var import_node_process6 = __toESM(require("node:process"), 1);
+var import_node_os8 = __toESM(require("node:os"), 1);
+var import_node_tty = __toESM(require("node:tty"), 1);
+function hasFlag(flag, argv = import_node_process6.default.argv) {
+ const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
+ const position = argv.indexOf(prefix + flag);
+ const terminatorPosition = argv.indexOf("--");
+ return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
+}
+__name(hasFlag, "hasFlag");
+var { env: env4 } = import_node_process6.default;
+var flagForceColor;
+if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
+ flagForceColor = 0;
+} else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
+ flagForceColor = 1;
+}
+function envForceColor() {
+ if ("FORCE_COLOR" in env4) {
+ if (env4.FORCE_COLOR === "true") {
+ return 1;
+ }
+ if (env4.FORCE_COLOR === "false") {
+ return 0;
+ }
+ return env4.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env4.FORCE_COLOR, 10), 3);
+ }
+}
+__name(envForceColor, "envForceColor");
+function translateLevel(level) {
+ if (level === 0) {
+ return false;
+ }
+ return {
+ level,
+ hasBasic: true,
+ has256: level >= 2,
+ has16m: level >= 3
+ };
+}
+__name(translateLevel, "translateLevel");
+function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
+ const noFlagForceColor = envForceColor();
+ if (noFlagForceColor !== void 0) {
+ flagForceColor = noFlagForceColor;
+ }
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
+ if (forceColor === 0) {
+ return 0;
+ }
+ if (sniffFlags) {
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
+ return 3;
+ }
+ if (hasFlag("color=256")) {
+ return 2;
+ }
+ }
+ if (haveStream && !streamIsTTY && forceColor === void 0) {
+ return 0;
+ }
+ const min = forceColor || 0;
+ if (env4.TERM === "dumb") {
+ return min;
+ }
+ if (import_node_process6.default.platform === "win32") {
+ const osRelease = import_node_os8.default.release().split(".");
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
+ return Number(osRelease[2]) >= 14931 ? 3 : 2;
+ }
+ return 1;
+ }
+ if ("CI" in env4) {
+ if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "GITHUB_ACTIONS", "BUILDKITE", "DRONE"].some((sign) => sign in env4) || env4.CI_NAME === "codeship") {
+ return 1;
+ }
+ return min;
+ }
+ if ("TEAMCITY_VERSION" in env4) {
+ return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env4.TEAMCITY_VERSION) ? 1 : 0;
+ }
+ if ("TF_BUILD" in env4 && "AGENT_NAME" in env4) {
+ return 1;
+ }
+ if (env4.COLORTERM === "truecolor") {
+ return 3;
+ }
+ if ("TERM_PROGRAM" in env4) {
+ const version2 = Number.parseInt((env4.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
+ switch (env4.TERM_PROGRAM) {
+ case "iTerm.app":
+ return version2 >= 3 ? 3 : 2;
+ case "Apple_Terminal":
+ return 2;
+ }
+ }
+ if (/-256(color)?$/i.test(env4.TERM)) {
+ return 2;
+ }
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env4.TERM)) {
+ return 1;
+ }
+ if ("COLORTERM" in env4) {
+ return 1;
+ }
+ return min;
+}
+__name(_supportsColor, "_supportsColor");
+function createSupportsColor(stream2, options14 = {}) {
+ const level = _supportsColor(stream2, {
+ streamIsTTY: stream2 && stream2.isTTY,
+ ...options14
+ });
+ return translateLevel(level);
+}
+__name(createSupportsColor, "createSupportsColor");
+var supportsColor = {
+ stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }),
+ stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) })
+};
+var supports_color_default = supportsColor;
+
+// src/index.ts
+var import_undici15 = __toESM(require_undici());
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/index.mjs
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/yargs-factory.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/command.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/typings/common-types.js
+init_import_meta_url();
+function assertNotStrictEqual(actual, expected, shim3, message) {
+ shim3.assert.notStrictEqual(actual, expected, message);
+}
+__name(assertNotStrictEqual, "assertNotStrictEqual");
+function assertSingleKey(actual, shim3) {
+ shim3.assert.strictEqual(typeof actual, "string");
+}
+__name(assertSingleKey, "assertSingleKey");
+function objectKeys(object) {
+ return Object.keys(object);
+}
+__name(objectKeys, "objectKeys");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/is-promise.js
+init_import_meta_url();
+function isPromise(maybePromise) {
+ return !!maybePromise && !!maybePromise.then && typeof maybePromise.then === "function";
+}
+__name(isPromise, "isPromise");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/middleware.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/argsert.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/parse-command.js
+init_import_meta_url();
+function parseCommand2(cmd) {
+ const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, " ");
+ const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
+ const bregex = /\.*[\][<>]/g;
+ const firstCommand = splitCommand.shift();
+ if (!firstCommand)
+ throw new Error(`No command found in: ${cmd}`);
+ const parsedCommand = {
+ cmd: firstCommand.replace(bregex, ""),
+ demanded: [],
+ optional: []
+ };
+ splitCommand.forEach((cmd2, i) => {
+ let variadic = false;
+ cmd2 = cmd2.replace(/\s/g, "");
+ if (/\.+[\]>]/.test(cmd2) && i === splitCommand.length - 1)
+ variadic = true;
+ if (/^\[/.test(cmd2)) {
+ parsedCommand.optional.push({
+ cmd: cmd2.replace(bregex, "").split("|"),
+ variadic
+ });
+ } else {
+ parsedCommand.demanded.push({
+ cmd: cmd2.replace(bregex, "").split("|"),
+ variadic
+ });
+ }
+ });
+ return parsedCommand;
+}
+__name(parseCommand2, "parseCommand");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/argsert.js
+var positionName = ["first", "second", "third", "fourth", "fifth", "sixth"];
+function argsert(arg1, arg2, arg3) {
+ function parseArgs() {
+ return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
+ parseCommand2(`cmd ${arg1}`),
+ arg2,
+ arg3
+ ];
+ }
+ __name(parseArgs, "parseArgs");
+ try {
+ let position = 0;
+ const [parsed, callerArguments, _length] = parseArgs();
+ const args = [].slice.call(callerArguments);
+ while (args.length && args[args.length - 1] === void 0)
+ args.pop();
+ const length = _length || args.length;
+ if (length < parsed.demanded.length) {
+ throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
+ }
+ const totalCommands = parsed.demanded.length + parsed.optional.length;
+ if (length > totalCommands) {
+ throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
+ }
+ parsed.demanded.forEach((demanded) => {
+ const arg = args.shift();
+ const observedType = guessType(arg);
+ const matchingTypes = demanded.cmd.filter((type) => type === observedType || type === "*");
+ if (matchingTypes.length === 0)
+ argumentTypeError(observedType, demanded.cmd, position);
+ position += 1;
+ });
+ parsed.optional.forEach((optional) => {
+ if (args.length === 0)
+ return;
+ const arg = args.shift();
+ const observedType = guessType(arg);
+ const matchingTypes = optional.cmd.filter((type) => type === observedType || type === "*");
+ if (matchingTypes.length === 0)
+ argumentTypeError(observedType, optional.cmd, position);
+ position += 1;
+ });
+ } catch (err) {
+ console.warn(err.stack);
+ }
+}
+__name(argsert, "argsert");
+function guessType(arg) {
+ if (Array.isArray(arg)) {
+ return "array";
+ } else if (arg === null) {
+ return "null";
+ }
+ return typeof arg;
+}
+__name(guessType, "guessType");
+function argumentTypeError(observedType, allowedTypes, position) {
+ throw new YError(`Invalid ${positionName[position] || "manyith"} argument. Expected ${allowedTypes.join(" or ")} but received ${observedType}.`);
+}
+__name(argumentTypeError, "argumentTypeError");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/middleware.js
+var GlobalMiddleware = class {
+ constructor(yargs) {
+ this.globalMiddleware = [];
+ this.frozens = [];
+ this.yargs = yargs;
+ }
+ addMiddleware(callback, applyBeforeValidation, global2 = true, mutates = false) {
+ argsert(" [boolean] [boolean] [boolean]", [callback, applyBeforeValidation, global2], arguments.length);
+ if (Array.isArray(callback)) {
+ for (let i = 0; i < callback.length; i++) {
+ if (typeof callback[i] !== "function") {
+ throw Error("middleware must be a function");
+ }
+ const m = callback[i];
+ m.applyBeforeValidation = applyBeforeValidation;
+ m.global = global2;
+ }
+ Array.prototype.push.apply(this.globalMiddleware, callback);
+ } else if (typeof callback === "function") {
+ const m = callback;
+ m.applyBeforeValidation = applyBeforeValidation;
+ m.global = global2;
+ m.mutates = mutates;
+ this.globalMiddleware.push(callback);
+ }
+ return this.yargs;
+ }
+ addCoerceMiddleware(callback, option) {
+ const aliases2 = this.yargs.getAliases();
+ this.globalMiddleware = this.globalMiddleware.filter((m) => {
+ const toCheck = [...aliases2[option] || [], option];
+ if (!m.option)
+ return true;
+ else
+ return !toCheck.includes(m.option);
+ });
+ callback.option = option;
+ return this.addMiddleware(callback, true, true, true);
+ }
+ getMiddleware() {
+ return this.globalMiddleware;
+ }
+ freeze() {
+ this.frozens.push([...this.globalMiddleware]);
+ }
+ unfreeze() {
+ const frozen = this.frozens.pop();
+ if (frozen !== void 0)
+ this.globalMiddleware = frozen;
+ }
+ reset() {
+ this.globalMiddleware = this.globalMiddleware.filter((m) => m.global);
+ }
+};
+__name(GlobalMiddleware, "GlobalMiddleware");
+function commandMiddlewareFactory(commandMiddleware) {
+ if (!commandMiddleware)
+ return [];
+ return commandMiddleware.map((middleware) => {
+ middleware.applyBeforeValidation = false;
+ return middleware;
+ });
+}
+__name(commandMiddlewareFactory, "commandMiddlewareFactory");
+function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
+ return middlewares.reduce((acc, middleware) => {
+ if (middleware.applyBeforeValidation !== beforeValidation) {
+ return acc;
+ }
+ if (middleware.mutates) {
+ if (middleware.applied)
+ return acc;
+ middleware.applied = true;
+ }
+ if (isPromise(acc)) {
+ return acc.then((initialObj) => Promise.all([initialObj, middleware(initialObj, yargs)])).then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
+ } else {
+ const result = middleware(acc, yargs);
+ return isPromise(result) ? result.then((middlewareObj) => Object.assign(acc, middlewareObj)) : Object.assign(acc, result);
+ }
+ }, argv);
+}
+__name(applyMiddleware, "applyMiddleware");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/maybe-async-result.js
+init_import_meta_url();
+function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
+ throw err;
+}) {
+ try {
+ const result = isFunction(getResult) ? getResult() : getResult;
+ return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
+ } catch (err) {
+ return errorHandler(err);
+ }
+}
+__name(maybeAsyncResult, "maybeAsyncResult");
+function isFunction(arg) {
+ return typeof arg === "function";
+}
+__name(isFunction, "isFunction");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/which-module.js
+init_import_meta_url();
+function whichModule(exported) {
+ if (typeof require === "undefined")
+ return null;
+ for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) {
+ mod = require.cache[files[i]];
+ if (mod.exports === exported)
+ return mod;
+ }
+ return null;
+}
+__name(whichModule, "whichModule");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/command.js
+var DEFAULT_MARKER = /(^\*)|(^\$0)/;
+var CommandInstance = class {
+ constructor(usage2, validation2, globalMiddleware, shim3) {
+ this.requireCache = /* @__PURE__ */ new Set();
+ this.handlers = {};
+ this.aliasMap = {};
+ this.frozens = [];
+ this.shim = shim3;
+ this.usage = usage2;
+ this.globalMiddleware = globalMiddleware;
+ this.validation = validation2;
+ }
+ addDirectory(dir, req, callerFile, opts) {
+ opts = opts || {};
+ if (typeof opts.recurse !== "boolean")
+ opts.recurse = false;
+ if (!Array.isArray(opts.extensions))
+ opts.extensions = ["js"];
+ const parentVisit = typeof opts.visit === "function" ? opts.visit : (o) => o;
+ opts.visit = (obj, joined, filename) => {
+ const visited = parentVisit(obj, joined, filename);
+ if (visited) {
+ if (this.requireCache.has(joined))
+ return visited;
+ else
+ this.requireCache.add(joined);
+ this.addHandler(visited);
+ }
+ return visited;
+ };
+ this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
+ }
+ addHandler(cmd, description, builder, handler15, commandMiddleware, deprecated2) {
+ let aliases2 = [];
+ const middlewares = commandMiddlewareFactory(commandMiddleware);
+ handler15 = handler15 || (() => {
+ });
+ if (Array.isArray(cmd)) {
+ if (isCommandAndAliases(cmd)) {
+ [cmd, ...aliases2] = cmd;
+ } else {
+ for (const command2 of cmd) {
+ this.addHandler(command2);
+ }
+ }
+ } else if (isCommandHandlerDefinition(cmd)) {
+ let command2 = Array.isArray(cmd.command) || typeof cmd.command === "string" ? cmd.command : this.moduleName(cmd);
+ if (cmd.aliases)
+ command2 = [].concat(command2).concat(cmd.aliases);
+ this.addHandler(command2, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
+ return;
+ } else if (isCommandBuilderDefinition(builder)) {
+ this.addHandler([cmd].concat(aliases2), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
+ return;
+ }
+ if (typeof cmd === "string") {
+ const parsedCommand = parseCommand2(cmd);
+ aliases2 = aliases2.map((alias) => parseCommand2(alias).cmd);
+ let isDefault = false;
+ const parsedAliases = [parsedCommand.cmd].concat(aliases2).filter((c) => {
+ if (DEFAULT_MARKER.test(c)) {
+ isDefault = true;
+ return false;
+ }
+ return true;
+ });
+ if (parsedAliases.length === 0 && isDefault)
+ parsedAliases.push("$0");
+ if (isDefault) {
+ parsedCommand.cmd = parsedAliases[0];
+ aliases2 = parsedAliases.slice(1);
+ cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
+ }
+ aliases2.forEach((alias) => {
+ this.aliasMap[alias] = parsedCommand.cmd;
+ });
+ if (description !== false) {
+ this.usage.command(cmd, description, isDefault, aliases2, deprecated2);
+ }
+ this.handlers[parsedCommand.cmd] = {
+ original: cmd,
+ description,
+ handler: handler15,
+ builder: builder || {},
+ middlewares,
+ deprecated: deprecated2,
+ demanded: parsedCommand.demanded,
+ optional: parsedCommand.optional
+ };
+ if (isDefault)
+ this.defaultCommand = this.handlers[parsedCommand.cmd];
+ }
+ }
+ getCommandHandlers() {
+ return this.handlers;
+ }
+ getCommands() {
+ return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
+ }
+ hasDefaultCommand() {
+ return !!this.defaultCommand;
+ }
+ runCommand(command2, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
+ const commandHandler = this.handlers[command2] || this.handlers[this.aliasMap[command2]] || this.defaultCommand;
+ const currentContext = yargs.getInternalMethods().getContext();
+ const parentCommands = currentContext.commands.slice();
+ const isDefaultCommand = !command2;
+ if (command2) {
+ currentContext.commands.push(command2);
+ currentContext.fullCommands.push(commandHandler.original);
+ }
+ const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
+ return isPromise(builderResult) ? builderResult.then((result) => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
+ }
+ applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases2, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
+ const builder = commandHandler.builder;
+ let innerYargs = yargs;
+ if (isCommandBuilderCallback(builder)) {
+ yargs.getInternalMethods().getUsageInstance().freeze();
+ const builderOutput = builder(yargs.getInternalMethods().reset(aliases2), helpOrVersionSet);
+ if (isPromise(builderOutput)) {
+ return builderOutput.then((output) => {
+ innerYargs = isYargsInstance(output) ? output : yargs;
+ return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
+ });
+ }
+ } else if (isCommandBuilderOptionDefinitions(builder)) {
+ yargs.getInternalMethods().getUsageInstance().freeze();
+ innerYargs = yargs.getInternalMethods().reset(aliases2);
+ Object.keys(commandHandler.builder).forEach((key) => {
+ innerYargs.option(key, builder[key]);
+ });
+ }
+ return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
+ }
+ parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
+ if (isDefaultCommand)
+ innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
+ if (this.shouldUpdateUsage(innerYargs)) {
+ innerYargs.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
+ }
+ const innerArgv = innerYargs.getInternalMethods().runYargsParserAndExecuteCommands(null, void 0, true, commandIndex, helpOnly);
+ return isPromise(innerArgv) ? innerArgv.then((argv) => ({
+ aliases: innerYargs.parsed.aliases,
+ innerArgv: argv
+ })) : {
+ aliases: innerYargs.parsed.aliases,
+ innerArgv
+ };
+ }
+ shouldUpdateUsage(yargs) {
+ return !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && yargs.getInternalMethods().getUsageInstance().getUsage().length === 0;
+ }
+ usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
+ const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
+ const pc = parentCommands.filter((c2) => {
+ return !DEFAULT_MARKER.test(c2);
+ });
+ pc.push(c);
+ return `$0 ${pc.join(" ")}`;
+ }
+ handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases2, yargs, middlewares, positionalMap) {
+ if (!yargs.getInternalMethods().getHasOutput()) {
+ const validation2 = yargs.getInternalMethods().runValidation(aliases2, positionalMap, yargs.parsed.error, isDefaultCommand);
+ innerArgv = maybeAsyncResult(innerArgv, (result) => {
+ validation2(result);
+ return result;
+ });
+ }
+ if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
+ yargs.getInternalMethods().setHasOutput();
+ const populateDoubleDash = !!yargs.getOptions().configuration["populate--"];
+ yargs.getInternalMethods().postProcess(innerArgv, populateDoubleDash, false, false);
+ innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
+ innerArgv = maybeAsyncResult(innerArgv, (result) => {
+ const handlerResult = commandHandler.handler(result);
+ return isPromise(handlerResult) ? handlerResult.then(() => result) : result;
+ });
+ if (!isDefaultCommand) {
+ yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
+ }
+ if (isPromise(innerArgv) && !yargs.getInternalMethods().hasParseCallback()) {
+ innerArgv.catch((error) => {
+ try {
+ yargs.getInternalMethods().getUsageInstance().fail(null, error);
+ } catch (_err) {
+ }
+ });
+ }
+ }
+ if (!isDefaultCommand) {
+ currentContext.commands.pop();
+ currentContext.fullCommands.pop();
+ }
+ return innerArgv;
+ }
+ applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases2, yargs) {
+ let positionalMap = {};
+ if (helpOnly)
+ return innerArgv;
+ if (!yargs.getInternalMethods().getHasOutput()) {
+ positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
+ }
+ const middlewares = this.globalMiddleware.getMiddleware().slice(0).concat(commandHandler.middlewares);
+ const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
+ return isPromise(maybePromiseArgv) ? maybePromiseArgv.then((resolvedInnerArgv) => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases2, yargs, middlewares, positionalMap)) : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases2, yargs, middlewares, positionalMap);
+ }
+ populatePositionals(commandHandler, argv, context2, yargs) {
+ argv._ = argv._.slice(context2.commands.length);
+ const demanded = commandHandler.demanded.slice(0);
+ const optional = commandHandler.optional.slice(0);
+ const positionalMap = {};
+ this.validation.positionalCount(demanded.length, argv._.length);
+ while (demanded.length) {
+ const demand = demanded.shift();
+ this.populatePositional(demand, argv, positionalMap);
+ }
+ while (optional.length) {
+ const maybe = optional.shift();
+ this.populatePositional(maybe, argv, positionalMap);
+ }
+ argv._ = context2.commands.concat(argv._.map((a) => "" + a));
+ this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
+ return positionalMap;
+ }
+ populatePositional(positional, argv, positionalMap) {
+ const cmd = positional.cmd[0];
+ if (positional.variadic) {
+ positionalMap[cmd] = argv._.splice(0).map(String);
+ } else {
+ if (argv._.length)
+ positionalMap[cmd] = [String(argv._.shift())];
+ }
+ }
+ cmdToParseOptions(cmdString) {
+ const parseOptions = {
+ array: [],
+ default: {},
+ alias: {},
+ demand: {}
+ };
+ const parsed = parseCommand2(cmdString);
+ parsed.demanded.forEach((d) => {
+ const [cmd, ...aliases2] = d.cmd;
+ if (d.variadic) {
+ parseOptions.array.push(cmd);
+ parseOptions.default[cmd] = [];
+ }
+ parseOptions.alias[cmd] = aliases2;
+ parseOptions.demand[cmd] = true;
+ });
+ parsed.optional.forEach((o) => {
+ const [cmd, ...aliases2] = o.cmd;
+ if (o.variadic) {
+ parseOptions.array.push(cmd);
+ parseOptions.default[cmd] = [];
+ }
+ parseOptions.alias[cmd] = aliases2;
+ });
+ return parseOptions;
+ }
+ postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
+ const options14 = Object.assign({}, yargs.getOptions());
+ options14.default = Object.assign(parseOptions.default, options14.default);
+ for (const key of Object.keys(parseOptions.alias)) {
+ options14.alias[key] = (options14.alias[key] || []).concat(parseOptions.alias[key]);
+ }
+ options14.array = options14.array.concat(parseOptions.array);
+ options14.config = {};
+ const unparsed = [];
+ Object.keys(positionalMap).forEach((key) => {
+ positionalMap[key].map((value) => {
+ if (options14.configuration["unknown-options-as-args"])
+ options14.key[key] = true;
+ unparsed.push(`--${key}`);
+ unparsed.push(value);
+ });
+ });
+ if (!unparsed.length)
+ return;
+ const config = Object.assign({}, options14.configuration, {
+ "populate--": false
+ });
+ const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options14, {
+ configuration: config
+ }));
+ if (parsed.error) {
+ yargs.getInternalMethods().getUsageInstance().fail(parsed.error.message, parsed.error);
+ } else {
+ const positionalKeys = Object.keys(positionalMap);
+ Object.keys(positionalMap).forEach((key) => {
+ positionalKeys.push(...parsed.aliases[key]);
+ });
+ Object.keys(parsed.argv).forEach((key) => {
+ if (positionalKeys.includes(key)) {
+ if (!positionalMap[key])
+ positionalMap[key] = parsed.argv[key];
+ if (!this.isInConfigs(yargs, key) && !this.isDefaulted(yargs, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
+ argv[key] = [].concat(argv[key], parsed.argv[key]);
+ } else {
+ argv[key] = parsed.argv[key];
+ }
+ }
+ });
+ }
+ }
+ isDefaulted(yargs, key) {
+ const { default: defaults } = yargs.getOptions();
+ return Object.prototype.hasOwnProperty.call(defaults, key) || Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key));
+ }
+ isInConfigs(yargs, key) {
+ const { configObjects } = yargs.getOptions();
+ return configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, key)) || configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)));
+ }
+ runDefaultBuilderOn(yargs) {
+ if (!this.defaultCommand)
+ return;
+ if (this.shouldUpdateUsage(yargs)) {
+ const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) ? this.defaultCommand.original : this.defaultCommand.original.replace(/^[^[\]<>]*/, "$0 ");
+ yargs.getInternalMethods().getUsageInstance().usage(commandString, this.defaultCommand.description);
+ }
+ const builder = this.defaultCommand.builder;
+ if (isCommandBuilderCallback(builder)) {
+ return builder(yargs, true);
+ } else if (!isCommandBuilderDefinition(builder)) {
+ Object.keys(builder).forEach((key) => {
+ yargs.option(key, builder[key]);
+ });
+ }
+ return void 0;
+ }
+ moduleName(obj) {
+ const mod = whichModule(obj);
+ if (!mod)
+ throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
+ return this.commandFromFilename(mod.filename);
+ }
+ commandFromFilename(filename) {
+ return this.shim.path.basename(filename, this.shim.path.extname(filename));
+ }
+ extractDesc({ describe, description, desc }) {
+ for (const test of [describe, description, desc]) {
+ if (typeof test === "string" || test === false)
+ return test;
+ assertNotStrictEqual(test, true, this.shim);
+ }
+ return false;
+ }
+ freeze() {
+ this.frozens.push({
+ handlers: this.handlers,
+ aliasMap: this.aliasMap,
+ defaultCommand: this.defaultCommand
+ });
+ }
+ unfreeze() {
+ const frozen = this.frozens.pop();
+ assertNotStrictEqual(frozen, void 0, this.shim);
+ ({
+ handlers: this.handlers,
+ aliasMap: this.aliasMap,
+ defaultCommand: this.defaultCommand
+ } = frozen);
+ }
+ reset() {
+ this.handlers = {};
+ this.aliasMap = {};
+ this.defaultCommand = void 0;
+ this.requireCache = /* @__PURE__ */ new Set();
+ return this;
+ }
+};
+__name(CommandInstance, "CommandInstance");
+function command(usage2, validation2, globalMiddleware, shim3) {
+ return new CommandInstance(usage2, validation2, globalMiddleware, shim3);
+}
+__name(command, "command");
+function isCommandBuilderDefinition(builder) {
+ return typeof builder === "object" && !!builder.builder && typeof builder.handler === "function";
+}
+__name(isCommandBuilderDefinition, "isCommandBuilderDefinition");
+function isCommandAndAliases(cmd) {
+ return cmd.every((c) => typeof c === "string");
+}
+__name(isCommandAndAliases, "isCommandAndAliases");
+function isCommandBuilderCallback(builder) {
+ return typeof builder === "function";
+}
+__name(isCommandBuilderCallback, "isCommandBuilderCallback");
+function isCommandBuilderOptionDefinitions(builder) {
+ return typeof builder === "object";
+}
+__name(isCommandBuilderOptionDefinitions, "isCommandBuilderOptionDefinitions");
+function isCommandHandlerDefinition(cmd) {
+ return typeof cmd === "object" && !Array.isArray(cmd);
+}
+__name(isCommandHandlerDefinition, "isCommandHandlerDefinition");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/usage.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/obj-filter.js
+init_import_meta_url();
+function objFilter(original = {}, filter = () => true) {
+ const obj = {};
+ objectKeys(original).forEach((key) => {
+ if (filter(key, original[key])) {
+ obj[key] = original[key];
+ }
+ });
+ return obj;
+}
+__name(objFilter, "objFilter");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/set-blocking.js
+init_import_meta_url();
+function setBlocking(blocking) {
+ if (typeof process === "undefined")
+ return;
+ [process.stdout, process.stderr].forEach((_stream) => {
+ const stream2 = _stream;
+ if (stream2._handle && stream2.isTTY && typeof stream2._handle.setBlocking === "function") {
+ stream2._handle.setBlocking(blocking);
+ }
+ });
+}
+__name(setBlocking, "setBlocking");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/usage.js
+function isBoolean2(fail) {
+ return typeof fail === "boolean";
+}
+__name(isBoolean2, "isBoolean");
+function usage(yargs, shim3) {
+ const __ = shim3.y18n.__;
+ const self2 = {};
+ const fails = [];
+ self2.failFn = /* @__PURE__ */ __name(function failFn(f) {
+ fails.push(f);
+ }, "failFn");
+ let failMessage = null;
+ let globalFailMessage = null;
+ let showHelpOnFail = true;
+ self2.showHelpOnFail = /* @__PURE__ */ __name(function showHelpOnFailFn(arg1 = true, arg2) {
+ const [enabled, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
+ if (yargs.getInternalMethods().isGlobalContext()) {
+ globalFailMessage = message;
+ }
+ failMessage = message;
+ showHelpOnFail = enabled;
+ return self2;
+ }, "showHelpOnFailFn");
+ let failureOutput = false;
+ self2.fail = /* @__PURE__ */ __name(function fail(msg, err) {
+ const logger2 = yargs.getInternalMethods().getLoggerInstance();
+ if (fails.length) {
+ for (let i = fails.length - 1; i >= 0; --i) {
+ const fail2 = fails[i];
+ if (isBoolean2(fail2)) {
+ if (err)
+ throw err;
+ else if (msg)
+ throw Error(msg);
+ } else {
+ fail2(msg, err, self2);
+ }
+ }
+ } else {
+ if (yargs.getExitProcess())
+ setBlocking(true);
+ if (!failureOutput) {
+ failureOutput = true;
+ if (showHelpOnFail) {
+ yargs.showHelp("error");
+ logger2.error();
+ }
+ if (msg || err)
+ logger2.error(msg || err);
+ const globalOrCommandFailMessage = failMessage || globalFailMessage;
+ if (globalOrCommandFailMessage) {
+ if (msg || err)
+ logger2.error("");
+ logger2.error(globalOrCommandFailMessage);
+ }
+ }
+ err = err || new YError(msg);
+ if (yargs.getExitProcess()) {
+ return yargs.exit(1);
+ } else if (yargs.getInternalMethods().hasParseCallback()) {
+ return yargs.exit(1, err);
+ } else {
+ throw err;
+ }
+ }
+ }, "fail");
+ let usages = [];
+ let usageDisabled = false;
+ self2.usage = (msg, description) => {
+ if (msg === null) {
+ usageDisabled = true;
+ usages = [];
+ return self2;
+ }
+ usageDisabled = false;
+ usages.push([msg, description || ""]);
+ return self2;
+ };
+ self2.getUsage = () => {
+ return usages;
+ };
+ self2.getUsageDisabled = () => {
+ return usageDisabled;
+ };
+ self2.getPositionalGroupName = () => {
+ return __("Positionals:");
+ };
+ let examples = [];
+ self2.example = (cmd, description) => {
+ examples.push([cmd, description || ""]);
+ };
+ let commands = [];
+ self2.command = /* @__PURE__ */ __name(function command2(cmd, description, isDefault, aliases2, deprecated2 = false) {
+ if (isDefault) {
+ commands = commands.map((cmdArray) => {
+ cmdArray[2] = false;
+ return cmdArray;
+ });
+ }
+ commands.push([cmd, description || "", isDefault, aliases2, deprecated2]);
+ }, "command");
+ self2.getCommands = () => commands;
+ let descriptions = {};
+ self2.describe = /* @__PURE__ */ __name(function describe(keyOrKeys, desc) {
+ if (Array.isArray(keyOrKeys)) {
+ keyOrKeys.forEach((k) => {
+ self2.describe(k, desc);
+ });
+ } else if (typeof keyOrKeys === "object") {
+ Object.keys(keyOrKeys).forEach((k) => {
+ self2.describe(k, keyOrKeys[k]);
+ });
+ } else {
+ descriptions[keyOrKeys] = desc;
+ }
+ }, "describe");
+ self2.getDescriptions = () => descriptions;
+ let epilogs = [];
+ self2.epilog = (msg) => {
+ epilogs.push(msg);
+ };
+ let wrapSet = false;
+ let wrap2;
+ self2.wrap = (cols) => {
+ wrapSet = true;
+ wrap2 = cols;
+ };
+ self2.getWrap = () => {
+ if (shim3.getEnv("YARGS_DISABLE_WRAP")) {
+ return null;
+ }
+ if (!wrapSet) {
+ wrap2 = windowWidth();
+ wrapSet = true;
+ }
+ return wrap2;
+ };
+ const deferY18nLookupPrefix = "__yargsString__:";
+ self2.deferY18nLookup = (str) => deferY18nLookupPrefix + str;
+ self2.help = /* @__PURE__ */ __name(function help() {
+ if (cachedHelpMessage)
+ return cachedHelpMessage;
+ normalizeAliases();
+ const base$0 = yargs.customScriptName ? yargs.$0 : shim3.path.basename(yargs.$0);
+ const demandedOptions = yargs.getDemandedOptions();
+ const demandedCommands = yargs.getDemandedCommands();
+ const deprecatedOptions = yargs.getDeprecatedOptions();
+ const groups = yargs.getGroups();
+ const options14 = yargs.getOptions();
+ let keys = [];
+ keys = keys.concat(Object.keys(descriptions));
+ keys = keys.concat(Object.keys(demandedOptions));
+ keys = keys.concat(Object.keys(demandedCommands));
+ keys = keys.concat(Object.keys(options14.default));
+ keys = keys.filter(filterHiddenOptions);
+ keys = Object.keys(keys.reduce((acc, key) => {
+ if (key !== "_")
+ acc[key] = true;
+ return acc;
+ }, {}));
+ const theWrap = self2.getWrap();
+ const ui2 = shim3.cliui({
+ width: theWrap,
+ wrap: !!theWrap
+ });
+ if (!usageDisabled) {
+ if (usages.length) {
+ usages.forEach((usage2) => {
+ ui2.div({ text: `${usage2[0].replace(/\$0/g, base$0)}` });
+ if (usage2[1]) {
+ ui2.div({ text: `${usage2[1]}`, padding: [1, 0, 0, 0] });
+ }
+ });
+ ui2.div();
+ } else if (commands.length) {
+ let u = null;
+ if (demandedCommands._) {
+ u = `${base$0} <${__("command")}>
+`;
+ } else {
+ u = `${base$0} [${__("command")}]
+`;
+ }
+ ui2.div(`${u}`);
+ }
+ }
+ if (commands.length > 1 || commands.length === 1 && !commands[0][2]) {
+ ui2.div(__("Commands:"));
+ const context2 = yargs.getInternalMethods().getContext();
+ const parentCommands = context2.commands.length ? `${context2.commands.join(" ")} ` : "";
+ if (yargs.getInternalMethods().getParserConfiguration()["sort-commands"] === true) {
+ commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
+ }
+ const prefix = base$0 ? `${base$0} ` : "";
+ commands.forEach((command2) => {
+ const commandString = `${prefix}${parentCommands}${command2[0].replace(/^\$0 ?/, "")}`;
+ ui2.span({
+ text: commandString,
+ padding: [0, 2, 0, 2],
+ width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
+ }, { text: command2[1] });
+ const hints = [];
+ if (command2[2])
+ hints.push(`[${__("default")}]`);
+ if (command2[3] && command2[3].length) {
+ hints.push(`[${__("aliases:")} ${command2[3].join(", ")}]`);
+ }
+ if (command2[4]) {
+ if (typeof command2[4] === "string") {
+ hints.push(`[${__("deprecated: %s", command2[4])}]`);
+ } else {
+ hints.push(`[${__("deprecated")}]`);
+ }
+ }
+ if (hints.length) {
+ ui2.div({
+ text: hints.join(" "),
+ padding: [0, 0, 0, 2],
+ align: "right"
+ });
+ } else {
+ ui2.div();
+ }
+ });
+ ui2.div();
+ }
+ const aliasKeys = (Object.keys(options14.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
+ keys = keys.filter((key) => !yargs.parsed.newAliases[key] && aliasKeys.every((alias) => (options14.alias[alias] || []).indexOf(key) === -1));
+ const defaultGroup = __("Options:");
+ if (!groups[defaultGroup])
+ groups[defaultGroup] = [];
+ addUngroupedKeys(keys, options14.alias, groups, defaultGroup);
+ const isLongSwitch = /* @__PURE__ */ __name((sw) => /^--/.test(getText(sw)), "isLongSwitch");
+ const displayedGroups = Object.keys(groups).filter((groupName) => groups[groupName].length > 0).map((groupName) => {
+ const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
+ if (aliasKeys.includes(key))
+ return key;
+ for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== void 0; i++) {
+ if ((options14.alias[aliasKey] || []).includes(key))
+ return aliasKey;
+ }
+ return key;
+ });
+ return { groupName, normalizedKeys };
+ }).filter(({ normalizedKeys }) => normalizedKeys.length > 0).map(({ groupName, normalizedKeys }) => {
+ const switches = normalizedKeys.reduce((acc, key) => {
+ acc[key] = [key].concat(options14.alias[key] || []).map((sw) => {
+ if (groupName === self2.getPositionalGroupName())
+ return sw;
+ else {
+ return (/^[0-9]$/.test(sw) ? options14.boolean.includes(key) ? "-" : "--" : sw.length > 1 ? "--" : "-") + sw;
+ }
+ }).sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) ? 0 : isLongSwitch(sw1) ? 1 : -1).join(", ");
+ return acc;
+ }, {});
+ return { groupName, normalizedKeys, switches };
+ });
+ const shortSwitchesUsed = displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).some(({ normalizedKeys, switches }) => !normalizedKeys.every((key) => isLongSwitch(switches[key])));
+ if (shortSwitchesUsed) {
+ displayedGroups.filter(({ groupName }) => groupName !== self2.getPositionalGroupName()).forEach(({ normalizedKeys, switches }) => {
+ normalizedKeys.forEach((key) => {
+ if (isLongSwitch(switches[key])) {
+ switches[key] = addIndentation(switches[key], "-x, ".length);
+ }
+ });
+ });
+ }
+ displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
+ ui2.div(groupName);
+ normalizedKeys.forEach((key) => {
+ const kswitch = switches[key];
+ let desc = descriptions[key] || "";
+ let type = null;
+ if (desc.includes(deferY18nLookupPrefix))
+ desc = __(desc.substring(deferY18nLookupPrefix.length));
+ if (options14.boolean.includes(key))
+ type = `[${__("boolean")}]`;
+ if (options14.count.includes(key))
+ type = `[${__("count")}]`;
+ if (options14.string.includes(key))
+ type = `[${__("string")}]`;
+ if (options14.normalize.includes(key))
+ type = `[${__("string")}]`;
+ if (options14.array.includes(key))
+ type = `[${__("array")}]`;
+ if (options14.number.includes(key))
+ type = `[${__("number")}]`;
+ const deprecatedExtra = /* @__PURE__ */ __name((deprecated2) => typeof deprecated2 === "string" ? `[${__("deprecated: %s", deprecated2)}]` : `[${__("deprecated")}]`, "deprecatedExtra");
+ const extra = [
+ key in deprecatedOptions ? deprecatedExtra(deprecatedOptions[key]) : null,
+ type,
+ key in demandedOptions ? `[${__("required")}]` : null,
+ options14.choices && options14.choices[key] ? `[${__("choices:")} ${self2.stringifiedValues(options14.choices[key])}]` : null,
+ defaultString(options14.default[key], options14.defaultDescription[key])
+ ].filter(Boolean).join(" ");
+ ui2.span({
+ text: getText(kswitch),
+ padding: [0, 2, 0, 2 + getIndentation(kswitch)],
+ width: maxWidth(switches, theWrap) + 4
+ }, desc);
+ const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()["hide-types"] === true;
+ if (extra && !shouldHideOptionExtras)
+ ui2.div({ text: extra, padding: [0, 0, 0, 2], align: "right" });
+ else
+ ui2.div();
+ });
+ ui2.div();
+ });
+ if (examples.length) {
+ ui2.div(__("Examples:"));
+ examples.forEach((example) => {
+ example[0] = example[0].replace(/\$0/g, base$0);
+ });
+ examples.forEach((example) => {
+ if (example[1] === "") {
+ ui2.div({
+ text: example[0],
+ padding: [0, 2, 0, 2]
+ });
+ } else {
+ ui2.div({
+ text: example[0],
+ padding: [0, 2, 0, 2],
+ width: maxWidth(examples, theWrap) + 4
+ }, {
+ text: example[1]
+ });
+ }
+ });
+ ui2.div();
+ }
+ if (epilogs.length > 0) {
+ const e2 = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
+ ui2.div(`${e2}
+`);
+ }
+ return ui2.toString().replace(/\s*$/, "");
+ }, "help");
+ function maxWidth(table, theWrap, modifier) {
+ let width = 0;
+ if (!Array.isArray(table)) {
+ table = Object.values(table).map((v) => [v]);
+ }
+ table.forEach((v) => {
+ width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
+ });
+ if (theWrap)
+ width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
+ return width;
+ }
+ __name(maxWidth, "maxWidth");
+ function normalizeAliases() {
+ const demandedOptions = yargs.getDemandedOptions();
+ const options14 = yargs.getOptions();
+ (Object.keys(options14.alias) || []).forEach((key) => {
+ options14.alias[key].forEach((alias) => {
+ if (descriptions[alias])
+ self2.describe(key, descriptions[alias]);
+ if (alias in demandedOptions)
+ yargs.demandOption(key, demandedOptions[alias]);
+ if (options14.boolean.includes(alias))
+ yargs.boolean(key);
+ if (options14.count.includes(alias))
+ yargs.count(key);
+ if (options14.string.includes(alias))
+ yargs.string(key);
+ if (options14.normalize.includes(alias))
+ yargs.normalize(key);
+ if (options14.array.includes(alias))
+ yargs.array(key);
+ if (options14.number.includes(alias))
+ yargs.number(key);
+ });
+ });
+ }
+ __name(normalizeAliases, "normalizeAliases");
+ let cachedHelpMessage;
+ self2.cacheHelpMessage = function() {
+ cachedHelpMessage = this.help();
+ };
+ self2.clearCachedHelpMessage = function() {
+ cachedHelpMessage = void 0;
+ };
+ self2.hasCachedHelpMessage = function() {
+ return !!cachedHelpMessage;
+ };
+ function addUngroupedKeys(keys, aliases2, groups, defaultGroup) {
+ let groupedKeys = [];
+ let toCheck = null;
+ Object.keys(groups).forEach((group) => {
+ groupedKeys = groupedKeys.concat(groups[group]);
+ });
+ keys.forEach((key) => {
+ toCheck = [key].concat(aliases2[key]);
+ if (!toCheck.some((k) => groupedKeys.indexOf(k) !== -1)) {
+ groups[defaultGroup].push(key);
+ }
+ });
+ return groupedKeys;
+ }
+ __name(addUngroupedKeys, "addUngroupedKeys");
+ function filterHiddenOptions(key) {
+ return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt];
+ }
+ __name(filterHiddenOptions, "filterHiddenOptions");
+ self2.showHelp = (level) => {
+ const logger2 = yargs.getInternalMethods().getLoggerInstance();
+ if (!level)
+ level = "error";
+ const emit = typeof level === "function" ? level : logger2[level];
+ emit(self2.help());
+ };
+ self2.functionDescription = (fn2) => {
+ const description = fn2.name ? shim3.Parser.decamelize(fn2.name, "-") : __("generated-value");
+ return ["(", description, ")"].join("");
+ };
+ self2.stringifiedValues = /* @__PURE__ */ __name(function stringifiedValues(values, separator) {
+ let string = "";
+ const sep2 = separator || ", ";
+ const array = [].concat(values);
+ if (!values || !array.length)
+ return string;
+ array.forEach((value) => {
+ if (string.length)
+ string += sep2;
+ string += JSON.stringify(value);
+ });
+ return string;
+ }, "stringifiedValues");
+ function defaultString(value, defaultDescription) {
+ let string = `[${__("default:")} `;
+ if (value === void 0 && !defaultDescription)
+ return null;
+ if (defaultDescription) {
+ string += defaultDescription;
+ } else {
+ switch (typeof value) {
+ case "string":
+ string += `"${value}"`;
+ break;
+ case "object":
+ string += JSON.stringify(value);
+ break;
+ default:
+ string += value;
+ }
+ }
+ return `${string}]`;
+ }
+ __name(defaultString, "defaultString");
+ function windowWidth() {
+ const maxWidth2 = 80;
+ if (shim3.process.stdColumns) {
+ return Math.min(maxWidth2, shim3.process.stdColumns);
+ } else {
+ return maxWidth2;
+ }
+ }
+ __name(windowWidth, "windowWidth");
+ let version2 = null;
+ self2.version = (ver) => {
+ version2 = ver;
+ };
+ self2.showVersion = (level) => {
+ const logger2 = yargs.getInternalMethods().getLoggerInstance();
+ if (!level)
+ level = "error";
+ const emit = typeof level === "function" ? level : logger2[level];
+ emit(version2);
+ };
+ self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
+ failMessage = null;
+ failureOutput = false;
+ usages = [];
+ usageDisabled = false;
+ epilogs = [];
+ examples = [];
+ commands = [];
+ descriptions = objFilter(descriptions, (k) => !localLookup[k]);
+ return self2;
+ }, "reset");
+ const frozens = [];
+ self2.freeze = /* @__PURE__ */ __name(function freeze() {
+ frozens.push({
+ failMessage,
+ failureOutput,
+ usages,
+ usageDisabled,
+ epilogs,
+ examples,
+ commands,
+ descriptions
+ });
+ }, "freeze");
+ self2.unfreeze = /* @__PURE__ */ __name(function unfreeze(defaultCommand = false) {
+ const frozen = frozens.pop();
+ if (!frozen)
+ return;
+ if (defaultCommand) {
+ descriptions = { ...frozen.descriptions, ...descriptions };
+ commands = [...frozen.commands, ...commands];
+ usages = [...frozen.usages, ...usages];
+ examples = [...frozen.examples, ...examples];
+ epilogs = [...frozen.epilogs, ...epilogs];
+ } else {
+ ({
+ failMessage,
+ failureOutput,
+ usages,
+ usageDisabled,
+ epilogs,
+ examples,
+ commands,
+ descriptions
+ } = frozen);
+ }
+ }, "unfreeze");
+ return self2;
+}
+__name(usage, "usage");
+function isIndentedText(text) {
+ return typeof text === "object";
+}
+__name(isIndentedText, "isIndentedText");
+function addIndentation(text, indent) {
+ return isIndentedText(text) ? { text: text.text, indentation: text.indentation + indent } : { text, indentation: indent };
+}
+__name(addIndentation, "addIndentation");
+function getIndentation(text) {
+ return isIndentedText(text) ? text.indentation : 0;
+}
+__name(getIndentation, "getIndentation");
+function getText(text) {
+ return isIndentedText(text) ? text.text : text;
+}
+__name(getText, "getText");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/completion.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/completion-templates.js
+init_import_meta_url();
+var completionShTemplate = `###-begin-{{app_name}}-completions-###
+#
+# yargs command completion script
+#
+# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
+# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
+#
+_{{app_name}}_yargs_completions()
+{
+ local cur_word args type_list
+
+ cur_word="\${COMP_WORDS[COMP_CWORD]}"
+ args=("\${COMP_WORDS[@]}")
+
+ # ask yargs to generate completions.
+ type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")
+
+ COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )
+
+ # if no match was found, fall back to filename completion
+ if [ \${#COMPREPLY[@]} -eq 0 ]; then
+ COMPREPLY=()
+ fi
+
+ return 0
+}
+complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
+###-end-{{app_name}}-completions-###
+`;
+var completionZshTemplate = `#compdef {{app_name}}
+###-begin-{{app_name}}-completions-###
+#
+# yargs command completion script
+#
+# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
+# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
+#
+_{{app_name}}_yargs_completions()
+{
+ local reply
+ local si=$IFS
+ IFS=$'
+' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
+ IFS=$si
+ _describe 'values' reply
+}
+compdef _{{app_name}}_yargs_completions {{app_name}}
+###-end-{{app_name}}-completions-###
+`;
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/completion.js
+var Completion = class {
+ constructor(yargs, usage2, command2, shim3) {
+ var _a2, _b2, _c2;
+ this.yargs = yargs;
+ this.usage = usage2;
+ this.command = command2;
+ this.shim = shim3;
+ this.completionKey = "get-yargs-completions";
+ this.aliases = null;
+ this.customCompletionFunction = null;
+ this.indexAfterLastReset = 0;
+ this.zshShell = (_c2 = ((_a2 = this.shim.getEnv("SHELL")) === null || _a2 === void 0 ? void 0 : _a2.includes("zsh")) || ((_b2 = this.shim.getEnv("ZSH_NAME")) === null || _b2 === void 0 ? void 0 : _b2.includes("zsh"))) !== null && _c2 !== void 0 ? _c2 : false;
+ }
+ defaultCompletion(args, argv, current, done) {
+ const handlers = this.command.getCommandHandlers();
+ for (let i = 0, ii = args.length; i < ii; ++i) {
+ if (handlers[args[i]] && handlers[args[i]].builder) {
+ const builder = handlers[args[i]].builder;
+ if (isCommandBuilderCallback(builder)) {
+ this.indexAfterLastReset = i + 1;
+ const y = this.yargs.getInternalMethods().reset();
+ builder(y, true);
+ return y.argv;
+ }
+ }
+ }
+ const completions = [];
+ this.commandCompletions(completions, args, current);
+ this.optionCompletions(completions, args, argv, current);
+ this.choicesFromOptionsCompletions(completions, args, argv, current);
+ this.choicesFromPositionalsCompletions(completions, args, argv, current);
+ done(null, completions);
+ }
+ commandCompletions(completions, args, current) {
+ const parentCommands = this.yargs.getInternalMethods().getContext().commands;
+ if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args)) {
+ this.usage.getCommands().forEach((usageCommand) => {
+ const commandName = parseCommand2(usageCommand[0]).cmd;
+ if (args.indexOf(commandName) === -1) {
+ if (!this.zshShell) {
+ completions.push(commandName);
+ } else {
+ const desc = usageCommand[1] || "";
+ completions.push(commandName.replace(/:/g, "\\:") + ":" + desc);
+ }
+ }
+ });
+ }
+ }
+ optionCompletions(completions, args, argv, current) {
+ if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args)) {
+ const options14 = this.yargs.getOptions();
+ const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
+ Object.keys(options14.key).forEach((key) => {
+ const negable = !!options14.configuration["boolean-negation"] && options14.boolean.includes(key);
+ const isPositionalKey = positionalKeys.includes(key);
+ if (!isPositionalKey && !options14.hiddenOptions.includes(key) && !this.argsContainKey(args, key, negable)) {
+ this.completeOptionKey(key, completions, current);
+ if (negable && !!options14.default[key])
+ this.completeOptionKey(`no-${key}`, completions, current);
+ }
+ });
+ }
+ }
+ choicesFromOptionsCompletions(completions, args, argv, current) {
+ if (this.previousArgHasChoices(args)) {
+ const choices = this.getPreviousArgChoices(args);
+ if (choices && choices.length > 0) {
+ completions.push(...choices.map((c) => c.replace(/:/g, "\\:")));
+ }
+ }
+ }
+ choicesFromPositionalsCompletions(completions, args, argv, current) {
+ if (current === "" && completions.length > 0 && this.previousArgHasChoices(args)) {
+ return;
+ }
+ const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
+ const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + 1);
+ const positionalKey = positionalKeys[argv._.length - offset - 1];
+ if (!positionalKey) {
+ return;
+ }
+ const choices = this.yargs.getOptions().choices[positionalKey] || [];
+ for (const choice of choices) {
+ if (choice.startsWith(current)) {
+ completions.push(choice.replace(/:/g, "\\:"));
+ }
+ }
+ }
+ getPreviousArgChoices(args) {
+ if (args.length < 1)
+ return;
+ let previousArg = args[args.length - 1];
+ let filter = "";
+ if (!previousArg.startsWith("-") && args.length > 1) {
+ filter = previousArg;
+ previousArg = args[args.length - 2];
+ }
+ if (!previousArg.startsWith("-"))
+ return;
+ const previousArgKey = previousArg.replace(/^-+/, "");
+ const options14 = this.yargs.getOptions();
+ const possibleAliases = [
+ previousArgKey,
+ ...this.yargs.getAliases()[previousArgKey] || []
+ ];
+ let choices;
+ for (const possibleAlias of possibleAliases) {
+ if (Object.prototype.hasOwnProperty.call(options14.key, possibleAlias) && Array.isArray(options14.choices[possibleAlias])) {
+ choices = options14.choices[possibleAlias];
+ break;
+ }
+ }
+ if (choices) {
+ return choices.filter((choice) => !filter || choice.startsWith(filter));
+ }
+ }
+ previousArgHasChoices(args) {
+ const choices = this.getPreviousArgChoices(args);
+ return choices !== void 0 && choices.length > 0;
+ }
+ argsContainKey(args, key, negable) {
+ const argsContains = /* @__PURE__ */ __name((s) => args.indexOf((/^[^0-9]$/.test(s) ? "-" : "--") + s) !== -1, "argsContains");
+ if (argsContains(key))
+ return true;
+ if (negable && argsContains(`no-${key}`))
+ return true;
+ if (this.aliases) {
+ for (const alias of this.aliases[key]) {
+ if (argsContains(alias))
+ return true;
+ }
+ }
+ return false;
+ }
+ completeOptionKey(key, completions, current) {
+ var _a2, _b2, _c2;
+ const descs = this.usage.getDescriptions();
+ const startsByTwoDashes = /* @__PURE__ */ __name((s) => /^--/.test(s), "startsByTwoDashes");
+ const isShortOption = /* @__PURE__ */ __name((s) => /^[^0-9]$/.test(s), "isShortOption");
+ const dashes = !startsByTwoDashes(current) && isShortOption(key) ? "-" : "--";
+ if (!this.zshShell) {
+ completions.push(dashes + key);
+ } else {
+ const aliasKey = (_a2 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a2 === void 0 ? void 0 : _a2[key].find((alias) => {
+ const desc2 = descs[alias];
+ return typeof desc2 === "string" && desc2.length > 0;
+ });
+ const descFromAlias = aliasKey ? descs[aliasKey] : void 0;
+ const desc = (_c2 = (_b2 = descs[key]) !== null && _b2 !== void 0 ? _b2 : descFromAlias) !== null && _c2 !== void 0 ? _c2 : "";
+ completions.push(dashes + `${key.replace(/:/g, "\\:")}:${desc.replace("__yargsString__:", "").replace(/(\r\n|\n|\r)/gm, " ")}`);
+ }
+ }
+ customCompletion(args, argv, current, done) {
+ assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
+ if (isSyncCompletionFunction(this.customCompletionFunction)) {
+ const result = this.customCompletionFunction(current, argv);
+ if (isPromise(result)) {
+ return result.then((list) => {
+ this.shim.process.nextTick(() => {
+ done(null, list);
+ });
+ }).catch((err) => {
+ this.shim.process.nextTick(() => {
+ done(err, void 0);
+ });
+ });
+ }
+ return done(null, result);
+ } else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
+ return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), (completions) => {
+ done(null, completions);
+ });
+ } else {
+ return this.customCompletionFunction(current, argv, (completions) => {
+ done(null, completions);
+ });
+ }
+ }
+ getCompletion(args, done) {
+ const current = args.length ? args[args.length - 1] : "";
+ const argv = this.yargs.parse(args, true);
+ const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args, argv2, current, done) : (argv2) => this.defaultCompletion(args, argv2, current, done);
+ return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
+ }
+ generateCompletionScript($0, cmd) {
+ let script = this.zshShell ? completionZshTemplate : completionShTemplate;
+ const name = this.shim.path.basename($0);
+ if ($0.match(/\.js$/))
+ $0 = `./${$0}`;
+ script = script.replace(/{{app_name}}/g, name);
+ script = script.replace(/{{completion_command}}/g, cmd);
+ return script.replace(/{{app_path}}/g, $0);
+ }
+ registerFunction(fn2) {
+ this.customCompletionFunction = fn2;
+ }
+ setParsed(parsed) {
+ this.aliases = parsed.aliases;
+ }
+};
+__name(Completion, "Completion");
+function completion(yargs, usage2, command2, shim3) {
+ return new Completion(yargs, usage2, command2, shim3);
+}
+__name(completion, "completion");
+function isSyncCompletionFunction(completionFunction) {
+ return completionFunction.length < 3;
+}
+__name(isSyncCompletionFunction, "isSyncCompletionFunction");
+function isFallbackCompletionFunction(completionFunction) {
+ return completionFunction.length > 3;
+}
+__name(isFallbackCompletionFunction, "isFallbackCompletionFunction");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/validation.js
+init_import_meta_url();
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/utils/levenshtein.js
+init_import_meta_url();
+function levenshtein(a, b) {
+ if (a.length === 0)
+ return b.length;
+ if (b.length === 0)
+ return a.length;
+ const matrix = [];
+ let i;
+ for (i = 0; i <= b.length; i++) {
+ matrix[i] = [i];
+ }
+ let j;
+ for (j = 0; j <= a.length; j++) {
+ matrix[0][j] = j;
+ }
+ for (i = 1; i <= b.length; i++) {
+ for (j = 1; j <= a.length; j++) {
+ if (b.charAt(i - 1) === a.charAt(j - 1)) {
+ matrix[i][j] = matrix[i - 1][j - 1];
+ } else {
+ if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) {
+ matrix[i][j] = matrix[i - 2][j - 2] + 1;
+ } else {
+ matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
+ }
+ }
+ }
+ }
+ return matrix[b.length][a.length];
+}
+__name(levenshtein, "levenshtein");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/validation.js
+var specialKeys = ["$0", "--", "_"];
+function validation(yargs, usage2, shim3) {
+ const __ = shim3.y18n.__;
+ const __n = shim3.y18n.__n;
+ const self2 = {};
+ self2.nonOptionCount = /* @__PURE__ */ __name(function nonOptionCount(argv) {
+ const demandedCommands = yargs.getDemandedCommands();
+ const positionalCount = argv._.length + (argv["--"] ? argv["--"].length : 0);
+ const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
+ if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
+ if (_s < demandedCommands._.min) {
+ if (demandedCommands._.minMsg !== void 0) {
+ usage2.fail(demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) : null);
+ } else {
+ usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", _s, _s.toString(), demandedCommands._.min.toString()));
+ }
+ } else if (_s > demandedCommands._.max) {
+ if (demandedCommands._.maxMsg !== void 0) {
+ usage2.fail(demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) : null);
+ } else {
+ usage2.fail(__n("Too many non-option arguments: got %s, maximum of %s", "Too many non-option arguments: got %s, maximum of %s", _s, _s.toString(), demandedCommands._.max.toString()));
+ }
+ }
+ }
+ }, "nonOptionCount");
+ self2.positionalCount = /* @__PURE__ */ __name(function positionalCount(required, observed) {
+ if (observed < required) {
+ usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", observed, observed + "", required + ""));
+ }
+ }, "positionalCount");
+ self2.requiredArguments = /* @__PURE__ */ __name(function requiredArguments(argv, demandedOptions) {
+ let missing = null;
+ for (const key of Object.keys(demandedOptions)) {
+ if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === "undefined") {
+ missing = missing || {};
+ missing[key] = demandedOptions[key];
+ }
+ }
+ if (missing) {
+ const customMsgs = [];
+ for (const key of Object.keys(missing)) {
+ const msg = missing[key];
+ if (msg && customMsgs.indexOf(msg) < 0) {
+ customMsgs.push(msg);
+ }
+ }
+ const customMsg = customMsgs.length ? `
+${customMsgs.join("\n")}` : "";
+ usage2.fail(__n("Missing required argument: %s", "Missing required arguments: %s", Object.keys(missing).length, Object.keys(missing).join(", ") + customMsg));
+ }
+ }, "requiredArguments");
+ self2.unknownArguments = /* @__PURE__ */ __name(function unknownArguments(argv, aliases2, positionalMap, isDefaultCommand, checkPositionals = true) {
+ var _a2;
+ const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
+ const unknown = [];
+ const currentContext = yargs.getInternalMethods().getContext();
+ Object.keys(argv).forEach((key) => {
+ if (!specialKeys.includes(key) && !Object.prototype.hasOwnProperty.call(positionalMap, key) && !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && !self2.isValidAndSomeAliasIsNotNew(key, aliases2)) {
+ unknown.push(key);
+ }
+ });
+ if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
+ argv._.slice(currentContext.commands.length).forEach((key) => {
+ if (!commandKeys.includes("" + key)) {
+ unknown.push("" + key);
+ }
+ });
+ }
+ if (checkPositionals) {
+ const demandedCommands = yargs.getDemandedCommands();
+ const maxNonOptDemanded = ((_a2 = demandedCommands._) === null || _a2 === void 0 ? void 0 : _a2.max) || 0;
+ const expected = currentContext.commands.length + maxNonOptDemanded;
+ if (expected < argv._.length) {
+ argv._.slice(expected).forEach((key) => {
+ key = String(key);
+ if (!currentContext.commands.includes(key) && !unknown.includes(key)) {
+ unknown.push(key);
+ }
+ });
+ }
+ }
+ if (unknown.length) {
+ usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown.length, unknown.map((s) => s.trim() ? s : `"${s}"`).join(", ")));
+ }
+ }, "unknownArguments");
+ self2.unknownCommands = /* @__PURE__ */ __name(function unknownCommands(argv) {
+ const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
+ const unknown = [];
+ const currentContext = yargs.getInternalMethods().getContext();
+ if (currentContext.commands.length > 0 || commandKeys.length > 0) {
+ argv._.slice(currentContext.commands.length).forEach((key) => {
+ if (!commandKeys.includes("" + key)) {
+ unknown.push("" + key);
+ }
+ });
+ }
+ if (unknown.length > 0) {
+ usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown.length, unknown.join(", ")));
+ return true;
+ } else {
+ return false;
+ }
+ }, "unknownCommands");
+ self2.isValidAndSomeAliasIsNotNew = /* @__PURE__ */ __name(function isValidAndSomeAliasIsNotNew(key, aliases2) {
+ if (!Object.prototype.hasOwnProperty.call(aliases2, key)) {
+ return false;
+ }
+ const newAliases = yargs.parsed.newAliases;
+ return [key, ...aliases2[key]].some((a) => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
+ }, "isValidAndSomeAliasIsNotNew");
+ self2.limitedChoices = /* @__PURE__ */ __name(function limitedChoices(argv) {
+ const options14 = yargs.getOptions();
+ const invalid = {};
+ if (!Object.keys(options14.choices).length)
+ return;
+ Object.keys(argv).forEach((key) => {
+ if (specialKeys.indexOf(key) === -1 && Object.prototype.hasOwnProperty.call(options14.choices, key)) {
+ [].concat(argv[key]).forEach((value) => {
+ if (options14.choices[key].indexOf(value) === -1 && value !== void 0) {
+ invalid[key] = (invalid[key] || []).concat(value);
+ }
+ });
+ }
+ });
+ const invalidKeys = Object.keys(invalid);
+ if (!invalidKeys.length)
+ return;
+ let msg = __("Invalid values:");
+ invalidKeys.forEach((key) => {
+ msg += `
+ ${__("Argument: %s, Given: %s, Choices: %s", key, usage2.stringifiedValues(invalid[key]), usage2.stringifiedValues(options14.choices[key]))}`;
+ });
+ usage2.fail(msg);
+ }, "limitedChoices");
+ let implied = {};
+ self2.implies = /* @__PURE__ */ __name(function implies(key, value) {
+ argsert(" [array|number|string]", [key, value], arguments.length);
+ if (typeof key === "object") {
+ Object.keys(key).forEach((k) => {
+ self2.implies(k, key[k]);
+ });
+ } else {
+ yargs.global(key);
+ if (!implied[key]) {
+ implied[key] = [];
+ }
+ if (Array.isArray(value)) {
+ value.forEach((i) => self2.implies(key, i));
+ } else {
+ assertNotStrictEqual(value, void 0, shim3);
+ implied[key].push(value);
+ }
+ }
+ }, "implies");
+ self2.getImplied = /* @__PURE__ */ __name(function getImplied() {
+ return implied;
+ }, "getImplied");
+ function keyExists(argv, val) {
+ const num = Number(val);
+ val = isNaN(num) ? val : num;
+ if (typeof val === "number") {
+ val = argv._.length >= val;
+ } else if (val.match(/^--no-.+/)) {
+ val = val.match(/^--no-(.+)/)[1];
+ val = !Object.prototype.hasOwnProperty.call(argv, val);
+ } else {
+ val = Object.prototype.hasOwnProperty.call(argv, val);
+ }
+ return val;
+ }
+ __name(keyExists, "keyExists");
+ self2.implications = /* @__PURE__ */ __name(function implications(argv) {
+ const implyFail = [];
+ Object.keys(implied).forEach((key) => {
+ const origKey = key;
+ (implied[key] || []).forEach((value) => {
+ let key2 = origKey;
+ const origValue = value;
+ key2 = keyExists(argv, key2);
+ value = keyExists(argv, value);
+ if (key2 && !value) {
+ implyFail.push(` ${origKey} -> ${origValue}`);
+ }
+ });
+ });
+ if (implyFail.length) {
+ let msg = `${__("Implications failed:")}
+`;
+ implyFail.forEach((value) => {
+ msg += value;
+ });
+ usage2.fail(msg);
+ }
+ }, "implications");
+ let conflicting = {};
+ self2.conflicts = /* @__PURE__ */ __name(function conflicts(key, value) {
+ argsert(" [array|string]", [key, value], arguments.length);
+ if (typeof key === "object") {
+ Object.keys(key).forEach((k) => {
+ self2.conflicts(k, key[k]);
+ });
+ } else {
+ yargs.global(key);
+ if (!conflicting[key]) {
+ conflicting[key] = [];
+ }
+ if (Array.isArray(value)) {
+ value.forEach((i) => self2.conflicts(key, i));
+ } else {
+ conflicting[key].push(value);
+ }
+ }
+ }, "conflicts");
+ self2.getConflicting = () => conflicting;
+ self2.conflicting = /* @__PURE__ */ __name(function conflictingFn(argv) {
+ Object.keys(argv).forEach((key) => {
+ if (conflicting[key]) {
+ conflicting[key].forEach((value) => {
+ if (value && argv[key] !== void 0 && argv[value] !== void 0) {
+ usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
+ }
+ });
+ }
+ });
+ if (yargs.getInternalMethods().getParserConfiguration()["strip-dashed"]) {
+ Object.keys(conflicting).forEach((key) => {
+ conflicting[key].forEach((value) => {
+ if (value && argv[shim3.Parser.camelCase(key)] !== void 0 && argv[shim3.Parser.camelCase(value)] !== void 0) {
+ usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
+ }
+ });
+ });
+ }
+ }, "conflictingFn");
+ self2.recommendCommands = /* @__PURE__ */ __name(function recommendCommands(cmd, potentialCommands) {
+ const threshold = 3;
+ potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
+ let recommended = null;
+ let bestDistance = Infinity;
+ for (let i = 0, candidate; (candidate = potentialCommands[i]) !== void 0; i++) {
+ const d = levenshtein(cmd, candidate);
+ if (d <= threshold && d < bestDistance) {
+ bestDistance = d;
+ recommended = candidate;
+ }
+ }
+ if (recommended)
+ usage2.fail(__("Did you mean %s?", recommended));
+ }, "recommendCommands");
+ self2.reset = /* @__PURE__ */ __name(function reset(localLookup) {
+ implied = objFilter(implied, (k) => !localLookup[k]);
+ conflicting = objFilter(conflicting, (k) => !localLookup[k]);
+ return self2;
+ }, "reset");
+ const frozens = [];
+ self2.freeze = /* @__PURE__ */ __name(function freeze() {
+ frozens.push({
+ implied,
+ conflicting
+ });
+ }, "freeze");
+ self2.unfreeze = /* @__PURE__ */ __name(function unfreeze() {
+ const frozen = frozens.pop();
+ assertNotStrictEqual(frozen, void 0, shim3);
+ ({ implied, conflicting } = frozen);
+ }, "unfreeze");
+ return self2;
+}
+__name(validation, "validation");
+
+// ../../node_modules/.pnpm/yargs@17.7.1/node_modules/yargs/build/lib/yargs-factory.js
+var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
+ if (kind === "m")
+ throw new TypeError("Private method is not writable");
+ if (kind === "a" && !f)
+ throw new TypeError("Private accessor was defined without a setter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
+ throw new TypeError("Cannot write private member to an object whose class did not declare it");
+ return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
+};
+var __classPrivateFieldGet = function(receiver, state, kind, f) {
+ if (kind === "a" && !f)
+ throw new TypeError("Private accessor was defined without a getter");
+ if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver))
+ throw new TypeError("Cannot read private member from an object whose class did not declare it");
+ return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
+};
+var _YargsInstance_command;
+var _YargsInstance_cwd;
+var _YargsInstance_context;
+var _YargsInstance_completion;
+var _YargsInstance_completionCommand;
+var _YargsInstance_defaultShowHiddenOpt;
+var _YargsInstance_exitError;
+var _YargsInstance_detectLocale;
+var _YargsInstance_emittedWarnings;
+var _YargsInstance_exitProcess;
+var _YargsInstance_frozens;
+var _YargsInstance_globalMiddleware;
+var _YargsInstance_groups;
+var _YargsInstance_hasOutput;
+var _YargsInstance_helpOpt;
+var _YargsInstance_isGlobalContext;
+var _YargsInstance_logger;
+var _YargsInstance_output;
+var _YargsInstance_options;
+var _YargsInstance_parentRequire;
+var _YargsInstance_parserConfig;
+var _YargsInstance_parseFn;
+var _YargsInstance_parseContext;
+var _YargsInstance_pkgs;
+var _YargsInstance_preservedGroups;
+var _YargsInstance_processArgs;
+var _YargsInstance_recommendCommands;
+var _YargsInstance_shim;
+var _YargsInstance_strict;
+var _YargsInstance_strictCommands;
+var _YargsInstance_strictOptions;
+var _YargsInstance_usage;
+var _YargsInstance_usageConfig;
+var _YargsInstance_versionOpt;
+var _YargsInstance_validation;
+function YargsFactory(_shim) {
+ return (processArgs = [], cwd2 = _shim.process.cwd(), parentRequire) => {
+ const yargs = new YargsInstance(processArgs, cwd2, parentRequire, _shim);
+ Object.defineProperty(yargs, "argv", {
+ get: () => {
+ return yargs.parse();
+ },
+ enumerable: true
+ });
+ yargs.help();
+ yargs.version();
+ return yargs;
+ };
+}
+__name(YargsFactory, "YargsFactory");
+var kCopyDoubleDash = Symbol("copyDoubleDash");
+var kCreateLogger = Symbol("copyDoubleDash");
+var kDeleteFromParserHintObject = Symbol("deleteFromParserHintObject");
+var kEmitWarning = Symbol("emitWarning");
+var kFreeze = Symbol("freeze");
+var kGetDollarZero = Symbol("getDollarZero");
+var kGetParserConfiguration = Symbol("getParserConfiguration");
+var kGetUsageConfiguration = Symbol("getUsageConfiguration");
+var kGuessLocale = Symbol("guessLocale");
+var kGuessVersion = Symbol("guessVersion");
+var kParsePositionalNumbers = Symbol("parsePositionalNumbers");
+var kPkgUp = Symbol("pkgUp");
+var kPopulateParserHintArray = Symbol("populateParserHintArray");
+var kPopulateParserHintSingleValueDictionary = Symbol("populateParserHintSingleValueDictionary");
+var kPopulateParserHintArrayDictionary = Symbol("populateParserHintArrayDictionary");
+var kPopulateParserHintDictionary = Symbol("populateParserHintDictionary");
+var kSanitizeKey = Symbol("sanitizeKey");
+var kSetKey = Symbol("setKey");
+var kUnfreeze = Symbol("unfreeze");
+var kValidateAsync = Symbol("validateAsync");
+var kGetCommandInstance = Symbol("getCommandInstance");
+var kGetContext = Symbol("getContext");
+var kGetHasOutput = Symbol("getHasOutput");
+var kGetLoggerInstance = Symbol("getLoggerInstance");
+var kGetParseContext = Symbol("getParseContext");
+var kGetUsageInstance = Symbol("getUsageInstance");
+var kGetValidationInstance = Symbol("getValidationInstance");
+var kHasParseCallback = Symbol("hasParseCallback");
+var kIsGlobalContext = Symbol("isGlobalContext");
+var kPostProcess = Symbol("postProcess");
+var kRebase = Symbol("rebase");
+var kReset = Symbol("reset");
+var kRunYargsParserAndExecuteCommands = Symbol("runYargsParserAndExecuteCommands");
+var kRunValidation = Symbol("runValidation");
+var kSetHasOutput = Symbol("setHasOutput");
+var kTrackManuallySetKeys = Symbol("kTrackManuallySetKeys");
+var YargsInstance = class {
+ constructor(processArgs = [], cwd2, parentRequire, shim3) {
+ this.customScriptName = false;
+ this.parsed = false;
+ _YargsInstance_command.set(this, void 0);
+ _YargsInstance_cwd.set(this, void 0);
+ _YargsInstance_context.set(this, { commands: [], fullCommands: [] });
+ _YargsInstance_completion.set(this, null);
+ _YargsInstance_completionCommand.set(this, null);
+ _YargsInstance_defaultShowHiddenOpt.set(this, "show-hidden");
+ _YargsInstance_exitError.set(this, null);
+ _YargsInstance_detectLocale.set(this, true);
+ _YargsInstance_emittedWarnings.set(this, {});
+ _YargsInstance_exitProcess.set(this, true);
+ _YargsInstance_frozens.set(this, []);
+ _YargsInstance_globalMiddleware.set(this, void 0);
+ _YargsInstance_groups.set(this, {});
+ _YargsInstance_hasOutput.set(this, false);
+ _YargsInstance_helpOpt.set(this, null);
+ _YargsInstance_isGlobalContext.set(this, true);
+ _YargsInstance_logger.set(this, void 0);
+ _YargsInstance_output.set(this, "");
+ _YargsInstance_options.set(this, void 0);
+ _YargsInstance_parentRequire.set(this, void 0);
+ _YargsInstance_parserConfig.set(this, {});
+ _YargsInstance_parseFn.set(this, null);
+ _YargsInstance_parseContext.set(this, null);
+ _YargsInstance_pkgs.set(this, {});
+ _YargsInstance_preservedGroups.set(this, {});
+ _YargsInstance_processArgs.set(this, void 0);
+ _YargsInstance_recommendCommands.set(this, false);
+ _YargsInstance_shim.set(this, void 0);
+ _YargsInstance_strict.set(this, false);
+ _YargsInstance_strictCommands.set(this, false);
+ _YargsInstance_strictOptions.set(this, false);
+ _YargsInstance_usage.set(this, void 0);
+ _YargsInstance_usageConfig.set(this, {});
+ _YargsInstance_versionOpt.set(this, null);
+ _YargsInstance_validation.set(this, void 0);
+ __classPrivateFieldSet(this, _YargsInstance_shim, shim3, "f");
+ __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f");
+ __classPrivateFieldSet(this, _YargsInstance_cwd, cwd2, "f");
+ __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f");
+ __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
+ this.$0 = this[kGetDollarZero]();
+ this[kReset]();
+ __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f");
+ __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f");
+ __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f");
+ __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f");
+ __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f");
+ __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f");
+ }
+ addHelpOpt(opt, msg) {
+ const defaultHelpOpt = "help";
+ argsert("[string|boolean] [string]", [opt, msg], arguments.length);
+ if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) {
+ this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"));
+ __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f");
+ }
+ if (opt === false && msg === void 0)
+ return this;
+ __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
+ this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"));
+ this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup("Show help"));
+ return this;
+ }
+ help(opt, msg) {
+ return this.addHelpOpt(opt, msg);
+ }
+ addShowHiddenOpt(opt, msg) {
+ argsert("[string|boolean] [string]", [opt, msg], arguments.length);
+ if (opt === false && msg === void 0)
+ return this;
+ const showHiddenOpt = typeof opt === "string" ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f");
+ this.boolean(showHiddenOpt);
+ this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
+ __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
+ return this;
+ }
+ showHidden(opt, msg) {
+ return this.addShowHiddenOpt(opt, msg);
+ }
+ alias(key, value) {
+ argsert("