/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __esm = (fn, res) => function __init() { return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; }; var __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all5) => { for (var name in all5) __defProp(target, name, { get: all5[name], enumerable: true }); }; var __copyProps = (to, from, except, desc) => { if (from && typeof from === "object" || typeof from === "function") { for (let key of __getOwnPropNames(from)) if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); } return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( // If the importer is in node compatibility mode or this is not an ESM // file that has been converted to a CommonJS file using a Babel- // compatible transform (i.e. "__esModule" has not been set), then set // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; // node_modules/crypto-js/core.js var require_core = __commonJS({ "node_modules/crypto-js/core.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { define([], factory); } else { root2.CryptoJS = factory(); } })(exports, function() { var CryptoJS = CryptoJS || function(Math2, undefined2) { var crypto2; if (typeof window !== "undefined" && window.crypto) { crypto2 = window.crypto; } if (typeof self !== "undefined" && self.crypto) { crypto2 = self.crypto; } if (typeof globalThis !== "undefined" && globalThis.crypto) { crypto2 = globalThis.crypto; } if (!crypto2 && typeof window !== "undefined" && window.msCrypto) { crypto2 = window.msCrypto; } if (!crypto2 && typeof global !== "undefined" && global.crypto) { crypto2 = global.crypto; } if (!crypto2 && typeof require === "function") { try { crypto2 = require("crypto"); } catch (err) { } } var cryptoSecureRandomInt = function() { if (crypto2) { if (typeof crypto2.getRandomValues === "function") { try { return crypto2.getRandomValues(new Uint32Array(1))[0]; } catch (err) { } } if (typeof crypto2.randomBytes === "function") { try { return crypto2.randomBytes(4).readInt32LE(); } catch (err) { } } } throw new Error("Native crypto module could not be used to get secure random number."); }; var create2 = Object.create || function() { function F() { } return function(obj) { var subtype; F.prototype = obj; subtype = new F(); F.prototype = null; return subtype; }; }(); var C = {}; var C_lib = C.lib = {}; var Base = C_lib.Base = function() { return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function(overrides) { var subtype = create2(this); if (overrides) { subtype.mixIn(overrides); } if (!subtype.hasOwnProperty("init") || this.init === subtype.init) { subtype.init = function() { subtype.$super.init.apply(this, arguments); }; } subtype.init.prototype = subtype; subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function() { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function() { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function(properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } if (properties.hasOwnProperty("toString")) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function() { return this.init.prototype.extend(this); } }; }(); var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function(words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined2) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function(encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function(wordArray) { var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; this.clamp(); if (thisSigBytes % 4) { for (var i = 0; i < thatSigBytes; i++) { var thatByte = thatWords[i >>> 2] >>> 24 - i % 4 * 8 & 255; thisWords[thisSigBytes + i >>> 2] |= thatByte << 24 - (thisSigBytes + i) % 4 * 8; } } else { for (var j = 0; j < thatSigBytes; j += 4) { thisWords[thisSigBytes + j >>> 2] = thatWords[j >>> 2]; } } this.sigBytes += thatSigBytes; return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function() { var words = this.words; var sigBytes = this.sigBytes; words[sigBytes >>> 2] &= 4294967295 << 32 - sigBytes % 4 * 8; words.length = Math2.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function() { var clone2 = Base.clone.call(this); clone2.words = this.words.slice(0); return clone2; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function(nBytes) { var words = []; for (var i = 0; i < nBytes; i += 4) { words.push(cryptoSecureRandomInt()); } return new WordArray.init(words, nBytes); } }); var C_enc = C.enc = {}; var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function(wordArray) { var words = wordArray.words; var sigBytes = wordArray.sigBytes; var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 15).toString(16)); } return hexChars.join(""); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function(hexStr) { var hexStrLength = hexStr.length; var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << 24 - i % 8 * 4; } return new WordArray.init(words, hexStrLength / 2); } }; var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function(wordArray) { var words = wordArray.words; var sigBytes = wordArray.sigBytes; var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = words[i >>> 2] >>> 24 - i % 4 * 8 & 255; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(""); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function(latin1Str) { var latin1StrLength = latin1Str.length; var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 255) << 24 - i % 4 * 8; } return new WordArray.init(words, latin1StrLength); } }; var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function(wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error("Malformed UTF-8 data"); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function(utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function() { this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function(data) { if (typeof data == "string") { data = Utf8.parse(data); } this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function(doFlush) { var processedWords; var data = this._data; var dataWords2 = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { nBlocksReady = Math2.ceil(nBlocksReady); } else { nBlocksReady = Math2.max((nBlocksReady | 0) - this._minBufferSize, 0); } var nWordsReady = nBlocksReady * blockSize; var nBytesReady = Math2.min(nWordsReady * 4, dataSigBytes); if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { this._doProcessBlock(dataWords2, offset); } processedWords = dataWords2.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function() { var clone2 = Base.clone.call(this); clone2._data = this._data.clone(); return clone2; }, _minBufferSize: 0 }); var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function(cfg) { this.cfg = this.cfg.extend(cfg); this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function() { BufferedBlockAlgorithm.reset.call(this); this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function(messageUpdate) { this._append(messageUpdate); this._process(); return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function(messageUpdate) { if (messageUpdate) { this._append(messageUpdate); } var hash = this._doFinalize(); return hash; }, blockSize: 512 / 32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function(hasher) { return function(message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function(hasher) { return function(message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); var C_algo = C.algo = {}; return C; }(Math); return CryptoJS; }); } }); // node_modules/crypto-js/x64-core.js var require_x64_core = __commonJS({ "node_modules/crypto-js/x64-core.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function(undefined2) { var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; var C_x64 = C.x64 = {}; var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function(high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function(words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined2) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function() { var x64Words = this.words; var x64WordsLength = x64Words.length; var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function() { var clone2 = Base.clone.call(this); var words = clone2.words = this.words.slice(0); var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone2; } }); })(); return CryptoJS; }); } }); // node_modules/crypto-js/lib-typedarrays.js var require_lib_typedarrays = __commonJS({ "node_modules/crypto-js/lib-typedarrays.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { if (typeof ArrayBuffer != "function") { return; } var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var superInit = WordArray.init; var subInit = WordArray.init = function(typedArray) { if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } if (typedArray instanceof Int8Array || typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } if (typedArray instanceof Uint8Array) { var typedArrayByteLength = typedArray.byteLength; var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << 24 - i % 4 * 8; } superInit.call(this, words, typedArrayByteLength); } else { superInit.apply(this, arguments); } }; subInit.prototype = WordArray; })(); return CryptoJS.lib.WordArray; }); } }); // node_modules/crypto-js/enc-utf16.js var require_enc_utf16 = __commonJS({ "node_modules/crypto-js/enc-utf16.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function(wordArray) { var words = wordArray.words; var sigBytes = wordArray.sigBytes; var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = words[i >>> 2] >>> 16 - i % 4 * 8 & 65535; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(""); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function(utf16Str) { var utf16StrLength = utf16Str.length; var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << 16 - i % 2 * 16; } return WordArray.create(words, utf16StrLength * 2); } }; C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function(wordArray) { var words = wordArray.words; var sigBytes = wordArray.sigBytes; var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian(words[i >>> 2] >>> 16 - i % 4 * 8 & 65535); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(""); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function(utf16Str) { var utf16StrLength = utf16Str.length; var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << 16 - i % 2 * 16); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return word << 8 & 4278255360 | word >>> 8 & 16711935; } })(); return CryptoJS.enc.Utf16; }); } }); // node_modules/crypto-js/enc-base64.js var require_enc_base64 = __commonJS({ "node_modules/crypto-js/enc-base64.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function(wordArray) { var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map2 = this._map; wordArray.clamp(); var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 255; var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255; var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255; var triplet = byte1 << 16 | byte2 << 8 | byte3; for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) { base64Chars.push(map2.charAt(triplet >>> 6 * (3 - j) & 63)); } } var paddingChar = map2.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(""); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function(base64Str) { var base64StrLength = base64Str.length; var map2 = this._map; var reverseMap = this._reverseMap; if (!reverseMap) { reverseMap = this._reverseMap = []; for (var j = 0; j < map2.length; j++) { reverseMap[map2.charCodeAt(j)] = j; } } var paddingChar = map2.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } return parseLoop(base64Str, base64StrLength, reverseMap); }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" }; function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << i % 4 * 2; var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> 6 - i % 4 * 2; var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8; nBytes++; } } return WordArray.create(words, nBytes); } })(); return CryptoJS.enc.Base64; }); } }); // node_modules/crypto-js/enc-base64url.js var require_enc_base64url = __commonJS({ "node_modules/crypto-js/enc-base64url.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; var Base64url = C_enc.Base64url = { /** * Converts a word array to a Base64url string. * * @param {WordArray} wordArray The word array. * * @param {boolean} urlSafe Whether to use url safe * * @return {string} The Base64url string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64url.stringify(wordArray); */ stringify: function(wordArray, urlSafe = true) { var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map2 = urlSafe ? this._safe_map : this._map; wordArray.clamp(); var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 255; var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 255; var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 255; var triplet = byte1 << 16 | byte2 << 8 | byte3; for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) { base64Chars.push(map2.charAt(triplet >>> 6 * (3 - j) & 63)); } } var paddingChar = map2.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(""); }, /** * Converts a Base64url string to a word array. * * @param {string} base64Str The Base64url string. * * @param {boolean} urlSafe Whether to use url safe * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64url.parse(base64String); */ parse: function(base64Str, urlSafe = true) { var base64StrLength = base64Str.length; var map2 = urlSafe ? this._safe_map : this._map; var reverseMap = this._reverseMap; if (!reverseMap) { reverseMap = this._reverseMap = []; for (var j = 0; j < map2.length; j++) { reverseMap[map2.charCodeAt(j)] = j; } } var paddingChar = map2.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex !== -1) { base64StrLength = paddingIndex; } } return parseLoop(base64Str, base64StrLength, reverseMap); }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", _safe_map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" }; function parseLoop(base64Str, base64StrLength, reverseMap) { var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = reverseMap[base64Str.charCodeAt(i - 1)] << i % 4 * 2; var bits2 = reverseMap[base64Str.charCodeAt(i)] >>> 6 - i % 4 * 2; var bitsCombined = bits1 | bits2; words[nBytes >>> 2] |= bitsCombined << 24 - nBytes % 4 * 8; nBytes++; } } return WordArray.create(words, nBytes); } })(); return CryptoJS.enc.Base64url; }); } }); // node_modules/crypto-js/md5.js var require_md5 = __commonJS({ "node_modules/crypto-js/md5.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function(Math2) { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; var T = []; (function() { for (var i = 0; i < 64; i++) { T[i] = Math2.abs(Math2.sin(i + 1)) * 4294967296 | 0; } })(); var MD52 = C_algo.MD5 = Hasher.extend({ _doReset: function() { this._hash = new WordArray.init([ 1732584193, 4023233417, 2562383102, 271733878 ]); }, _doProcessBlock: function(M, offset) { for (var i = 0; i < 16; i++) { var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360; } var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; var a2 = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; a2 = FF(a2, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a2, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a2, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a2, M_offset_3, 22, T[3]); a2 = FF(a2, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a2, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a2, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a2, M_offset_7, 22, T[7]); a2 = FF(a2, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a2, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a2, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a2, M_offset_11, 22, T[11]); a2 = FF(a2, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a2, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a2, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a2, M_offset_15, 22, T[15]); a2 = GG(a2, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a2, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a2, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a2, M_offset_0, 20, T[19]); a2 = GG(a2, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a2, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a2, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a2, M_offset_4, 20, T[23]); a2 = GG(a2, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a2, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a2, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a2, M_offset_8, 20, T[27]); a2 = GG(a2, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a2, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a2, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a2, M_offset_12, 20, T[31]); a2 = HH(a2, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a2, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a2, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a2, M_offset_14, 23, T[35]); a2 = HH(a2, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a2, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a2, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a2, M_offset_10, 23, T[39]); a2 = HH(a2, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a2, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a2, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a2, M_offset_6, 23, T[43]); a2 = HH(a2, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a2, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a2, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a2, M_offset_2, 23, T[47]); a2 = II(a2, b, c, d, M_offset_0, 6, T[48]); d = II(d, a2, b, c, M_offset_7, 10, T[49]); c = II(c, d, a2, b, M_offset_14, 15, T[50]); b = II(b, c, d, a2, M_offset_5, 21, T[51]); a2 = II(a2, b, c, d, M_offset_12, 6, T[52]); d = II(d, a2, b, c, M_offset_3, 10, T[53]); c = II(c, d, a2, b, M_offset_10, 15, T[54]); b = II(b, c, d, a2, M_offset_1, 21, T[55]); a2 = II(a2, b, c, d, M_offset_8, 6, T[56]); d = II(d, a2, b, c, M_offset_15, 10, T[57]); c = II(c, d, a2, b, M_offset_6, 15, T[58]); b = II(b, c, d, a2, M_offset_13, 21, T[59]); a2 = II(a2, b, c, d, M_offset_4, 6, T[60]); d = II(d, a2, b, c, M_offset_11, 10, T[61]); c = II(c, d, a2, b, M_offset_2, 15, T[62]); b = II(b, c, d, a2, M_offset_9, 21, T[63]); H[0] = H[0] + a2 | 0; H[1] = H[1] + b | 0; H[2] = H[2] + c | 0; H[3] = H[3] + d | 0; }, _doFinalize: function() { var data = this._data; var dataWords2 = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; dataWords2[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32; var nBitsTotalH = Math2.floor(nBitsTotal / 4294967296); var nBitsTotalL = nBitsTotal; dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 15] = (nBitsTotalH << 8 | nBitsTotalH >>> 24) & 16711935 | (nBitsTotalH << 24 | nBitsTotalH >>> 8) & 4278255360; dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotalL << 8 | nBitsTotalL >>> 24) & 16711935 | (nBitsTotalL << 24 | nBitsTotalL >>> 8) & 4278255360; data.sigBytes = (dataWords2.length + 1) * 4; this._process(); var hash = this._hash; var H = hash.words; for (var i = 0; i < 4; i++) { var H_i = H[i]; H[i] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360; } return hash; }, clone: function() { var clone2 = Hasher.clone.call(this); clone2._hash = this._hash.clone(); return clone2; } }); function FF(a2, b, c, d, x, s, t) { var n = a2 + (b & c | ~b & d) + x + t; return (n << s | n >>> 32 - s) + b; } function GG(a2, b, c, d, x, s, t) { var n = a2 + (b & d | c & ~d) + x + t; return (n << s | n >>> 32 - s) + b; } function HH(a2, b, c, d, x, s, t) { var n = a2 + (b ^ c ^ d) + x + t; return (n << s | n >>> 32 - s) + b; } function II(a2, b, c, d, x, s, t) { var n = a2 + (c ^ (b | ~d)) + x + t; return (n << s | n >>> 32 - s) + b; } C.MD5 = Hasher._createHelper(MD52); C.HmacMD5 = Hasher._createHmacHelper(MD52); })(Math); return CryptoJS.MD5; }); } }); // node_modules/crypto-js/sha1.js var require_sha1 = __commonJS({ "node_modules/crypto-js/sha1.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; var W = []; var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function() { this._hash = new WordArray.init([ 1732584193, 4023233417, 2562383102, 271733878, 3285377520 ]); }, _doProcessBlock: function(M, offset) { var H = this._hash.words; var a2 = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = n << 1 | n >>> 31; } var t = (a2 << 5 | a2 >>> 27) + e + W[i]; if (i < 20) { t += (b & c | ~b & d) + 1518500249; } else if (i < 40) { t += (b ^ c ^ d) + 1859775393; } else if (i < 60) { t += (b & c | b & d | c & d) - 1894007588; } else { t += (b ^ c ^ d) - 899497514; } e = d; d = c; c = b << 30 | b >>> 2; b = a2; a2 = t; } H[0] = H[0] + a2 | 0; H[1] = H[1] + b | 0; H[2] = H[2] + c | 0; H[3] = H[3] + d | 0; H[4] = H[4] + e | 0; }, _doFinalize: function() { var data = this._data; var dataWords2 = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; dataWords2[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32; dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math.floor(nBitsTotal / 4294967296); dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal; data.sigBytes = dataWords2.length * 4; this._process(); return this._hash; }, clone: function() { var clone2 = Hasher.clone.call(this); clone2._hash = this._hash.clone(); return clone2; } }); C.SHA1 = Hasher._createHelper(SHA1); C.HmacSHA1 = Hasher._createHmacHelper(SHA1); })(); return CryptoJS.SHA1; }); } }); // node_modules/crypto-js/sha256.js var require_sha256 = __commonJS({ "node_modules/crypto-js/sha256.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function(Math2) { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; var H = []; var K = []; (function() { function isPrime(n2) { var sqrtN = Math2.sqrt(n2); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n2 % factor)) { return false; } } return true; } function getFractionalBits(n2) { return (n2 - (n2 | 0)) * 4294967296 | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math2.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math2.pow(n, 1 / 3)); nPrime++; } n++; } })(); var W = []; var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function() { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function(M, offset) { var H2 = this._hash.words; var a2 = H2[0]; var b = H2[1]; var c = H2[2]; var d = H2[3]; var e = H2[4]; var f = H2[5]; var g = H2[6]; var h2 = H2[7]; for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = (gamma0x << 25 | gamma0x >>> 7) ^ (gamma0x << 14 | gamma0x >>> 18) ^ gamma0x >>> 3; var gamma1x = W[i - 2]; var gamma1 = (gamma1x << 15 | gamma1x >>> 17) ^ (gamma1x << 13 | gamma1x >>> 19) ^ gamma1x >>> 10; W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = e & f ^ ~e & g; var maj = a2 & b ^ a2 & c ^ b & c; var sigma0 = (a2 << 30 | a2 >>> 2) ^ (a2 << 19 | a2 >>> 13) ^ (a2 << 10 | a2 >>> 22); var sigma1 = (e << 26 | e >>> 6) ^ (e << 21 | e >>> 11) ^ (e << 7 | e >>> 25); var t1 = h2 + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h2 = g; g = f; f = e; e = d + t1 | 0; d = c; c = b; b = a2; a2 = t1 + t2 | 0; } H2[0] = H2[0] + a2 | 0; H2[1] = H2[1] + b | 0; H2[2] = H2[2] + c | 0; H2[3] = H2[3] + d | 0; H2[4] = H2[4] + e | 0; H2[5] = H2[5] + f | 0; H2[6] = H2[6] + g | 0; H2[7] = H2[7] + h2 | 0; }, _doFinalize: function() { var data = this._data; var dataWords2 = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; dataWords2[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32; dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 14] = Math2.floor(nBitsTotal / 4294967296); dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 15] = nBitsTotal; data.sigBytes = dataWords2.length * 4; this._process(); return this._hash; }, clone: function() { var clone2 = Hasher.clone.call(this); clone2._hash = this._hash.clone(); return clone2; } }); C.SHA256 = Hasher._createHelper(SHA256); C.HmacSHA256 = Hasher._createHmacHelper(SHA256); })(Math); return CryptoJS.SHA256; }); } }); // node_modules/crypto-js/sha224.js var require_sha224 = __commonJS({ "node_modules/crypto-js/sha224.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_sha256()); } else if (typeof define === "function" && define.amd) { define(["./core", "./sha256"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function() { this._hash = new WordArray.init([ 3238371032, 914150663, 812702999, 4144912697, 4290775857, 1750603025, 1694076839, 3204075428 ]); }, _doFinalize: function() { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); C.SHA224 = SHA256._createHelper(SHA224); C.HmacSHA224 = SHA256._createHmacHelper(SHA224); })(); return CryptoJS.SHA224; }); } }); // node_modules/crypto-js/sha512.js var require_sha512 = __commonJS({ "node_modules/crypto-js/sha512.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_x64_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./x64-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } var K = [ X64Word_create(1116352408, 3609767458), X64Word_create(1899447441, 602891725), X64Word_create(3049323471, 3964484399), X64Word_create(3921009573, 2173295548), X64Word_create(961987163, 4081628472), X64Word_create(1508970993, 3053834265), X64Word_create(2453635748, 2937671579), X64Word_create(2870763221, 3664609560), X64Word_create(3624381080, 2734883394), X64Word_create(310598401, 1164996542), X64Word_create(607225278, 1323610764), X64Word_create(1426881987, 3590304994), X64Word_create(1925078388, 4068182383), X64Word_create(2162078206, 991336113), X64Word_create(2614888103, 633803317), X64Word_create(3248222580, 3479774868), X64Word_create(3835390401, 2666613458), X64Word_create(4022224774, 944711139), X64Word_create(264347078, 2341262773), X64Word_create(604807628, 2007800933), X64Word_create(770255983, 1495990901), X64Word_create(1249150122, 1856431235), X64Word_create(1555081692, 3175218132), X64Word_create(1996064986, 2198950837), X64Word_create(2554220882, 3999719339), X64Word_create(2821834349, 766784016), X64Word_create(2952996808, 2566594879), X64Word_create(3210313671, 3203337956), X64Word_create(3336571891, 1034457026), X64Word_create(3584528711, 2466948901), X64Word_create(113926993, 3758326383), X64Word_create(338241895, 168717936), X64Word_create(666307205, 1188179964), X64Word_create(773529912, 1546045734), X64Word_create(1294757372, 1522805485), X64Word_create(1396182291, 2643833823), X64Word_create(1695183700, 2343527390), X64Word_create(1986661051, 1014477480), X64Word_create(2177026350, 1206759142), X64Word_create(2456956037, 344077627), X64Word_create(2730485921, 1290863460), X64Word_create(2820302411, 3158454273), X64Word_create(3259730800, 3505952657), X64Word_create(3345764771, 106217008), X64Word_create(3516065817, 3606008344), X64Word_create(3600352804, 1432725776), X64Word_create(4094571909, 1467031594), X64Word_create(275423344, 851169720), X64Word_create(430227734, 3100823752), X64Word_create(506948616, 1363258195), X64Word_create(659060556, 3750685593), X64Word_create(883997877, 3785050280), X64Word_create(958139571, 3318307427), X64Word_create(1322822218, 3812723403), X64Word_create(1537002063, 2003034995), X64Word_create(1747873779, 3602036899), X64Word_create(1955562222, 1575990012), X64Word_create(2024104815, 1125592928), X64Word_create(2227730452, 2716904306), X64Word_create(2361852424, 442776044), X64Word_create(2428436474, 593698344), X64Word_create(2756734187, 3733110249), X64Word_create(3204031479, 2999351573), X64Word_create(3329325298, 3815920427), X64Word_create(3391569614, 3928383900), X64Word_create(3515267271, 566280711), X64Word_create(3940187606, 3454069534), X64Word_create(4118630271, 4000239992), X64Word_create(116418474, 1914138554), X64Word_create(174292421, 2731055270), X64Word_create(289380356, 3203993006), X64Word_create(460393269, 320620315), X64Word_create(685471733, 587496836), X64Word_create(852142971, 1086792851), X64Word_create(1017036298, 365543100), X64Word_create(1126000580, 2618297676), X64Word_create(1288033470, 3409855158), X64Word_create(1501505948, 4234509866), X64Word_create(1607167915, 987167468), X64Word_create(1816402316, 1246189591) ]; var W = []; (function() { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } })(); var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function() { this._hash = new X64WordArray.init([ new X64Word.init(1779033703, 4089235720), new X64Word.init(3144134277, 2227873595), new X64Word.init(1013904242, 4271175723), new X64Word.init(2773480762, 1595750129), new X64Word.init(1359893119, 2917565137), new X64Word.init(2600822924, 725511199), new X64Word.init(528734635, 4215389547), new X64Word.init(1541459225, 327033209) ]); }, _doProcessBlock: function(M, offset) { var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; for (var i = 0; i < 80; i++) { var Wil; var Wih; var Wi = W[i]; if (i < 16) { Wih = Wi.high = M[offset + i * 2] | 0; Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = (gamma0xh >>> 1 | gamma0xl << 31) ^ (gamma0xh >>> 8 | gamma0xl << 24) ^ gamma0xh >>> 7; var gamma0l = (gamma0xl >>> 1 | gamma0xh << 31) ^ (gamma0xl >>> 8 | gamma0xh << 24) ^ (gamma0xl >>> 7 | gamma0xh << 25); var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = (gamma1xh >>> 19 | gamma1xl << 13) ^ (gamma1xh << 3 | gamma1xl >>> 29) ^ gamma1xh >>> 6; var gamma1l = (gamma1xl >>> 19 | gamma1xh << 13) ^ (gamma1xl << 3 | gamma1xh >>> 29) ^ (gamma1xl >>> 6 | gamma1xh << 26); var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; Wil = gamma0l + Wi7l; Wih = gamma0h + Wi7h + (Wil >>> 0 < gamma0l >>> 0 ? 1 : 0); Wil = Wil + gamma1l; Wih = Wih + gamma1h + (Wil >>> 0 < gamma1l >>> 0 ? 1 : 0); Wil = Wil + Wi16l; Wih = Wih + Wi16h + (Wil >>> 0 < Wi16l >>> 0 ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = eh & fh ^ ~eh & gh; var chl = el & fl ^ ~el & gl; var majh = ah & bh ^ ah & ch ^ bh & ch; var majl = al & bl ^ al & cl ^ bl & cl; var sigma0h = (ah >>> 28 | al << 4) ^ (ah << 30 | al >>> 2) ^ (ah << 25 | al >>> 7); var sigma0l = (al >>> 28 | ah << 4) ^ (al << 30 | ah >>> 2) ^ (al << 25 | ah >>> 7); var sigma1h = (eh >>> 14 | el << 18) ^ (eh >>> 18 | el << 14) ^ (eh << 23 | el >>> 9); var sigma1l = (el >>> 14 | eh << 18) ^ (el >>> 18 | eh << 14) ^ (el << 23 | eh >>> 9); var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + (t1l >>> 0 < hl >>> 0 ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + (t1l >>> 0 < chl >>> 0 ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + (t1l >>> 0 < Kil >>> 0 ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + (t1l >>> 0 < Wil >>> 0 ? 1 : 0); var t2l = sigma0l + majl; var t2h = sigma0h + majh + (t2l >>> 0 < sigma0l >>> 0 ? 1 : 0); hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = dl + t1l | 0; eh = dh + t1h + (el >>> 0 < dl >>> 0 ? 1 : 0) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = t1l + t2l | 0; ah = t1h + t2h + (al >>> 0 < t1l >>> 0 ? 1 : 0) | 0; } H0l = H0.low = H0l + al; H0.high = H0h + ah + (H0l >>> 0 < al >>> 0 ? 1 : 0); H1l = H1.low = H1l + bl; H1.high = H1h + bh + (H1l >>> 0 < bl >>> 0 ? 1 : 0); H2l = H2.low = H2l + cl; H2.high = H2h + ch + (H2l >>> 0 < cl >>> 0 ? 1 : 0); H3l = H3.low = H3l + dl; H3.high = H3h + dh + (H3l >>> 0 < dl >>> 0 ? 1 : 0); H4l = H4.low = H4l + el; H4.high = H4h + eh + (H4l >>> 0 < el >>> 0 ? 1 : 0); H5l = H5.low = H5l + fl; H5.high = H5h + fh + (H5l >>> 0 < fl >>> 0 ? 1 : 0); H6l = H6.low = H6l + gl; H6.high = H6h + gh + (H6l >>> 0 < gl >>> 0 ? 1 : 0); H7l = H7.low = H7l + hl; H7.high = H7h + hh + (H7l >>> 0 < hl >>> 0 ? 1 : 0); }, _doFinalize: function() { var data = this._data; var dataWords2 = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; dataWords2[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32; dataWords2[(nBitsLeft + 128 >>> 10 << 5) + 30] = Math.floor(nBitsTotal / 4294967296); dataWords2[(nBitsLeft + 128 >>> 10 << 5) + 31] = nBitsTotal; data.sigBytes = dataWords2.length * 4; this._process(); var hash = this._hash.toX32(); return hash; }, clone: function() { var clone2 = Hasher.clone.call(this); clone2._hash = this._hash.clone(); return clone2; }, blockSize: 1024 / 32 }); C.SHA512 = Hasher._createHelper(SHA512); C.HmacSHA512 = Hasher._createHmacHelper(SHA512); })(); return CryptoJS.SHA512; }); } }); // node_modules/crypto-js/sha384.js var require_sha384 = __commonJS({ "node_modules/crypto-js/sha384.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_x64_core(), require_sha512()); } else if (typeof define === "function" && define.amd) { define(["./core", "./x64-core", "./sha512"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function() { this._hash = new X64WordArray.init([ new X64Word.init(3418070365, 3238371032), new X64Word.init(1654270250, 914150663), new X64Word.init(2438529370, 812702999), new X64Word.init(355462360, 4144912697), new X64Word.init(1731405415, 4290775857), new X64Word.init(2394180231, 1750603025), new X64Word.init(3675008525, 1694076839), new X64Word.init(1203062813, 3204075428) ]); }, _doFinalize: function() { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); C.SHA384 = SHA512._createHelper(SHA384); C.HmacSHA384 = SHA512._createHmacHelper(SHA384); })(); return CryptoJS.SHA384; }); } }); // node_modules/crypto-js/sha3.js var require_sha3 = __commonJS({ "node_modules/crypto-js/sha3.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_x64_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./x64-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function(Math2) { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; (function() { var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = (t + 1) * (t + 2) / 2 % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + (2 * x + 3 * y) % 5 * 5; } } var LFSR = 1; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 1) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else { roundConstantMsw ^= 1 << bitPosition - 32; } } if (LFSR & 128) { LFSR = LFSR << 1 ^ 113; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } })(); var T = []; (function() { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } })(); var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function() { var state = this._state = []; for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function(M, offset) { var state = this._state; var nBlockSizeLanes = this.blockSize / 2; for (var i = 0; i < nBlockSizeLanes; i++) { var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; M2i = (M2i << 8 | M2i >>> 24) & 16711935 | (M2i << 24 | M2i >>> 8) & 4278255360; M2i1 = (M2i1 << 8 | M2i1 >>> 24) & 16711935 | (M2i1 << 24 | M2i1 >>> 8) & 4278255360; var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } for (var round = 0; round < 24; round++) { for (var x = 0; x < 5; x++) { var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; var tMsw = Tx4.high ^ (Tx1Msw << 1 | Tx1Lsw >>> 31); var tLsw = Tx4.low ^ (Tx1Lsw << 1 | Tx1Msw >>> 31); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } for (var laneIndex = 1; laneIndex < 25; laneIndex++) { var tMsw; var tLsw; var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; if (rhoOffset < 32) { tMsw = laneMsw << rhoOffset | laneLsw >>> 32 - rhoOffset; tLsw = laneLsw << rhoOffset | laneMsw >>> 32 - rhoOffset; } else { tMsw = laneLsw << rhoOffset - 32 | laneMsw >>> 64 - rhoOffset; tLsw = laneMsw << rhoOffset - 32 | laneLsw >>> 64 - rhoOffset; } var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[(x + 1) % 5 + 5 * y]; var Tx2Lane = T[(x + 2) % 5 + 5 * y]; lane.high = TLane.high ^ ~Tx1Lane.high & Tx2Lane.high; lane.low = TLane.low ^ ~Tx1Lane.low & Tx2Lane.low; } } var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low; } }, _doFinalize: function() { var data = this._data; var dataWords2 = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; dataWords2[nBitsLeft >>> 5] |= 1 << 24 - nBitsLeft % 32; dataWords2[(Math2.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits >>> 5) - 1] |= 128; data.sigBytes = dataWords2.length * 4; this._process(); var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; laneMsw = (laneMsw << 8 | laneMsw >>> 24) & 16711935 | (laneMsw << 24 | laneMsw >>> 8) & 4278255360; laneLsw = (laneLsw << 8 | laneLsw >>> 24) & 16711935 | (laneLsw << 24 | laneLsw >>> 8) & 4278255360; hashWords.push(laneLsw); hashWords.push(laneMsw); } return new WordArray.init(hashWords, outputLengthBytes); }, clone: function() { var clone2 = Hasher.clone.call(this); var state = clone2._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone2; } }); C.SHA3 = Hasher._createHelper(SHA3); C.HmacSHA3 = Hasher._createHmacHelper(SHA3); })(Math); return CryptoJS.SHA3; }); } }); // node_modules/crypto-js/ripemd160.js var require_ripemd160 = __commonJS({ "node_modules/crypto-js/ripemd160.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function(Math2) { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 ]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 ]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([0, 1518500249, 1859775393, 2400959708, 2840853838]); var _hr = WordArray.create([1352829926, 1548603684, 1836072691, 2053994217, 0]); var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function() { this._hash = WordArray.create([1732584193, 4023233417, 2562383102, 271733878, 3285377520]); }, _doProcessBlock: function(M, offset) { for (var i = 0; i < 16; i++) { var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = (M_offset_i << 8 | M_offset_i >>> 24) & 16711935 | (M_offset_i << 24 | M_offset_i >>> 8) & 4278255360; } var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; var t; for (var i = 0; i < 80; i += 1) { t = al + M[offset + zl[i]] | 0; if (i < 16) { t += f1(bl, cl, dl) + hl[0]; } else if (i < 32) { t += f2(bl, cl, dl) + hl[1]; } else if (i < 48) { t += f3(bl, cl, dl) + hl[2]; } else if (i < 64) { t += f4(bl, cl, dl) + hl[3]; } else { t += f5(bl, cl, dl) + hl[4]; } t = t | 0; t = rotl(t, sl[i]); t = t + el | 0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = ar + M[offset + zr[i]] | 0; if (i < 16) { t += f5(br, cr, dr) + hr[0]; } else if (i < 32) { t += f4(br, cr, dr) + hr[1]; } else if (i < 48) { t += f3(br, cr, dr) + hr[2]; } else if (i < 64) { t += f2(br, cr, dr) + hr[3]; } else { t += f1(br, cr, dr) + hr[4]; } t = t | 0; t = rotl(t, sr[i]); t = t + er | 0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } t = H[1] + cl + dr | 0; H[1] = H[2] + dl + er | 0; H[2] = H[3] + el + ar | 0; H[3] = H[4] + al + br | 0; H[4] = H[0] + bl + cr | 0; H[0] = t; }, _doFinalize: function() { var data = this._data; var dataWords2 = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; dataWords2[nBitsLeft >>> 5] |= 128 << 24 - nBitsLeft % 32; dataWords2[(nBitsLeft + 64 >>> 9 << 4) + 14] = (nBitsTotal << 8 | nBitsTotal >>> 24) & 16711935 | (nBitsTotal << 24 | nBitsTotal >>> 8) & 4278255360; data.sigBytes = (dataWords2.length + 1) * 4; this._process(); var hash = this._hash; var H = hash.words; for (var i = 0; i < 5; i++) { var H_i = H[i]; H[i] = (H_i << 8 | H_i >>> 24) & 16711935 | (H_i << 24 | H_i >>> 8) & 4278255360; } return hash; }, clone: function() { var clone2 = Hasher.clone.call(this); clone2._hash = this._hash.clone(); return clone2; } }); function f1(x, y, z) { return x ^ y ^ z; } function f2(x, y, z) { return x & y | ~x & z; } function f3(x, y, z) { return (x | ~y) ^ z; } function f4(x, y, z) { return x & z | y & ~z; } function f5(x, y, z) { return x ^ (y | ~z); } function rotl(x, n) { return x << n | x >>> 32 - n; } C.RIPEMD160 = Hasher._createHelper(RIPEMD160); C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); })(Math); return CryptoJS.RIPEMD160; }); } }); // node_modules/crypto-js/hmac.js var require_hmac = __commonJS({ "node_modules/crypto-js/hmac.js"(exports, module2) { (function(root2, factory) { if (typeof exports === "object") { module2.exports = exports = factory(require_core()); } else if (typeof define === "function" && define.amd) { define(["./core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function(hasher, key) { hasher = this._hasher = new hasher.init(); if (typeof key == "string") { key = Utf8.parse(key); } var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } key.clamp(); var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); var oKeyWords = oKey.words; var iKeyWords = iKey.words; for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 1549556828; iKeyWords[i] ^= 909522486; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function() { var hasher = this._hasher; hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function(messageUpdate) { this._hasher.update(messageUpdate); return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function(messageUpdate) { var hasher = this._hasher; var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); })(); }); } }); // node_modules/crypto-js/pbkdf2.js var require_pbkdf2 = __commonJS({ "node_modules/crypto-js/pbkdf2.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_sha1(), require_hmac()); } else if (typeof define === "function" && define.amd) { define(["./core", "./sha1", "./hmac"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128 / 32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function(cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function(password, salt) { var cfg = this.cfg; var hmac = HMAC.create(cfg.hasher, password); var derivedKey = WordArray.create(); var blockIndex = WordArray.create([1]); var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); var blockWords = block.words; var blockWordsLength = blockWords.length; var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); var intermediateWords = intermediate.words; for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); C.PBKDF2 = function(password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; })(); return CryptoJS.PBKDF2; }); } }); // node_modules/crypto-js/evpkdf.js var require_evpkdf = __commonJS({ "node_modules/crypto-js/evpkdf.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_sha1(), require_hmac()); } else if (typeof define === "function" && define.amd) { define(["./core", "./sha1", "./hmac"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD52 = C_algo.MD5; var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128 / 32, hasher: MD52, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function(cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function(password, salt) { var block; var cfg = this.cfg; var hasher = cfg.hasher.create(); var derivedKey = WordArray.create(); var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } block = hasher.update(password).finalize(salt); hasher.reset(); for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); C.EvpKDF = function(password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; })(); return CryptoJS.EvpKDF; }); } }); // node_modules/crypto-js/cipher-core.js var require_cipher_core = __commonJS({ "node_modules/crypto-js/cipher-core.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_evpkdf()); } else if (typeof define === "function" && define.amd) { define(["./core", "./evpkdf"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.lib.Cipher || function(undefined2) { var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function(key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function(key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function(xformMode, key, cfg) { this.cfg = this.cfg.extend(cfg); this._xformMode = xformMode; this._key = key; this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function() { BufferedBlockAlgorithm.reset.call(this); this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function(dataUpdate) { this._append(dataUpdate); return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function(dataUpdate) { if (dataUpdate) { this._append(dataUpdate); } var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128 / 32, ivSize: 128 / 32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: function() { function selectCipherStrategy(key) { if (typeof key == "string") { return PasswordBasedCipher; } else { return SerializableCipher; } } return function(cipher) { return { encrypt: function(message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function(ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }() }); var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function() { var finalProcessedBlocks = this._process(true); return finalProcessedBlocks; }, blockSize: 1 }); var C_mode = C.mode = {}; var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function(cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function(cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function(cipher, iv) { this._cipher = cipher; this._iv = iv; } }); var CBC = C_mode.CBC = function() { var CBC2 = BlockCipherMode.extend(); CBC2.Encryptor = CBC2.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); this._prevBlock = words.slice(offset, offset + blockSize); } }); CBC2.Decryptor = CBC2.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; var thisBlock = words.slice(offset, offset + blockSize); cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { var block; var iv = this._iv; if (iv) { block = iv; this._iv = undefined2; } else { block = this._prevBlock; } for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC2; }(); var C_pad = C.pad = {}; var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function(data, blockSize) { var blockSizeBytes = blockSize * 4; var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; var paddingWord = nPaddingBytes << 24 | nPaddingBytes << 16 | nPaddingBytes << 8 | nPaddingBytes; var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function(data) { var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255; data.sigBytes -= nPaddingBytes; } }; var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function() { var modeCreator; Cipher.reset.call(this); var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; if (this._xformMode == this._ENC_XFORM_MODE) { modeCreator = mode.createEncryptor; } else { modeCreator = mode.createDecryptor; this._minBufferSize = 1; } if (this._mode && this._mode.__creator == modeCreator) { this._mode.init(this, iv && iv.words); } else { this._mode = modeCreator.call(mode, this, iv && iv.words); this._mode.__creator = modeCreator; } }, _doProcessBlock: function(words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function() { var finalProcessedBlocks; var padding = this.cfg.padding; if (this._xformMode == this._ENC_XFORM_MODE) { padding.pad(this._data, this.blockSize); finalProcessedBlocks = this._process(true); } else { finalProcessedBlocks = this._process(true); padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128 / 32 }); var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function(cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function(formatter) { return (formatter || this.formatter).stringify(this); } }); var C_format = C.format = {}; var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function(cipherParams) { var wordArray; var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; if (salt) { wordArray = WordArray.create([1398893684, 1701076831]).concat(salt).concat(ciphertext); } else { wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function(openSSLStr) { var salt; var ciphertext = Base64.parse(openSSLStr); var ciphertextWords = ciphertext.words; if (ciphertextWords[0] == 1398893684 && ciphertextWords[1] == 1701076831) { salt = WordArray.create(ciphertextWords.slice(2, 4)); ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext, salt }); } }; var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function(cipher, message, key, cfg) { cfg = this.cfg.extend(cfg); var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); var cipherCfg = encryptor.cfg; return CipherParams.create({ ciphertext, key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function(cipher, ciphertext, key, cfg) { cfg = this.cfg.extend(cfg); ciphertext = this._parse(ciphertext, cfg.format); var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function(ciphertext, format) { if (typeof ciphertext == "string") { return format.parse(ciphertext, this); } else { return ciphertext; } } }); var C_kdf = C.kdf = {}; var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function(password, keySize, ivSize, salt) { if (!salt) { salt = WordArray.random(64 / 8); } var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; return CipherParams.create({ key, iv, salt }); } }; var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function(cipher, message, password, cfg) { cfg = this.cfg.extend(cfg); var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); cfg.iv = derivedParams.iv; var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function(cipher, ciphertext, password, cfg) { cfg = this.cfg.extend(cfg); ciphertext = this._parse(ciphertext, cfg.format); var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); cfg.iv = derivedParams.iv; var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }(); }); } }); // node_modules/crypto-js/mode-cfb.js var require_mode_cfb = __commonJS({ "node_modules/crypto-js/mode-cfb.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.mode.CFB = function() { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { var keystream; var iv = this._iv; if (iv) { keystream = iv.slice(0); this._iv = void 0; } else { keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }(); return CryptoJS.mode.CFB; }); } }); // node_modules/crypto-js/mode-ctr.js var require_mode_ctr = __commonJS({ "node_modules/crypto-js/mode-ctr.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.mode.CTR = function() { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; if (iv) { counter = this._counter = iv.slice(0); this._iv = void 0; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); counter[blockSize - 1] = counter[blockSize - 1] + 1 | 0; for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }(); return CryptoJS.mode.CTR; }); } }); // node_modules/crypto-js/mode-ctr-gladman.js var require_mode_ctr_gladman = __commonJS({ "node_modules/crypto-js/mode-ctr-gladman.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.mode.CTRGladman = function() { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if ((word >> 24 & 255) === 255) { var b1 = word >> 16 & 255; var b2 = word >> 8 & 255; var b3 = word & 255; if (b1 === 255) { b1 = 0; if (b2 === 255) { b2 = 0; if (b3 === 255) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += b1 << 16; word += b2 << 8; word += b3; } else { word += 1 << 24; } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; if (iv) { counter = this._counter = iv.slice(0); this._iv = void 0; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }(); return CryptoJS.mode.CTRGladman; }); } }); // node_modules/crypto-js/mode-ofb.js var require_mode_ofb = __commonJS({ "node_modules/crypto-js/mode-ofb.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.mode.OFB = function() { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function(words, offset) { var cipher = this._cipher; var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; if (iv) { keystream = this._keystream = iv.slice(0); this._iv = void 0; } cipher.encryptBlock(keystream, 0); for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }(); return CryptoJS.mode.OFB; }); } }); // node_modules/crypto-js/mode-ecb.js var require_mode_ecb = __commonJS({ "node_modules/crypto-js/mode-ecb.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.mode.ECB = function() { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function(words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function(words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }(); return CryptoJS.mode.ECB; }); } }); // node_modules/crypto-js/pad-ansix923.js var require_pad_ansix923 = __commonJS({ "node_modules/crypto-js/pad-ansix923.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.pad.AnsiX923 = { pad: function(data, blockSize) { var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; var lastBytePos = dataSigBytes + nPaddingBytes - 1; data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << 24 - lastBytePos % 4 * 8; data.sigBytes += nPaddingBytes; }, unpad: function(data) { var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255; data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; }); } }); // node_modules/crypto-js/pad-iso10126.js var require_pad_iso10126 = __commonJS({ "node_modules/crypto-js/pad-iso10126.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.pad.Iso10126 = { pad: function(data, blockSize) { var blockSizeBytes = blockSize * 4; var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function(data) { var nPaddingBytes = data.words[data.sigBytes - 1 >>> 2] & 255; data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; }); } }); // node_modules/crypto-js/pad-iso97971.js var require_pad_iso97971 = __commonJS({ "node_modules/crypto-js/pad-iso97971.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.pad.Iso97971 = { pad: function(data, blockSize) { data.concat(CryptoJS.lib.WordArray.create([2147483648], 1)); CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function(data) { CryptoJS.pad.ZeroPadding.unpad(data); data.sigBytes--; } }; return CryptoJS.pad.Iso97971; }); } }); // node_modules/crypto-js/pad-zeropadding.js var require_pad_zeropadding = __commonJS({ "node_modules/crypto-js/pad-zeropadding.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.pad.ZeroPadding = { pad: function(data, blockSize) { var blockSizeBytes = blockSize * 4; data.clamp(); data.sigBytes += blockSizeBytes - (data.sigBytes % blockSizeBytes || blockSizeBytes); }, unpad: function(data) { var dataWords2 = data.words; var i = data.sigBytes - 1; for (var i = data.sigBytes - 1; i >= 0; i--) { if (dataWords2[i >>> 2] >>> 24 - i % 4 * 8 & 255) { data.sigBytes = i + 1; break; } } } }; return CryptoJS.pad.ZeroPadding; }); } }); // node_modules/crypto-js/pad-nopadding.js var require_pad_nopadding = __commonJS({ "node_modules/crypto-js/pad-nopadding.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { CryptoJS.pad.NoPadding = { pad: function() { }, unpad: function() { } }; return CryptoJS.pad.NoPadding; }); } }); // node_modules/crypto-js/format-hex.js var require_format_hex = __commonJS({ "node_modules/crypto-js/format-hex.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function(undefined2) { var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function(cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function(input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext }); } }; })(); return CryptoJS.format.Hex; }); } }); // node_modules/crypto-js/aes.js var require_aes = __commonJS({ "node_modules/crypto-js/aes.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; (function() { var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = i << 1 ^ 283; } } var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { var sx = xi ^ xi << 1 ^ xi << 2 ^ xi << 3 ^ xi << 4; sx = sx >>> 8 ^ sx & 255 ^ 99; SBOX[x] = sx; INV_SBOX[sx] = x; var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; var t = d[sx] * 257 ^ sx * 16843008; SUB_MIX_0[x] = t << 24 | t >>> 8; SUB_MIX_1[x] = t << 16 | t >>> 16; SUB_MIX_2[x] = t << 8 | t >>> 24; SUB_MIX_3[x] = t; var t = x8 * 16843009 ^ x4 * 65537 ^ x2 * 257 ^ x * 16843008; INV_SUB_MIX_0[sx] = t << 24 | t >>> 8; INV_SUB_MIX_1[sx] = t << 16 | t >>> 16; INV_SUB_MIX_2[sx] = t << 8 | t >>> 24; INV_SUB_MIX_3[sx] = t; if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } })(); var RCON = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54]; var AES = C_algo.AES = BlockCipher.extend({ _doReset: function() { var t; if (this._nRounds && this._keyPriorReset === this._key) { return; } var key = this._keyPriorReset = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; var nRounds = this._nRounds = keySize + 6; var ksRows = (nRounds + 1) * 4; var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { t = t << 8 | t >>> 24; t = SBOX[t >>> 24] << 24 | SBOX[t >>> 16 & 255] << 16 | SBOX[t >>> 8 & 255] << 8 | SBOX[t & 255]; t ^= RCON[ksRow / keySize | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { t = SBOX[t >>> 24] << 24 | SBOX[t >>> 16 & 255] << 16 | SBOX[t >>> 8 & 255] << 8 | SBOX[t & 255]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[t >>> 16 & 255]] ^ INV_SUB_MIX_2[SBOX[t >>> 8 & 255]] ^ INV_SUB_MIX_3[SBOX[t & 255]]; } } }, encryptBlock: function(M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function(M, offset) { var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function(M, offset, keySchedule, SUB_MIX_02, SUB_MIX_12, SUB_MIX_22, SUB_MIX_32, SBOX2) { var nRounds = this._nRounds; var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; var ksRow = 4; for (var round = 1; round < nRounds; round++) { var t0 = SUB_MIX_02[s0 >>> 24] ^ SUB_MIX_12[s1 >>> 16 & 255] ^ SUB_MIX_22[s2 >>> 8 & 255] ^ SUB_MIX_32[s3 & 255] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_02[s1 >>> 24] ^ SUB_MIX_12[s2 >>> 16 & 255] ^ SUB_MIX_22[s3 >>> 8 & 255] ^ SUB_MIX_32[s0 & 255] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_02[s2 >>> 24] ^ SUB_MIX_12[s3 >>> 16 & 255] ^ SUB_MIX_22[s0 >>> 8 & 255] ^ SUB_MIX_32[s1 & 255] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_02[s3 >>> 24] ^ SUB_MIX_12[s0 >>> 16 & 255] ^ SUB_MIX_22[s1 >>> 8 & 255] ^ SUB_MIX_32[s2 & 255] ^ keySchedule[ksRow++]; s0 = t0; s1 = t1; s2 = t2; s3 = t3; } var t0 = (SBOX2[s0 >>> 24] << 24 | SBOX2[s1 >>> 16 & 255] << 16 | SBOX2[s2 >>> 8 & 255] << 8 | SBOX2[s3 & 255]) ^ keySchedule[ksRow++]; var t1 = (SBOX2[s1 >>> 24] << 24 | SBOX2[s2 >>> 16 & 255] << 16 | SBOX2[s3 >>> 8 & 255] << 8 | SBOX2[s0 & 255]) ^ keySchedule[ksRow++]; var t2 = (SBOX2[s2 >>> 24] << 24 | SBOX2[s3 >>> 16 & 255] << 16 | SBOX2[s0 >>> 8 & 255] << 8 | SBOX2[s1 & 255]) ^ keySchedule[ksRow++]; var t3 = (SBOX2[s3 >>> 24] << 24 | SBOX2[s0 >>> 16 & 255] << 16 | SBOX2[s1 >>> 8 & 255] << 8 | SBOX2[s2 & 255]) ^ keySchedule[ksRow++]; M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256 / 32 }); C.AES = BlockCipher._createHelper(AES); })(); return CryptoJS.AES; }); } }); // node_modules/crypto-js/tripledes.js var require_tripledes = __commonJS({ "node_modules/crypto-js/tripledes.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; var SBOX_P = [ { 0: 8421888, 268435456: 32768, 536870912: 8421378, 805306368: 2, 1073741824: 512, 1342177280: 8421890, 1610612736: 8389122, 1879048192: 8388608, 2147483648: 514, 2415919104: 8389120, 2684354560: 33280, 2952790016: 8421376, 3221225472: 32770, 3489660928: 8388610, 3758096384: 0, 4026531840: 33282, 134217728: 0, 402653184: 8421890, 671088640: 33282, 939524096: 32768, 1207959552: 8421888, 1476395008: 512, 1744830464: 8421378, 2013265920: 2, 2281701376: 8389120, 2550136832: 33280, 2818572288: 8421376, 3087007744: 8389122, 3355443200: 8388610, 3623878656: 32770, 3892314112: 514, 4160749568: 8388608, 1: 32768, 268435457: 2, 536870913: 8421888, 805306369: 8388608, 1073741825: 8421378, 1342177281: 33280, 1610612737: 512, 1879048193: 8389122, 2147483649: 8421890, 2415919105: 8421376, 2684354561: 8388610, 2952790017: 33282, 3221225473: 514, 3489660929: 8389120, 3758096385: 32770, 4026531841: 0, 134217729: 8421890, 402653185: 8421376, 671088641: 8388608, 939524097: 512, 1207959553: 32768, 1476395009: 8388610, 1744830465: 2, 2013265921: 33282, 2281701377: 32770, 2550136833: 8389122, 2818572289: 514, 3087007745: 8421888, 3355443201: 8389120, 3623878657: 0, 3892314113: 33280, 4160749569: 8421378 }, { 0: 1074282512, 16777216: 16384, 33554432: 524288, 50331648: 1074266128, 67108864: 1073741840, 83886080: 1074282496, 100663296: 1073758208, 117440512: 16, 134217728: 540672, 150994944: 1073758224, 167772160: 1073741824, 184549376: 540688, 201326592: 524304, 218103808: 0, 234881024: 16400, 251658240: 1074266112, 8388608: 1073758208, 25165824: 540688, 41943040: 16, 58720256: 1073758224, 75497472: 1074282512, 92274688: 1073741824, 109051904: 524288, 125829120: 1074266128, 142606336: 524304, 159383552: 0, 176160768: 16384, 192937984: 1074266112, 209715200: 1073741840, 226492416: 540672, 243269632: 1074282496, 260046848: 16400, 268435456: 0, 285212672: 1074266128, 301989888: 1073758224, 318767104: 1074282496, 335544320: 1074266112, 352321536: 16, 369098752: 540688, 385875968: 16384, 402653184: 16400, 419430400: 524288, 436207616: 524304, 452984832: 1073741840, 469762048: 540672, 486539264: 1073758208, 503316480: 1073741824, 520093696: 1074282512, 276824064: 540688, 293601280: 524288, 310378496: 1074266112, 327155712: 16384, 343932928: 1073758208, 360710144: 1074282512, 377487360: 16, 394264576: 1073741824, 411041792: 1074282496, 427819008: 1073741840, 444596224: 1073758224, 461373440: 524304, 478150656: 0, 494927872: 16400, 511705088: 1074266128, 528482304: 540672 }, { 0: 260, 1048576: 0, 2097152: 67109120, 3145728: 65796, 4194304: 65540, 5242880: 67108868, 6291456: 67174660, 7340032: 67174400, 8388608: 67108864, 9437184: 67174656, 10485760: 65792, 11534336: 67174404, 12582912: 67109124, 13631488: 65536, 14680064: 4, 15728640: 256, 524288: 67174656, 1572864: 67174404, 2621440: 0, 3670016: 67109120, 4718592: 67108868, 5767168: 65536, 6815744: 65540, 7864320: 260, 8912896: 4, 9961472: 256, 11010048: 67174400, 12058624: 65796, 13107200: 65792, 14155776: 67109124, 15204352: 67174660, 16252928: 67108864, 16777216: 67174656, 17825792: 65540, 18874368: 65536, 19922944: 67109120, 20971520: 256, 22020096: 67174660, 23068672: 67108868, 24117248: 0, 25165824: 67109124, 26214400: 67108864, 27262976: 4, 28311552: 65792, 29360128: 67174400, 30408704: 260, 31457280: 65796, 32505856: 67174404, 17301504: 67108864, 18350080: 260, 19398656: 67174656, 20447232: 0, 21495808: 65540, 22544384: 67109120, 23592960: 256, 24641536: 67174404, 25690112: 65536, 26738688: 67174660, 27787264: 65796, 28835840: 67108868, 29884416: 67109124, 30932992: 67174400, 31981568: 4, 33030144: 65792 }, { 0: 2151682048, 65536: 2147487808, 131072: 4198464, 196608: 2151677952, 262144: 0, 327680: 4198400, 393216: 2147483712, 458752: 4194368, 524288: 2147483648, 589824: 4194304, 655360: 64, 720896: 2147487744, 786432: 2151678016, 851968: 4160, 917504: 4096, 983040: 2151682112, 32768: 2147487808, 98304: 64, 163840: 2151678016, 229376: 2147487744, 294912: 4198400, 360448: 2151682112, 425984: 0, 491520: 2151677952, 557056: 4096, 622592: 2151682048, 688128: 4194304, 753664: 4160, 819200: 2147483648, 884736: 4194368, 950272: 4198464, 1015808: 2147483712, 1048576: 4194368, 1114112: 4198400, 1179648: 2147483712, 1245184: 0, 1310720: 4160, 1376256: 2151678016, 1441792: 2151682048, 1507328: 2147487808, 1572864: 2151682112, 1638400: 2147483648, 1703936: 2151677952, 1769472: 4198464, 1835008: 2147487744, 1900544: 4194304, 1966080: 64, 2031616: 4096, 1081344: 2151677952, 1146880: 2151682112, 1212416: 0, 1277952: 4198400, 1343488: 4194368, 1409024: 2147483648, 1474560: 2147487808, 1540096: 64, 1605632: 2147483712, 1671168: 4096, 1736704: 2147487744, 1802240: 2151678016, 1867776: 4160, 1933312: 2151682048, 1998848: 4194304, 2064384: 4198464 }, { 0: 128, 4096: 17039360, 8192: 262144, 12288: 536870912, 16384: 537133184, 20480: 16777344, 24576: 553648256, 28672: 262272, 32768: 16777216, 36864: 537133056, 40960: 536871040, 45056: 553910400, 49152: 553910272, 53248: 0, 57344: 17039488, 61440: 553648128, 2048: 17039488, 6144: 553648256, 10240: 128, 14336: 17039360, 18432: 262144, 22528: 537133184, 26624: 553910272, 30720: 536870912, 34816: 537133056, 38912: 0, 43008: 553910400, 47104: 16777344, 51200: 536871040, 55296: 553648128, 59392: 16777216, 63488: 262272, 65536: 262144, 69632: 128, 73728: 536870912, 77824: 553648256, 81920: 16777344, 86016: 553910272, 90112: 537133184, 94208: 16777216, 98304: 553910400, 102400: 553648128, 106496: 17039360, 110592: 537133056, 114688: 262272, 118784: 536871040, 122880: 0, 126976: 17039488, 67584: 553648256, 71680: 16777216, 75776: 17039360, 79872: 537133184, 83968: 536870912, 88064: 17039488, 92160: 128, 96256: 553910272, 100352: 262272, 104448: 553910400, 108544: 0, 112640: 553648128, 116736: 16777344, 120832: 262144, 124928: 537133056, 129024: 536871040 }, { 0: 268435464, 256: 8192, 512: 270532608, 768: 270540808, 1024: 268443648, 1280: 2097152, 1536: 2097160, 1792: 268435456, 2048: 0, 2304: 268443656, 2560: 2105344, 2816: 8, 3072: 270532616, 3328: 2105352, 3584: 8200, 3840: 270540800, 128: 270532608, 384: 270540808, 640: 8, 896: 2097152, 1152: 2105352, 1408: 268435464, 1664: 268443648, 1920: 8200, 2176: 2097160, 2432: 8192, 2688: 268443656, 2944: 270532616, 3200: 0, 3456: 270540800, 3712: 2105344, 3968: 268435456, 4096: 268443648, 4352: 270532616, 4608: 270540808, 4864: 8200, 5120: 2097152, 5376: 268435456, 5632: 268435464, 5888: 2105344, 6144: 2105352, 6400: 0, 6656: 8, 6912: 270532608, 7168: 8192, 7424: 268443656, 7680: 270540800, 7936: 2097160, 4224: 8, 4480: 2105344, 4736: 2097152, 4992: 268435464, 5248: 268443648, 5504: 8200, 5760: 270540808, 6016: 270532608, 6272: 270540800, 6528: 270532616, 6784: 8192, 7040: 2105352, 7296: 2097160, 7552: 0, 7808: 268435456, 8064: 268443656 }, { 0: 1048576, 16: 33555457, 32: 1024, 48: 1049601, 64: 34604033, 80: 0, 96: 1, 112: 34603009, 128: 33555456, 144: 1048577, 160: 33554433, 176: 34604032, 192: 34603008, 208: 1025, 224: 1049600, 240: 33554432, 8: 34603009, 24: 0, 40: 33555457, 56: 34604032, 72: 1048576, 88: 33554433, 104: 33554432, 120: 1025, 136: 1049601, 152: 33555456, 168: 34603008, 184: 1048577, 200: 1024, 216: 34604033, 232: 1, 248: 1049600, 256: 33554432, 272: 1048576, 288: 33555457, 304: 34603009, 320: 1048577, 336: 33555456, 352: 34604032, 368: 1049601, 384: 1025, 400: 34604033, 416: 1049600, 432: 1, 448: 0, 464: 34603008, 480: 33554433, 496: 1024, 264: 1049600, 280: 33555457, 296: 34603009, 312: 1, 328: 33554432, 344: 1048576, 360: 1025, 376: 34604032, 392: 33554433, 408: 34603008, 424: 0, 440: 34604033, 456: 1049601, 472: 1024, 488: 33555456, 504: 1048577 }, { 0: 134219808, 1: 131072, 2: 134217728, 3: 32, 4: 131104, 5: 134350880, 6: 134350848, 7: 2048, 8: 134348800, 9: 134219776, 10: 133120, 11: 134348832, 12: 2080, 13: 0, 14: 134217760, 15: 133152, 2147483648: 2048, 2147483649: 134350880, 2147483650: 134219808, 2147483651: 134217728, 2147483652: 134348800, 2147483653: 133120, 2147483654: 133152, 2147483655: 32, 2147483656: 134217760, 2147483657: 2080, 2147483658: 131104, 2147483659: 134350848, 2147483660: 0, 2147483661: 134348832, 2147483662: 134219776, 2147483663: 131072, 16: 133152, 17: 134350848, 18: 32, 19: 2048, 20: 134219776, 21: 134217760, 22: 134348832, 23: 131072, 24: 0, 25: 131104, 26: 134348800, 27: 134219808, 28: 134350880, 29: 133120, 30: 2080, 31: 134217728, 2147483664: 131072, 2147483665: 2048, 2147483666: 134348832, 2147483667: 133152, 2147483668: 32, 2147483669: 134348800, 2147483670: 134217728, 2147483671: 134219808, 2147483672: 134350880, 2147483673: 134217760, 2147483674: 134219776, 2147483675: 0, 2147483676: 133120, 2147483677: 2080, 2147483678: 131104, 2147483679: 134350848 } ]; var SBOX_MASK = [ 4160749569, 528482304, 33030144, 2064384, 129024, 8064, 504, 2147483679 ]; var DES = C_algo.DES = BlockCipher.extend({ _doReset: function() { var key = this._key; var keyWords = key.words; var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = keyWords[keyBitPos >>> 5] >>> 31 - keyBitPos % 32 & 1; } var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { var subKey = subKeys[nSubKey] = []; var bitShift = BIT_SHIFTS[nSubKey]; for (var i = 0; i < 24; i++) { subKey[i / 6 | 0] |= keyBits[(PC2[i] - 1 + bitShift) % 28] << 31 - i % 6; subKey[4 + (i / 6 | 0)] |= keyBits[28 + (PC2[i + 24] - 1 + bitShift) % 28] << 31 - i % 6; } subKey[0] = subKey[0] << 1 | subKey[0] >>> 31; for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> (i - 1) * 4 + 3; } subKey[7] = subKey[7] << 5 | subKey[7] >>> 27; } var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function(M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function(M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function(M, offset, subKeys) { this._lBlock = M[offset]; this._rBlock = M[offset + 1]; exchangeLR.call(this, 4, 252645135); exchangeLR.call(this, 16, 65535); exchangeRL.call(this, 2, 858993459); exchangeRL.call(this, 8, 16711935); exchangeLR.call(this, 1, 1431655765); for (var round = 0; round < 16; round++) { var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; exchangeLR.call(this, 1, 1431655765); exchangeRL.call(this, 8, 16711935); exchangeRL.call(this, 2, 858993459); exchangeLR.call(this, 16, 65535); exchangeLR.call(this, 4, 252645135); M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64 / 32, ivSize: 64 / 32, blockSize: 64 / 32 }); function exchangeLR(offset, mask) { var t = (this._lBlock >>> offset ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = (this._rBlock >>> offset ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } C.DES = BlockCipher._createHelper(DES); var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function() { var key = this._key; var keyWords = key.words; if (keyWords.length !== 2 && keyWords.length !== 4 && keyWords.length < 6) { throw new Error("Invalid key length - 3DES requires the key length to be 64, 128, 192 or >192."); } var key1 = keyWords.slice(0, 2); var key2 = keyWords.length < 4 ? keyWords.slice(0, 2) : keyWords.slice(2, 4); var key3 = keyWords.length < 6 ? keyWords.slice(0, 2) : keyWords.slice(4, 6); this._des1 = DES.createEncryptor(WordArray.create(key1)); this._des2 = DES.createEncryptor(WordArray.create(key2)); this._des3 = DES.createEncryptor(WordArray.create(key3)); }, encryptBlock: function(M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function(M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192 / 32, ivSize: 64 / 32, blockSize: 64 / 32 }); C.TripleDES = BlockCipher._createHelper(TripleDES); })(); return CryptoJS.TripleDES; }); } }); // node_modules/crypto-js/rc4.js var require_rc4 = __commonJS({ "node_modules/crypto-js/rc4.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function() { var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = keyWords[keyByteIndex >>> 2] >>> 24 - keyByteIndex % 4 * 8 & 255; j = (j + S[i] + keyByte) % 256; var t = S[i]; S[i] = S[j]; S[j] = t; } this._i = this._j = 0; }, _doProcessBlock: function(M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256 / 32, ivSize: 0 }); function generateKeystreamWord() { var S = this._S; var i = this._i; var j = this._j; var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << 24 - n * 8; } this._i = i; this._j = j; return keystreamWord; } C.RC4 = StreamCipher._createHelper(RC4); var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function() { RC4._doReset.call(this); for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); C.RC4Drop = StreamCipher._createHelper(RC4Drop); })(); return CryptoJS.RC4; }); } }); // node_modules/crypto-js/rabbit.js var require_rabbit = __commonJS({ "node_modules/crypto-js/rabbit.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; var S = []; var C_ = []; var G = []; var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function() { var K = this._key.words; var iv = this.cfg.iv; for (var i = 0; i < 4; i++) { K[i] = (K[i] << 8 | K[i] >>> 24) & 16711935 | (K[i] << 24 | K[i] >>> 8) & 4278255360; } var X = this._X = [ K[0], K[3] << 16 | K[2] >>> 16, K[1], K[0] << 16 | K[3] >>> 16, K[2], K[1] << 16 | K[0] >>> 16, K[3], K[2] << 16 | K[1] >>> 16 ]; var C2 = this._C = [ K[2] << 16 | K[2] >>> 16, K[0] & 4294901760 | K[1] & 65535, K[3] << 16 | K[3] >>> 16, K[1] & 4294901760 | K[2] & 65535, K[0] << 16 | K[0] >>> 16, K[2] & 4294901760 | K[3] & 65535, K[1] << 16 | K[1] >>> 16, K[3] & 4294901760 | K[0] & 65535 ]; this._b = 0; for (var i = 0; i < 4; i++) { nextState.call(this); } for (var i = 0; i < 8; i++) { C2[i] ^= X[i + 4 & 7]; } if (iv) { var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360; var i2 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360; var i1 = i0 >>> 16 | i2 & 4294901760; var i3 = i2 << 16 | i0 & 65535; C2[0] ^= i0; C2[1] ^= i1; C2[2] ^= i2; C2[3] ^= i3; C2[4] ^= i0; C2[5] ^= i1; C2[6] ^= i2; C2[7] ^= i3; for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function(M, offset) { var X = this._X; nextState.call(this); S[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16; S[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16; S[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16; S[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16; for (var i = 0; i < 4; i++) { S[i] = (S[i] << 8 | S[i] >>> 24) & 16711935 | (S[i] << 24 | S[i] >>> 8) & 4278255360; M[offset + i] ^= S[i]; } }, blockSize: 128 / 32, ivSize: 64 / 32 }); function nextState() { var X = this._X; var C2 = this._C; for (var i = 0; i < 8; i++) { C_[i] = C2[i]; } C2[0] = C2[0] + 1295307597 + this._b | 0; C2[1] = C2[1] + 3545052371 + (C2[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0; C2[2] = C2[2] + 886263092 + (C2[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0; C2[3] = C2[3] + 1295307597 + (C2[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0; C2[4] = C2[4] + 3545052371 + (C2[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0; C2[5] = C2[5] + 886263092 + (C2[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0; C2[6] = C2[6] + 1295307597 + (C2[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0; C2[7] = C2[7] + 3545052371 + (C2[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0; this._b = C2[7] >>> 0 < C_[7] >>> 0 ? 1 : 0; for (var i = 0; i < 8; i++) { var gx = X[i] + C2[i]; var ga = gx & 65535; var gb = gx >>> 16; var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb; var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0); G[i] = gh ^ gl; } X[0] = G[0] + (G[7] << 16 | G[7] >>> 16) + (G[6] << 16 | G[6] >>> 16) | 0; X[1] = G[1] + (G[0] << 8 | G[0] >>> 24) + G[7] | 0; X[2] = G[2] + (G[1] << 16 | G[1] >>> 16) + (G[0] << 16 | G[0] >>> 16) | 0; X[3] = G[3] + (G[2] << 8 | G[2] >>> 24) + G[1] | 0; X[4] = G[4] + (G[3] << 16 | G[3] >>> 16) + (G[2] << 16 | G[2] >>> 16) | 0; X[5] = G[5] + (G[4] << 8 | G[4] >>> 24) + G[3] | 0; X[6] = G[6] + (G[5] << 16 | G[5] >>> 16) + (G[4] << 16 | G[4] >>> 16) | 0; X[7] = G[7] + (G[6] << 8 | G[6] >>> 24) + G[5] | 0; } C.Rabbit = StreamCipher._createHelper(Rabbit); })(); return CryptoJS.Rabbit; }); } }); // node_modules/crypto-js/rabbit-legacy.js var require_rabbit_legacy = __commonJS({ "node_modules/crypto-js/rabbit-legacy.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_enc_base64(), require_md5(), require_evpkdf(), require_cipher_core()); } else if (typeof define === "function" && define.amd) { define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { factory(root2.CryptoJS); } })(exports, function(CryptoJS) { (function() { var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; var S = []; var C_ = []; var G = []; var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function() { var K = this._key.words; var iv = this.cfg.iv; var X = this._X = [ K[0], K[3] << 16 | K[2] >>> 16, K[1], K[0] << 16 | K[3] >>> 16, K[2], K[1] << 16 | K[0] >>> 16, K[3], K[2] << 16 | K[1] >>> 16 ]; var C2 = this._C = [ K[2] << 16 | K[2] >>> 16, K[0] & 4294901760 | K[1] & 65535, K[3] << 16 | K[3] >>> 16, K[1] & 4294901760 | K[2] & 65535, K[0] << 16 | K[0] >>> 16, K[2] & 4294901760 | K[3] & 65535, K[1] << 16 | K[1] >>> 16, K[3] & 4294901760 | K[0] & 65535 ]; this._b = 0; for (var i = 0; i < 4; i++) { nextState.call(this); } for (var i = 0; i < 8; i++) { C2[i] ^= X[i + 4 & 7]; } if (iv) { var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; var i0 = (IV_0 << 8 | IV_0 >>> 24) & 16711935 | (IV_0 << 24 | IV_0 >>> 8) & 4278255360; var i2 = (IV_1 << 8 | IV_1 >>> 24) & 16711935 | (IV_1 << 24 | IV_1 >>> 8) & 4278255360; var i1 = i0 >>> 16 | i2 & 4294901760; var i3 = i2 << 16 | i0 & 65535; C2[0] ^= i0; C2[1] ^= i1; C2[2] ^= i2; C2[3] ^= i3; C2[4] ^= i0; C2[5] ^= i1; C2[6] ^= i2; C2[7] ^= i3; for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function(M, offset) { var X = this._X; nextState.call(this); S[0] = X[0] ^ X[5] >>> 16 ^ X[3] << 16; S[1] = X[2] ^ X[7] >>> 16 ^ X[5] << 16; S[2] = X[4] ^ X[1] >>> 16 ^ X[7] << 16; S[3] = X[6] ^ X[3] >>> 16 ^ X[1] << 16; for (var i = 0; i < 4; i++) { S[i] = (S[i] << 8 | S[i] >>> 24) & 16711935 | (S[i] << 24 | S[i] >>> 8) & 4278255360; M[offset + i] ^= S[i]; } }, blockSize: 128 / 32, ivSize: 64 / 32 }); function nextState() { var X = this._X; var C2 = this._C; for (var i = 0; i < 8; i++) { C_[i] = C2[i]; } C2[0] = C2[0] + 1295307597 + this._b | 0; C2[1] = C2[1] + 3545052371 + (C2[0] >>> 0 < C_[0] >>> 0 ? 1 : 0) | 0; C2[2] = C2[2] + 886263092 + (C2[1] >>> 0 < C_[1] >>> 0 ? 1 : 0) | 0; C2[3] = C2[3] + 1295307597 + (C2[2] >>> 0 < C_[2] >>> 0 ? 1 : 0) | 0; C2[4] = C2[4] + 3545052371 + (C2[3] >>> 0 < C_[3] >>> 0 ? 1 : 0) | 0; C2[5] = C2[5] + 886263092 + (C2[4] >>> 0 < C_[4] >>> 0 ? 1 : 0) | 0; C2[6] = C2[6] + 1295307597 + (C2[5] >>> 0 < C_[5] >>> 0 ? 1 : 0) | 0; C2[7] = C2[7] + 3545052371 + (C2[6] >>> 0 < C_[6] >>> 0 ? 1 : 0) | 0; this._b = C2[7] >>> 0 < C_[7] >>> 0 ? 1 : 0; for (var i = 0; i < 8; i++) { var gx = X[i] + C2[i]; var ga = gx & 65535; var gb = gx >>> 16; var gh = ((ga * ga >>> 17) + ga * gb >>> 15) + gb * gb; var gl = ((gx & 4294901760) * gx | 0) + ((gx & 65535) * gx | 0); G[i] = gh ^ gl; } X[0] = G[0] + (G[7] << 16 | G[7] >>> 16) + (G[6] << 16 | G[6] >>> 16) | 0; X[1] = G[1] + (G[0] << 8 | G[0] >>> 24) + G[7] | 0; X[2] = G[2] + (G[1] << 16 | G[1] >>> 16) + (G[0] << 16 | G[0] >>> 16) | 0; X[3] = G[3] + (G[2] << 8 | G[2] >>> 24) + G[1] | 0; X[4] = G[4] + (G[3] << 16 | G[3] >>> 16) + (G[2] << 16 | G[2] >>> 16) | 0; X[5] = G[5] + (G[4] << 8 | G[4] >>> 24) + G[3] | 0; X[6] = G[6] + (G[5] << 16 | G[5] >>> 16) + (G[4] << 16 | G[4] >>> 16) | 0; X[7] = G[7] + (G[6] << 8 | G[6] >>> 24) + G[5] | 0; } C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); })(); return CryptoJS.RabbitLegacy; }); } }); // node_modules/crypto-js/index.js var require_crypto_js = __commonJS({ "node_modules/crypto-js/index.js"(exports, module2) { (function(root2, factory, undef) { if (typeof exports === "object") { module2.exports = exports = factory(require_core(), require_x64_core(), require_lib_typedarrays(), require_enc_utf16(), require_enc_base64(), require_enc_base64url(), require_md5(), require_sha1(), require_sha256(), require_sha224(), require_sha512(), require_sha384(), require_sha3(), require_ripemd160(), require_hmac(), require_pbkdf2(), require_evpkdf(), require_cipher_core(), require_mode_cfb(), require_mode_ctr(), require_mode_ctr_gladman(), require_mode_ofb(), require_mode_ecb(), require_pad_ansix923(), require_pad_iso10126(), require_pad_iso97971(), require_pad_zeropadding(), require_pad_nopadding(), require_format_hex(), require_aes(), require_tripledes(), require_rc4(), require_rabbit(), require_rabbit_legacy()); } else if (typeof define === "function" && define.amd) { define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./enc-base64url", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { root2.CryptoJS = factory(root2.CryptoJS); } })(exports, function(CryptoJS) { return CryptoJS; }); } }); // node_modules/decamelize/index.js var require_decamelize = __commonJS({ "node_modules/decamelize/index.js"(exports, module2) { "use strict"; module2.exports = function(str2, sep) { if (typeof str2 !== "string") { throw new TypeError("Expected a string"); } sep = typeof sep === "undefined" ? "_" : sep; return str2.replace(/([a-z\d])([A-Z])/g, "$1" + sep + "$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g, "$1" + sep + "$2").toLowerCase(); }; } }); // node_modules/langchain/node_modules/camelcase/index.js var require_camelcase = __commonJS({ "node_modules/langchain/node_modules/camelcase/index.js"(exports, module2) { "use strict"; var UPPERCASE = /[\p{Lu}]/u; var LOWERCASE = /[\p{Ll}]/u; var LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; var IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; var SEPARATORS = /[_.\- ]+/; var LEADING_SEPARATORS = new RegExp("^" + SEPARATORS.source); var SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, "gu"); var NUMBERS_AND_IDENTIFIER = new RegExp("\\d+" + IDENTIFIER.source, "gu"); var preserveCamelCase = (string3, toLowerCase, toUpperCase) => { let isLastCharLower = false; let isLastCharUpper = false; let isLastLastCharUpper = false; for (let i = 0; i < string3.length; i++) { const character = string3[i]; if (isLastCharLower && UPPERCASE.test(character)) { string3 = string3.slice(0, i) + "-" + string3.slice(i); isLastCharLower = false; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = true; i++; } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { string3 = string3.slice(0, i - 1) + "-" + string3.slice(i - 1); isLastLastCharUpper = isLastCharUpper; isLastCharUpper = false; isLastCharLower = true; } else { isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; isLastLastCharUpper = isLastCharUpper; isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; } } return string3; }; var preserveConsecutiveUppercase = (input, toLowerCase) => { LEADING_CAPITAL.lastIndex = 0; return input.replace(LEADING_CAPITAL, (m1) => toLowerCase(m1)); }; var postProcess = (input, toUpperCase) => { SEPARATORS_AND_IDENTIFIER.lastIndex = 0; NUMBERS_AND_IDENTIFIER.lastIndex = 0; return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)).replace(NUMBERS_AND_IDENTIFIER, (m) => toUpperCase(m)); }; var camelCase2 = (input, options) => { if (!(typeof input === "string" || Array.isArray(input))) { throw new TypeError("Expected the input to be `string | string[]`"); } options = { pascalCase: false, preserveConsecutiveUppercase: false, ...options }; if (Array.isArray(input)) { input = input.map((x) => x.trim()).filter((x) => x.length).join("-"); } else { input = input.trim(); } if (input.length === 0) { return ""; } const toLowerCase = options.locale === false ? (string3) => string3.toLowerCase() : (string3) => string3.toLocaleLowerCase(options.locale); const toUpperCase = options.locale === false ? (string3) => string3.toUpperCase() : (string3) => string3.toLocaleUpperCase(options.locale); if (input.length === 1) { return options.pascalCase ? toUpperCase(input) : toLowerCase(input); } const hasUpperCase = input !== toLowerCase(input); if (hasUpperCase) { input = preserveCamelCase(input, toLowerCase, toUpperCase); } input = input.replace(LEADING_SEPARATORS, ""); if (options.preserveConsecutiveUppercase) { input = preserveConsecutiveUppercase(input, toLowerCase); } else { input = toLowerCase(input); } if (options.pascalCase) { input = toUpperCase(input.charAt(0)) + input.slice(1); } return postProcess(input, toUpperCase); }; module2.exports = camelCase2; module2.exports.default = camelCase2; } }); // node_modules/langchain/dist/load/map_keys.js function keyToJson(key, map2) { return (map2 == null ? void 0 : map2[key]) || (0, import_decamelize.default)(key); } function mapKeys(fields, mapper2, map2) { const mapped = {}; for (const key in fields) { if (Object.hasOwn(fields, key)) { mapped[mapper2(key, map2)] = fields[key]; } } return mapped; } var import_decamelize, import_camelcase; var init_map_keys = __esm({ "node_modules/langchain/dist/load/map_keys.js"() { import_decamelize = __toESM(require_decamelize(), 1); import_camelcase = __toESM(require_camelcase(), 1); } }); // node_modules/langchain/dist/load/serializable.js function shallowCopy(obj) { return Array.isArray(obj) ? [...obj] : { ...obj }; } function replaceSecrets(root2, secretsMap) { const result = shallowCopy(root2); for (const [path2, secretId] of Object.entries(secretsMap)) { const [last, ...partsReverse] = path2.split(".").reverse(); let current = result; for (const part of partsReverse.reverse()) { if (current[part] === void 0) { break; } current[part] = shallowCopy(current[part]); current = current[part]; } if (current[last] !== void 0) { current[last] = { lc: 1, type: "secret", id: [secretId] }; } } return result; } var Serializable; var init_serializable = __esm({ "node_modules/langchain/dist/load/serializable.js"() { init_map_keys(); Serializable = class { /** * A map of secrets, which will be omitted from serialization. * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". * Values are the secret ids, which will be used when deserializing. */ get lc_secrets() { return void 0; } /** * A map of additional attributes to merge with constructor args. * Keys are the attribute names, e.g. "foo". * Values are the attribute values, which will be serialized. * These attributes need to be accepted by the constructor as arguments. */ get lc_attributes() { return void 0; } /** * A map of aliases for constructor args. * Keys are the attribute names, e.g. "foo". * Values are the alias that will replace the key in serialization. * This is used to eg. make argument names match Python. */ get lc_aliases() { return void 0; } constructor(kwargs, ..._args) { Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "lc_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.lc_kwargs = kwargs || {}; } toJSON() { if (!this.lc_serializable) { return this.toJSONNotImplemented(); } if ( // eslint-disable-next-line no-instanceof/no-instanceof this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs) ) { return this.toJSONNotImplemented(); } const aliases = {}; const secrets = {}; const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { acc[key] = key in this ? this[key] : this.lc_kwargs[key]; return acc; }, {}); for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); } for (const key in secrets) { if (key in this && this[key] !== void 0) { kwargs[key] = this[key] || kwargs[key]; } } return { lc: 1, type: "constructor", id: [...this.lc_namespace, this.constructor.name], kwargs: mapKeys(Object.keys(secrets).length ? replaceSecrets(kwargs, secrets) : kwargs, keyToJson, aliases) }; } toJSONNotImplemented() { return { lc: 1, type: "not_implemented", id: [...this.lc_namespace, this.constructor.name] }; } }; } }); // node_modules/langchain/dist/schema/index.js var RUN_KEY, BaseMessage, HumanMessage, AIMessage, SystemMessage, ChatMessage, BasePromptValue, BaseRetriever, BaseListChatMessageHistory; var init_schema = __esm({ "node_modules/langchain/dist/schema/index.js"() { init_serializable(); RUN_KEY = "__run"; BaseMessage = class extends Serializable { /** * @deprecated * Use {@link BaseMessage.content} instead. */ get text() { return this.content; } constructor(fields, kwargs) { if (typeof fields === "string") { fields = { content: fields, additional_kwargs: kwargs }; } super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "schema"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "content", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "additional_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.name = fields.name; this.content = fields.content; this.additional_kwargs = fields.additional_kwargs || {}; } toDict() { return { type: this._getType(), data: this.toJSON().kwargs }; } }; HumanMessage = class extends BaseMessage { _getType() { return "human"; } }; AIMessage = class extends BaseMessage { _getType() { return "ai"; } }; SystemMessage = class extends BaseMessage { _getType() { return "system"; } }; ChatMessage = class extends BaseMessage { constructor(fields, role) { if (typeof fields === "string") { fields = { content: fields, role }; } super(fields); Object.defineProperty(this, "role", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.role = fields.role; } _getType() { return "generic"; } }; BasePromptValue = class extends Serializable { }; BaseRetriever = class { }; BaseListChatMessageHistory = class extends Serializable { addUserMessage(message) { return this.addMessage(new HumanMessage(message)); } addAIChatMessage(message) { return this.addMessage(new AIMessage(message)); } }; } }); // node_modules/uuid/dist/esm-browser/rng.js function rng() { if (!getRandomValues) { getRandomValues = typeof crypto !== "undefined" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto); if (!getRandomValues) { throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); } } return getRandomValues(rnds8); } var getRandomValues, rnds8; var init_rng = __esm({ "node_modules/uuid/dist/esm-browser/rng.js"() { rnds8 = new Uint8Array(16); } }); // node_modules/uuid/dist/esm-browser/stringify.js function unsafeStringify(arr, offset = 0) { return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); } var byteToHex; var init_stringify = __esm({ "node_modules/uuid/dist/esm-browser/stringify.js"() { byteToHex = []; for (let i = 0; i < 256; ++i) { byteToHex.push((i + 256).toString(16).slice(1)); } } }); // node_modules/uuid/dist/esm-browser/native.js var randomUUID, native_default; var init_native = __esm({ "node_modules/uuid/dist/esm-browser/native.js"() { randomUUID = typeof crypto !== "undefined" && crypto.randomUUID && crypto.randomUUID.bind(crypto); native_default = { randomUUID }; } }); // node_modules/uuid/dist/esm-browser/v4.js function v4(options, buf, offset) { if (native_default.randomUUID && !buf && !options) { return native_default.randomUUID(); } options = options || {}; const rnds = options.random || (options.rng || rng)(); rnds[6] = rnds[6] & 15 | 64; rnds[8] = rnds[8] & 63 | 128; if (buf) { offset = offset || 0; for (let i = 0; i < 16; ++i) { buf[offset + i] = rnds[i]; } return buf; } return unsafeStringify(rnds); } var v4_default; var init_v4 = __esm({ "node_modules/uuid/dist/esm-browser/v4.js"() { init_native(); init_rng(); init_stringify(); v4_default = v4; } }); // node_modules/uuid/dist/esm-browser/index.js var init_esm_browser = __esm({ "node_modules/uuid/dist/esm-browser/index.js"() { init_v4(); } }); // node_modules/langchain/dist/callbacks/base.js var BaseCallbackHandlerMethodsClass, BaseCallbackHandler; var init_base = __esm({ "node_modules/langchain/dist/callbacks/base.js"() { init_esm_browser(); init_serializable(); BaseCallbackHandlerMethodsClass = class { }; BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { get lc_namespace() { return ["langchain", "callbacks", this.name]; } get lc_secrets() { return void 0; } get lc_attributes() { return void 0; } get lc_aliases() { return void 0; } constructor(input) { var _a, _b, _c, _d; super(); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "lc_kwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "ignoreLLM", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "ignoreChain", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "ignoreAgent", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "awaitHandlers", { enumerable: true, configurable: true, writable: true, value: typeof process !== "undefined" ? ( // eslint-disable-next-line no-process-env ((_a = process.env) == null ? void 0 : _a.LANGCHAIN_CALLBACKS_BACKGROUND) !== "true" ) : true }); this.lc_kwargs = input || {}; if (input) { this.ignoreLLM = (_b = input.ignoreLLM) != null ? _b : this.ignoreLLM; this.ignoreChain = (_c = input.ignoreChain) != null ? _c : this.ignoreChain; this.ignoreAgent = (_d = input.ignoreAgent) != null ? _d : this.ignoreAgent; } } copy() { return new this.constructor(this); } toJSON() { return Serializable.prototype.toJSON.call(this); } toJSONNotImplemented() { return Serializable.prototype.toJSONNotImplemented.call(this); } static fromMethods(methods) { class Handler extends BaseCallbackHandler { constructor() { super(); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: v4_default() }); Object.assign(this, methods); } } return new Handler(); } }; } }); // node_modules/langchain/node_modules/ansi-styles/index.js var require_ansi_styles = __commonJS({ "node_modules/langchain/node_modules/ansi-styles/index.js"(exports, module2) { "use strict"; var ANSI_BACKGROUND_OFFSET = 10; var wrapAnsi256 = (offset = 0) => (code2) => `\x1B[${38 + offset};5;${code2}m`; var wrapAnsi16m = (offset = 0) => (red, green, blue) => `\x1B[${38 + offset};2;${red};${green};${blue}m`; function assembleStyles() { const codes = /* @__PURE__ */ new Map(); const styles2 = { modifier: { reset: [0, 0], // 21 isn't widely supported and 22 does the same thing bold: [1, 22], dim: [2, 22], italic: [3, 23], underline: [4, 24], overline: [53, 55], inverse: [7, 27], hidden: [8, 28], strikethrough: [9, 29] }, color: { black: [30, 39], red: [31, 39], green: [32, 39], yellow: [33, 39], blue: [34, 39], magenta: [35, 39], cyan: [36, 39], white: [37, 39], // Bright color blackBright: [90, 39], redBright: [91, 39], greenBright: [92, 39], yellowBright: [93, 39], blueBright: [94, 39], magentaBright: [95, 39], cyanBright: [96, 39], whiteBright: [97, 39] }, bgColor: { bgBlack: [40, 49], bgRed: [41, 49], bgGreen: [42, 49], bgYellow: [43, 49], bgBlue: [44, 49], bgMagenta: [45, 49], bgCyan: [46, 49], bgWhite: [47, 49], // Bright color bgBlackBright: [100, 49], bgRedBright: [101, 49], bgGreenBright: [102, 49], bgYellowBright: [103, 49], bgBlueBright: [104, 49], bgMagentaBright: [105, 49], bgCyanBright: [106, 49], bgWhiteBright: [107, 49] } }; styles2.color.gray = styles2.color.blackBright; styles2.bgColor.bgGray = styles2.bgColor.bgBlackBright; styles2.color.grey = styles2.color.blackBright; styles2.bgColor.bgGrey = styles2.bgColor.bgBlackBright; for (const [groupName, group] of Object.entries(styles2)) { for (const [styleName, style] of Object.entries(group)) { styles2[styleName] = { open: `\x1B[${style[0]}m`, close: `\x1B[${style[1]}m` }; group[styleName] = styles2[styleName]; codes.set(style[0], style[1]); } Object.defineProperty(styles2, groupName, { value: group, enumerable: false }); } Object.defineProperty(styles2, "codes", { value: codes, enumerable: false }); styles2.color.close = "\x1B[39m"; styles2.bgColor.close = "\x1B[49m"; styles2.color.ansi256 = wrapAnsi256(); styles2.color.ansi16m = wrapAnsi16m(); styles2.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); styles2.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); Object.defineProperties(styles2, { rgbToAnsi256: { value: (red, green, blue) => { if (red === green && green === blue) { if (red < 8) { return 16; } if (red > 248) { return 231; } return Math.round((red - 8) / 247 * 24) + 232; } return 16 + 36 * Math.round(red / 255 * 5) + 6 * Math.round(green / 255 * 5) + Math.round(blue / 255 * 5); }, enumerable: false }, hexToRgb: { value: (hex) => { const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); if (!matches) { return [0, 0, 0]; } let { colorString } = matches.groups; if (colorString.length === 3) { colorString = colorString.split("").map((character) => character + character).join(""); } const integer = Number.parseInt(colorString, 16); return [ integer >> 16 & 255, integer >> 8 & 255, integer & 255 ]; }, enumerable: false }, hexToAnsi256: { value: (hex) => styles2.rgbToAnsi256(...styles2.hexToRgb(hex)), enumerable: false } }); return styles2; } Object.defineProperty(module2, "exports", { enumerable: true, get: assembleStyles }); } }); // node_modules/langchain/dist/callbacks/handlers/tracer.js var BaseTracer; var init_tracer = __esm({ "node_modules/langchain/dist/callbacks/handlers/tracer.js"() { init_base(); BaseTracer = class extends BaseCallbackHandler { constructor(_fields) { super(...arguments); Object.defineProperty(this, "runMap", { enumerable: true, configurable: true, writable: true, value: /* @__PURE__ */ new Map() }); } copy() { return this; } _addChildRun(parentRun, childRun) { parentRun.child_runs.push(childRun); } _startTrace(run) { if (run.parent_run_id !== void 0) { const parentRun = this.runMap.get(run.parent_run_id); if (parentRun) { this._addChildRun(parentRun, run); } } this.runMap.set(run.id, run); } async _endTrace(run) { const parentRun = run.parent_run_id !== void 0 && this.runMap.get(run.parent_run_id); if (parentRun) { parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); } else { await this.persistRun(run); } this.runMap.delete(run.id); } _getExecutionOrder(parentRunId) { const parentRun = parentRunId !== void 0 && this.runMap.get(parentRunId); if (!parentRun) { return 1; } return parentRun.child_execution_order + 1; } async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata) { var _a; const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; const run = { id: runId, name: llm.id[llm.id.length - 1], parent_run_id: parentRunId, start_time, serialized: llm, events: [ { name: "start", time: start_time } ], inputs: { prompts }, execution_order, child_runs: [], child_execution_order: execution_order, run_type: "llm", extra: finalExtraParams != null ? finalExtraParams : {}, tags: tags || [] }; this._startTrace(run); await ((_a = this.onLLMStart) == null ? void 0 : _a.call(this, run)); } async handleChatModelStart(llm, messages4, runId, parentRunId, extraParams, tags, metadata) { var _a; const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const finalExtraParams = metadata ? { ...extraParams, metadata } : extraParams; const run = { id: runId, name: llm.id[llm.id.length - 1], parent_run_id: parentRunId, start_time, serialized: llm, events: [ { name: "start", time: start_time } ], inputs: { messages: messages4 }, execution_order, child_runs: [], child_execution_order: execution_order, run_type: "llm", extra: finalExtraParams != null ? finalExtraParams : {}, tags: tags || [] }; this._startTrace(run); await ((_a = this.onLLMStart) == null ? void 0 : _a.call(this, run)); } async handleLLMEnd(output, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "llm") { throw new Error("No LLM run to end."); } run.end_time = Date.now(); run.outputs = output; run.events.push({ name: "end", time: run.end_time }); await ((_a = this.onLLMEnd) == null ? void 0 : _a.call(this, run)); await this._endTrace(run); } async handleLLMError(error, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "llm") { throw new Error("No LLM run to end."); } run.end_time = Date.now(); run.error = error.message; run.events.push({ name: "error", time: run.end_time }); await ((_a = this.onLLMError) == null ? void 0 : _a.call(this, run)); await this._endTrace(run); } async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata) { var _a; const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const run = { id: runId, name: chain.id[chain.id.length - 1], parent_run_id: parentRunId, start_time, serialized: chain, events: [ { name: "start", time: start_time } ], inputs, execution_order, child_execution_order: execution_order, run_type: "chain", child_runs: [], extra: metadata ? { metadata } : {}, tags: tags || [] }; this._startTrace(run); await ((_a = this.onChainStart) == null ? void 0 : _a.call(this, run)); } async handleChainEnd(outputs, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "chain") { throw new Error("No chain run to end."); } run.end_time = Date.now(); run.outputs = outputs; run.events.push({ name: "end", time: run.end_time }); await ((_a = this.onChainEnd) == null ? void 0 : _a.call(this, run)); await this._endTrace(run); } async handleChainError(error, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "chain") { throw new Error("No chain run to end."); } run.end_time = Date.now(); run.error = error.message; run.events.push({ name: "error", time: run.end_time }); await ((_a = this.onChainError) == null ? void 0 : _a.call(this, run)); await this._endTrace(run); } async handleToolStart(tool, input, runId, parentRunId, tags, metadata) { var _a; const execution_order = this._getExecutionOrder(parentRunId); const start_time = Date.now(); const run = { id: runId, name: tool.id[tool.id.length - 1], parent_run_id: parentRunId, start_time, serialized: tool, events: [ { name: "start", time: start_time } ], inputs: { input }, execution_order, child_execution_order: execution_order, run_type: "tool", child_runs: [], extra: metadata ? { metadata } : {}, tags: tags || [] }; this._startTrace(run); await ((_a = this.onToolStart) == null ? void 0 : _a.call(this, run)); } async handleToolEnd(output, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "tool") { throw new Error("No tool run to end"); } run.end_time = Date.now(); run.outputs = { output }; run.events.push({ name: "end", time: run.end_time }); await ((_a = this.onToolEnd) == null ? void 0 : _a.call(this, run)); await this._endTrace(run); } async handleToolError(error, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "tool") { throw new Error("No tool run to end"); } run.end_time = Date.now(); run.error = error.message; run.events.push({ name: "error", time: run.end_time }); await ((_a = this.onToolError) == null ? void 0 : _a.call(this, run)); await this._endTrace(run); } async handleAgentAction(action, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "chain") { return; } const agentRun = run; agentRun.actions = agentRun.actions || []; agentRun.actions.push(action); agentRun.events.push({ name: "agent_action", time: Date.now(), kwargs: { action } }); await ((_a = this.onAgentAction) == null ? void 0 : _a.call(this, run)); } async handleAgentEnd(action, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "chain") { return; } run.events.push({ name: "agent_end", time: Date.now(), kwargs: { action } }); await ((_a = this.onAgentEnd) == null ? void 0 : _a.call(this, run)); } async handleText(text4, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "chain") { return; } run.events.push({ name: "text", time: Date.now(), kwargs: { text: text4 } }); await ((_a = this.onText) == null ? void 0 : _a.call(this, run)); } async handleLLMNewToken(token, idx, runId) { var _a; const run = this.runMap.get(runId); if (!run || (run == null ? void 0 : run.run_type) !== "llm") { return; } run.events.push({ name: "new_token", time: Date.now(), kwargs: { token, idx } }); await ((_a = this.onLLMNewToken) == null ? void 0 : _a.call(this, run)); } }; } }); // node_modules/langchain/dist/callbacks/handlers/console.js function wrap(style, text4) { return `${style.open}${text4}${style.close}`; } function tryJsonStringify(obj, fallback) { try { return JSON.stringify(obj, null, 2); } catch (err) { return fallback; } } function elapsed(run) { if (!run.end_time) return ""; const elapsed2 = run.end_time - run.start_time; if (elapsed2 < 1e3) { return `${elapsed2}ms`; } return `${(elapsed2 / 1e3).toFixed(2)}s`; } var import_ansi_styles, color, ConsoleCallbackHandler; var init_console = __esm({ "node_modules/langchain/dist/callbacks/handlers/console.js"() { import_ansi_styles = __toESM(require_ansi_styles(), 1); init_tracer(); ({ color } = import_ansi_styles.default); ConsoleCallbackHandler = class extends BaseTracer { constructor() { super(...arguments); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "console_callback_handler" }); } persistRun(_run) { return Promise.resolve(); } // utility methods getParents(run) { const parents = []; let currentRun = run; while (currentRun.parent_run_id) { const parent = this.runMap.get(currentRun.parent_run_id); if (parent) { parents.push(parent); currentRun = parent; } else { break; } } return parents; } getBreadcrumbs(run) { const parents = this.getParents(run).reverse(); const string3 = [...parents, run].map((parent, i, arr) => { const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; return i === arr.length - 1 ? wrap(import_ansi_styles.default.bold, name) : name; }).join(" > "); return wrap(color.grey, string3); } // logging methods onChainStart(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); } onChainEnd(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); } onChainError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onLLMStart(run) { const crumbs = this.getBreadcrumbs(run); const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs; console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); } onLLMEnd(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); } onLLMError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onToolStart(run) { var _a; const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${(_a = run.inputs.input) == null ? void 0 : _a.trim()}"`); } onToolEnd(run) { var _a, _b; const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${(_b = (_a = run.outputs) == null ? void 0 : _a.output) == null ? void 0 : _b.trim()}"`); } onToolError(run) { const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); } onAgentAction(run) { const agentRun = run; const crumbs = this.getBreadcrumbs(run); console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); } }; } }); // node_modules/retry/lib/retry_operation.js var require_retry_operation = __commonJS({ "node_modules/retry/lib/retry_operation.js"(exports, module2) { function RetryOperation(timeouts, options) { if (typeof options === "boolean") { options = { forever: options }; } this._originalTimeouts = JSON.parse(JSON.stringify(timeouts)); this._timeouts = timeouts; this._options = options || {}; this._maxRetryTime = options && options.maxRetryTime || Infinity; this._fn = null; this._errors = []; this._attempts = 1; this._operationTimeout = null; this._operationTimeoutCb = null; this._timeout = null; this._operationStart = null; this._timer = null; if (this._options.forever) { this._cachedTimeouts = this._timeouts.slice(0); } } module2.exports = RetryOperation; RetryOperation.prototype.reset = function() { this._attempts = 1; this._timeouts = this._originalTimeouts.slice(0); }; RetryOperation.prototype.stop = function() { if (this._timeout) { clearTimeout(this._timeout); } if (this._timer) { clearTimeout(this._timer); } this._timeouts = []; this._cachedTimeouts = null; }; RetryOperation.prototype.retry = function(err) { if (this._timeout) { clearTimeout(this._timeout); } if (!err) { return false; } var currentTime = new Date().getTime(); if (err && currentTime - this._operationStart >= this._maxRetryTime) { this._errors.push(err); this._errors.unshift(new Error("RetryOperation timeout occurred")); return false; } this._errors.push(err); var timeout = this._timeouts.shift(); if (timeout === void 0) { if (this._cachedTimeouts) { this._errors.splice(0, this._errors.length - 1); timeout = this._cachedTimeouts.slice(-1); } else { return false; } } var self2 = this; this._timer = setTimeout(function() { self2._attempts++; if (self2._operationTimeoutCb) { self2._timeout = setTimeout(function() { self2._operationTimeoutCb(self2._attempts); }, self2._operationTimeout); if (self2._options.unref) { self2._timeout.unref(); } } self2._fn(self2._attempts); }, timeout); if (this._options.unref) { this._timer.unref(); } return true; }; RetryOperation.prototype.attempt = function(fn, timeoutOps) { this._fn = fn; if (timeoutOps) { if (timeoutOps.timeout) { this._operationTimeout = timeoutOps.timeout; } if (timeoutOps.cb) { this._operationTimeoutCb = timeoutOps.cb; } } var self2 = this; if (this._operationTimeoutCb) { this._timeout = setTimeout(function() { self2._operationTimeoutCb(); }, self2._operationTimeout); } this._operationStart = new Date().getTime(); this._fn(this._attempts); }; RetryOperation.prototype.try = function(fn) { console.log("Using RetryOperation.try() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = function(fn) { console.log("Using RetryOperation.start() is deprecated"); this.attempt(fn); }; RetryOperation.prototype.start = RetryOperation.prototype.try; RetryOperation.prototype.errors = function() { return this._errors; }; RetryOperation.prototype.attempts = function() { return this._attempts; }; RetryOperation.prototype.mainError = function() { if (this._errors.length === 0) { return null; } var counts = {}; var mainError = null; var mainErrorCount = 0; for (var i = 0; i < this._errors.length; i++) { var error = this._errors[i]; var message = error.message; var count = (counts[message] || 0) + 1; counts[message] = count; if (count >= mainErrorCount) { mainError = error; mainErrorCount = count; } } return mainError; }; } }); // node_modules/retry/lib/retry.js var require_retry = __commonJS({ "node_modules/retry/lib/retry.js"(exports) { var RetryOperation = require_retry_operation(); exports.operation = function(options) { var timeouts = exports.timeouts(options); return new RetryOperation(timeouts, { forever: options && (options.forever || options.retries === Infinity), unref: options && options.unref, maxRetryTime: options && options.maxRetryTime }); }; exports.timeouts = function(options) { if (options instanceof Array) { return [].concat(options); } var opts = { retries: 10, factor: 2, minTimeout: 1 * 1e3, maxTimeout: Infinity, randomize: false }; for (var key in options) { opts[key] = options[key]; } if (opts.minTimeout > opts.maxTimeout) { throw new Error("minTimeout is greater than maxTimeout"); } var timeouts = []; for (var i = 0; i < opts.retries; i++) { timeouts.push(this.createTimeout(i, opts)); } if (options && options.forever && !timeouts.length) { timeouts.push(this.createTimeout(i, opts)); } timeouts.sort(function(a2, b) { return a2 - b; }); return timeouts; }; exports.createTimeout = function(attempt, opts) { var random = opts.randomize ? Math.random() + 1 : 1; var timeout = Math.round(random * Math.max(opts.minTimeout, 1) * Math.pow(opts.factor, attempt)); timeout = Math.min(timeout, opts.maxTimeout); return timeout; }; exports.wrap = function(obj, options, methods) { if (options instanceof Array) { methods = options; options = null; } if (!methods) { methods = []; for (var key in obj) { if (typeof obj[key] === "function") { methods.push(key); } } } for (var i = 0; i < methods.length; i++) { var method = methods[i]; var original = obj[method]; obj[method] = function retryWrapper(original2) { var op = exports.operation(options); var args = Array.prototype.slice.call(arguments, 1); var callback = args.pop(); args.push(function(err) { if (op.retry(err)) { return; } if (err) { arguments[0] = op.mainError(); } callback.apply(this, arguments); }); op.attempt(function() { original2.apply(obj, args); }); }.bind(obj, original); obj[method].options = options; } }; } }); // node_modules/retry/index.js var require_retry2 = __commonJS({ "node_modules/retry/index.js"(exports, module2) { module2.exports = require_retry(); } }); // node_modules/p-retry/index.js var require_p_retry = __commonJS({ "node_modules/p-retry/index.js"(exports, module2) { "use strict"; var retry = require_retry2(); var networkErrorMsgs = [ "Failed to fetch", // Chrome "NetworkError when attempting to fetch resource.", // Firefox "The Internet connection appears to be offline.", // Safari "Network request failed" // `cross-fetch` ]; var AbortError = class extends Error { constructor(message) { super(); if (message instanceof Error) { this.originalError = message; ({ message } = message); } else { this.originalError = new Error(message); this.originalError.stack = this.stack; } this.name = "AbortError"; this.message = message; } }; var decorateErrorWithCounts = (error, attemptNumber, options) => { const retriesLeft = options.retries - (attemptNumber - 1); error.attemptNumber = attemptNumber; error.retriesLeft = retriesLeft; return error; }; var isNetworkError = (errorMessage) => networkErrorMsgs.includes(errorMessage); var pRetry3 = (input, options) => new Promise((resolve, reject) => { options = { onFailedAttempt: () => { }, retries: 10, ...options }; const operation = retry.operation(options); operation.attempt(async (attemptNumber) => { try { resolve(await input(attemptNumber)); } catch (error) { if (!(error instanceof Error)) { reject(new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`)); return; } if (error instanceof AbortError) { operation.stop(); reject(error.originalError); } else if (error instanceof TypeError && !isNetworkError(error.message)) { operation.stop(); reject(error); } else { decorateErrorWithCounts(error, attemptNumber, options); try { await options.onFailedAttempt(error); } catch (error2) { reject(error2); return; } if (!operation.retry(error)) { reject(operation.mainError()); } } } }); }); module2.exports = pRetry3; module2.exports.default = pRetry3; module2.exports.AbortError = AbortError; } }); // node_modules/eventemitter3/index.js var require_eventemitter3 = __commonJS({ "node_modules/eventemitter3/index.js"(exports, module2) { "use strict"; var has = Object.prototype.hasOwnProperty; var prefix = "~"; function Events() { } if (Object.create) { Events.prototype = /* @__PURE__ */ Object.create(null); if (!new Events().__proto__) prefix = false; } function EE2(fn, context, once2) { this.fn = fn; this.context = context; this.once = once2 || false; } function addListener(emitter, event, fn, context, once2) { if (typeof fn !== "function") { throw new TypeError("The listener must be a function"); } var listener = new EE2(fn, context || emitter, once2), 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; } function clearEvent(emitter, evt) { if (--emitter._eventsCount === 0) emitter._events = new Events(); else delete emitter._events[evt]; } function EventEmitter2() { this._events = new Events(); this._eventsCount = 0; } EventEmitter2.prototype.eventNames = 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; }; EventEmitter2.prototype.listeners = function listeners(event) { var evt = prefix ? prefix + event : event, handlers2 = this._events[evt]; if (!handlers2) return []; if (handlers2.fn) return [handlers2.fn]; for (var i = 0, l = handlers2.length, ee = new Array(l); i < l; i++) { ee[i] = handlers2[i].fn; } return ee; }; EventEmitter2.prototype.listenerCount = function listenerCount2(event) { var evt = prefix ? prefix + event : event, listeners = this._events[evt]; if (!listeners) return 0; if (listeners.fn) return 1; return listeners.length; }; EventEmitter2.prototype.emit = 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; }; EventEmitter2.prototype.on = function on(event, fn, context) { return addListener(this, event, fn, context, false); }; EventEmitter2.prototype.once = function once2(event, fn, context) { return addListener(this, event, fn, context, true); }; EventEmitter2.prototype.removeListener = function removeListener(event, fn, context, once2) { var evt = prefix ? prefix + event : event; if (!this._events[evt]) return this; if (!fn) { clearEvent(this, evt); return this; } var listeners = this._events[evt]; if (listeners.fn) { if (listeners.fn === fn && (!once2 || listeners.once) && (!context || listeners.context === context)) { clearEvent(this, evt); } } else { for (var i = 0, events = [], length = listeners.length; i < length; i++) { if (listeners[i].fn !== fn || once2 && !listeners[i].once || context && listeners[i].context !== context) { events.push(listeners[i]); } } if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; else clearEvent(this, evt); } return this; }; EventEmitter2.prototype.removeAllListeners = 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; }; EventEmitter2.prototype.off = EventEmitter2.prototype.removeListener; EventEmitter2.prototype.addListener = EventEmitter2.prototype.on; EventEmitter2.prefixed = prefix; EventEmitter2.EventEmitter = EventEmitter2; if ("undefined" !== typeof module2) { module2.exports = EventEmitter2; } } }); // node_modules/p-finally/index.js var require_p_finally = __commonJS({ "node_modules/p-finally/index.js"(exports, module2) { "use strict"; module2.exports = (promise, onFinally) => { onFinally = onFinally || (() => { }); return promise.then( (val) => new Promise((resolve) => { resolve(onFinally()); }).then(() => val), (err) => new Promise((resolve) => { resolve(onFinally()); }).then(() => { throw err; }) ); }; } }); // node_modules/p-timeout/index.js var require_p_timeout = __commonJS({ "node_modules/p-timeout/index.js"(exports, module2) { "use strict"; var pFinally = require_p_finally(); var TimeoutError = class extends Error { constructor(message) { super(message); this.name = "TimeoutError"; } }; var pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { if (typeof milliseconds !== "number" || milliseconds < 0) { throw new TypeError("Expected `milliseconds` to be a positive number"); } if (milliseconds === Infinity) { resolve(promise); return; } const timer = setTimeout(() => { if (typeof fallback === "function") { try { resolve(fallback()); } catch (error) { reject(error); } return; } const message = typeof fallback === "string" ? fallback : `Promise timed out after ${milliseconds} milliseconds`; const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); if (typeof promise.cancel === "function") { promise.cancel(); } reject(timeoutError); }, milliseconds); pFinally( // eslint-disable-next-line promise/prefer-await-to-then promise.then(resolve, reject), () => { clearTimeout(timer); } ); }); module2.exports = pTimeout; module2.exports.default = pTimeout; module2.exports.TimeoutError = TimeoutError; } }); // node_modules/p-queue/dist/lower-bound.js var require_lower_bound = __commonJS({ "node_modules/p-queue/dist/lower-bound.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function lowerBound(array, value, comparator) { let first = 0; let count = array.length; while (count > 0) { const step = count / 2 | 0; let it = first + step; if (comparator(array[it], value) <= 0) { first = ++it; count -= step + 1; } else { count = step; } } return first; } exports.default = lowerBound; } }); // node_modules/p-queue/dist/priority-queue.js var require_priority_queue = __commonJS({ "node_modules/p-queue/dist/priority-queue.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var lower_bound_1 = require_lower_bound(); var PriorityQueue = class { constructor() { this._queue = []; } enqueue(run, options) { options = Object.assign({ priority: 0 }, options); const element2 = { priority: options.priority, run }; if (this.size && this._queue[this.size - 1].priority >= options.priority) { this._queue.push(element2); return; } const index2 = lower_bound_1.default(this._queue, element2, (a2, b) => b.priority - a2.priority); this._queue.splice(index2, 0, element2); } dequeue() { const item = this._queue.shift(); return item === null || item === void 0 ? void 0 : item.run; } filter(options) { return this._queue.filter((element2) => element2.priority === options.priority).map((element2) => element2.run); } get size() { return this._queue.length; } }; exports.default = PriorityQueue; } }); // node_modules/p-queue/dist/index.js var require_dist = __commonJS({ "node_modules/p-queue/dist/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var EventEmitter2 = require_eventemitter3(); var p_timeout_1 = require_p_timeout(); var priority_queue_1 = require_priority_queue(); var empty = () => { }; var timeoutError = new p_timeout_1.TimeoutError(); var PQueue = class extends EventEmitter2 { constructor(options) { var _a, _b, _c, _d; super(); this._intervalCount = 0; this._intervalEnd = 0; this._pendingCount = 0; this._resolveEmpty = empty; this._resolveIdle = empty; options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); if (!(typeof options.intervalCap === "number" && options.intervalCap >= 1)) { throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ""}\` (${typeof options.intervalCap})`); } if (options.interval === void 0 || !(Number.isFinite(options.interval) && options.interval >= 0)) { throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ""}\` (${typeof options.interval})`); } this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; this._intervalCap = options.intervalCap; this._interval = options.interval; this._queue = new options.queueClass(); this._queueClass = options.queueClass; this.concurrency = options.concurrency; this._timeout = options.timeout; this._throwOnTimeout = options.throwOnTimeout === true; this._isPaused = options.autoStart === false; } get _doesIntervalAllowAnother() { return this._isIntervalIgnored || this._intervalCount < this._intervalCap; } get _doesConcurrentAllowAnother() { return this._pendingCount < this._concurrency; } _next() { this._pendingCount--; this._tryToStartAnother(); this.emit("next"); } _resolvePromises() { this._resolveEmpty(); this._resolveEmpty = empty; if (this._pendingCount === 0) { this._resolveIdle(); this._resolveIdle = empty; this.emit("idle"); } } _onResumeInterval() { this._onInterval(); this._initializeIntervalIfNeeded(); this._timeoutId = void 0; } _isIntervalPaused() { const now = Date.now(); if (this._intervalId === void 0) { const delay = this._intervalEnd - now; if (delay < 0) { this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; } else { if (this._timeoutId === void 0) { this._timeoutId = setTimeout(() => { this._onResumeInterval(); }, delay); } return true; } } return false; } _tryToStartAnother() { if (this._queue.size === 0) { if (this._intervalId) { clearInterval(this._intervalId); } this._intervalId = void 0; this._resolvePromises(); return false; } if (!this._isPaused) { const canInitializeInterval = !this._isIntervalPaused(); if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { const job = this._queue.dequeue(); if (!job) { return false; } this.emit("active"); job(); if (canInitializeInterval) { this._initializeIntervalIfNeeded(); } return true; } } return false; } _initializeIntervalIfNeeded() { if (this._isIntervalIgnored || this._intervalId !== void 0) { return; } this._intervalId = setInterval(() => { this._onInterval(); }, this._interval); this._intervalEnd = Date.now() + this._interval; } _onInterval() { if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { clearInterval(this._intervalId); this._intervalId = void 0; } this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; this._processQueue(); } /** Executes all queued functions until it reaches the limit. */ _processQueue() { while (this._tryToStartAnother()) { } } get concurrency() { return this._concurrency; } set concurrency(newConcurrency) { if (!(typeof newConcurrency === "number" && newConcurrency >= 1)) { throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); } this._concurrency = newConcurrency; this._processQueue(); } /** Adds a sync or async task to the queue. Always returns a promise. */ async add(fn, options = {}) { return new Promise((resolve, reject) => { const run = async () => { this._pendingCount++; this._intervalCount++; try { const operation = this._timeout === void 0 && options.timeout === void 0 ? fn() : p_timeout_1.default(Promise.resolve(fn()), options.timeout === void 0 ? this._timeout : options.timeout, () => { if (options.throwOnTimeout === void 0 ? this._throwOnTimeout : options.throwOnTimeout) { reject(timeoutError); } return void 0; }); resolve(await operation); } catch (error) { reject(error); } this._next(); }; this._queue.enqueue(run, options); this._tryToStartAnother(); this.emit("add"); }); } /** Same as `.add()`, but accepts an array of sync or async functions. @returns A promise that resolves when all functions are resolved. */ async addAll(functions, options) { return Promise.all(functions.map(async (function_) => this.add(function_, options))); } /** Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) */ start() { if (!this._isPaused) { return this; } this._isPaused = false; this._processQueue(); return this; } /** Put queue execution on hold. */ pause() { this._isPaused = true; } /** Clear the queue. */ clear() { this._queue = new this._queueClass(); } /** Can be called multiple times. Useful if you for example add additional items at a later time. @returns A promise that settles when the queue becomes empty. */ async onEmpty() { if (this._queue.size === 0) { return; } return new Promise((resolve) => { const existingResolve = this._resolveEmpty; this._resolveEmpty = () => { existingResolve(); resolve(); }; }); } /** The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. */ async onIdle() { if (this._pendingCount === 0 && this._queue.size === 0) { return; } return new Promise((resolve) => { const existingResolve = this._resolveIdle; this._resolveIdle = () => { existingResolve(); resolve(); }; }); } /** Size of the queue. */ get size() { return this._queue.size; } /** Size of the queue, filtered by the given options. For example, this can be used to find the number of items remaining in the queue with a specific priority level. */ sizeBy(options) { return this._queue.filter(options).length; } /** Number of pending promises. */ get pending() { return this._pendingCount; } /** Whether the queue is currently paused. */ get isPaused() { return this._isPaused; } get timeout() { return this._timeout; } /** Set the timeout for future operations. */ set timeout(milliseconds) { this._timeout = milliseconds; } }; exports.default = PQueue; } }); // node_modules/langchainplus-sdk/dist/utils/async_caller.js var import_p_retry, import_p_queue, STATUS_NO_RETRY, AsyncCaller; var init_async_caller = __esm({ "node_modules/langchainplus-sdk/dist/utils/async_caller.js"() { import_p_retry = __toESM(require_p_retry(), 1); import_p_queue = __toESM(require_dist(), 1); STATUS_NO_RETRY = [ 400, 401, 403, 404, 405, 406, 407, 408, 409 // Conflict ]; AsyncCaller = class { constructor(params) { var _a, _b; Object.defineProperty(this, "maxConcurrency", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "maxRetries", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "queue", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.maxConcurrency = (_a = params.maxConcurrency) != null ? _a : Infinity; this.maxRetries = (_b = params.maxRetries) != null ? _b : 6; const PQueue = "default" in import_p_queue.default ? import_p_queue.default.default : import_p_queue.default; this.queue = new PQueue({ concurrency: this.maxConcurrency }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any call(callable, ...args) { return this.queue.add(() => (0, import_p_retry.default)(() => callable(...args).catch((error) => { if (error instanceof Error) { throw error; } else { throw new Error(error); } }), { onFailedAttempt(error) { var _a; if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) { throw error; } if ((error == null ? void 0 : error.code) === "ECONNABORTED") { throw error; } const status = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status; if (status && STATUS_NO_RETRY.includes(+status)) { throw error; } }, retries: this.maxRetries, randomize: true // If needed we can change some of the defaults here, // but they're quite sensible. }), { throwOnTimeout: true }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any callWithOptions(options, callable, ...args) { if (options.signal) { return Promise.race([ this.call(callable, ...args), new Promise((_, reject) => { var _a; (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => { reject(new Error("AbortError")); }); }) ]); } return this.call(callable, ...args); } fetch(...args) { return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); } }; } }); // node_modules/langchainplus-sdk/dist/utils/env.js async function getRuntimeEnvironment() { if (runtimeEnvironment === void 0) { const env = getEnv(); runtimeEnvironment = { library: "langsmith", runtime: env }; } return runtimeEnvironment; } function getEnvironmentVariable(name) { var _a; try { return typeof process !== "undefined" ? ( // eslint-disable-next-line no-process-env (_a = process.env) == null ? void 0 : _a[name] ) : void 0; } catch (e) { return void 0; } } var isBrowser, isWebWorker, isJsDom, isDeno, isNode, getEnv, runtimeEnvironment; var init_env = __esm({ "node_modules/langchainplus-sdk/dist/utils/env.js"() { isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")); isDeno = () => typeof Deno !== "undefined"; isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); getEnv = () => { let env; if (isBrowser()) { env = "browser"; } else if (isNode()) { env = "node"; } else if (isWebWorker()) { env = "webworker"; } else if (isJsDom()) { env = "jsdom"; } else if (isDeno()) { env = "deno"; } else { env = "other"; } return env; }; } }); // node_modules/langchainplus-sdk/dist/client.js var isLocalhost, raiseForStatus, Client; var init_client = __esm({ "node_modules/langchainplus-sdk/dist/client.js"() { init_esm_browser(); init_async_caller(); init_env(); isLocalhost = (url) => { const strippedUrl = url.replace("http://", "").replace("https://", ""); const hostname = strippedUrl.split("/")[0].split(":")[0]; return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"; }; raiseForStatus = async (response, operation) => { const body = await response.text(); if (!response.ok) { throw new Error(`Failed to ${operation}: ${response.status} ${response.statusText} ${body}`); } }; Client = class { constructor(config = {}) { var _a, _b, _c, _d; Object.defineProperty(this, "apiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "apiUrl", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "timeout_ms", { enumerable: true, configurable: true, writable: true, value: void 0 }); const defaultConfig = Client.getDefaultClientConfig(); this.apiUrl = (_a = config.apiUrl) != null ? _a : defaultConfig.apiUrl; this.apiKey = (_b = config.apiKey) != null ? _b : defaultConfig.apiKey; this.validateApiKeyIfHosted(); this.timeout_ms = (_c = config.timeout_ms) != null ? _c : 4e3; this.caller = new AsyncCaller((_d = config.callerOptions) != null ? _d : {}); } static getDefaultClientConfig() { var _a; return { apiUrl: (_a = getEnvironmentVariable("LANGCHAIN_ENDPOINT")) != null ? _a : "http://localhost:1984", apiKey: getEnvironmentVariable("LANGCHAIN_API_KEY") }; } validateApiKeyIfHosted() { const isLocal = isLocalhost(this.apiUrl); if (!isLocal && !this.apiKey) { throw new Error("API key must be provided when using hosted LangChain+ API"); } } get headers() { const headers = {}; if (this.apiKey) { headers["x-api-key"] = `${this.apiKey}`; } return headers; } async _get(path2, queryParams) { var _a; const paramsString = (_a = queryParams == null ? void 0 : queryParams.toString()) != null ? _a : ""; const url = `${this.apiUrl}${path2}?${paramsString}`; const response = await this.caller.call(fetch, url, { method: "GET", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to fetch ${path2}: ${response.status} ${response.statusText}`); } return response.json(); } async createRun(run) { var _a; const headers = { ...this.headers, "Content-Type": "application/json" }; const extra = (_a = run.extra) != null ? _a : {}; const runtimeEnv = await getRuntimeEnvironment(); const session_name = run.project_name; delete run.project_name; const runCreate = { session_name, ...run, extra: { ...run.extra, runtime: { ...runtimeEnv, ...extra.runtime } } }; const response = await this.caller.call(fetch, `${this.apiUrl}/runs`, { method: "POST", headers, body: JSON.stringify(runCreate), signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "create run"); } async updateRun(runId, run) { const headers = { ...this.headers, "Content-Type": "application/json" }; const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, { method: "PATCH", headers, body: JSON.stringify(run), signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "update run"); } async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { let run = await this._get(`/runs/${runId}`); if (loadChildRuns && run.child_run_ids) { run = await this._loadChildRuns(run); } return run; } async _loadChildRuns(run) { const childRuns = await this.listRuns({ id: run.child_run_ids }); const treemap = {}; const runs = {}; childRuns.sort((a2, b) => a2.execution_order - b.execution_order); for (const childRun of childRuns) { if (childRun.parent_run_id === null || childRun.parent_run_id === void 0) { throw new Error(`Child run ${childRun.id} has no parent`); } if (!(childRun.parent_run_id in treemap)) { treemap[childRun.parent_run_id] = []; } treemap[childRun.parent_run_id].push(childRun); runs[childRun.id] = childRun; } run.child_runs = treemap[run.id] || []; for (const runId in treemap) { if (runId !== run.id) { runs[runId].child_runs = treemap[runId]; } } return run; } async listRuns({ projectId, projectName, executionOrder, runType, error, id, limit, offset }) { const queryParams = new URLSearchParams(); let projectId_ = projectId; if (projectName) { if (projectId) { throw new Error("Only one of projectId or projectName may be given"); } projectId_ = (await this.readProject({ projectName })).id; } if (projectId_) { queryParams.append("session", projectId_); } if (executionOrder) { queryParams.append("execution_order", executionOrder.toString()); } if (runType) { queryParams.append("run_type", runType); } if (error !== void 0) { queryParams.append("error", error.toString()); } if (id !== void 0) { for (const id_ of id) { queryParams.append("id", id_); } } if (limit !== void 0) { queryParams.append("limit", limit.toString()); } if (offset !== void 0) { queryParams.append("offset", offset.toString()); } return this._get("/runs", queryParams); } async deleteRun(runId) { const response = await this.caller.call(fetch, `${this.apiUrl}/runs/${runId}`, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, "delete run"); } async createProject({ projectName, projectExtra, mode, upsert: upsert2 }) { const upsert_ = upsert2 ? `?upsert=true` : ""; const endpoint = `${this.apiUrl}/sessions${upsert_}`; const body = { name: projectName }; if (projectExtra !== void 0) { body["extra"] = projectExtra; } if (mode !== void 0) { body["mode"] = mode; } const response = await this.caller.call(fetch, endpoint, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(this.timeout_ms) }); const result = await response.json(); if (!response.ok) { throw new Error(`Failed to create session ${projectName}: ${response.status} ${response.statusText}`); } return result; } async readProject({ projectId, projectName }) { let path2 = "/sessions"; const params = new URLSearchParams(); if (projectId !== void 0 && projectName !== void 0) { throw new Error("Must provide either projectName or projectId, not both"); } else if (projectId !== void 0) { path2 += `/${projectId}`; } else if (projectName !== void 0) { params.append("name", projectName); } else { throw new Error("Must provide projectName or projectId"); } const response = await this._get(path2, params); let result; if (Array.isArray(response)) { if (response.length === 0) { throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); } result = response[0]; } else { result = response; } return result; } async listProjects() { return this._get("/sessions"); } async deleteProject({ projectId, projectName }) { let projectId_; if (projectId === void 0 && projectName === void 0) { throw new Error("Must provide projectName or projectId"); } else if (projectId !== void 0 && projectName !== void 0) { throw new Error("Must provide either projectName or projectId, not both"); } else if (projectId === void 0) { projectId_ = (await this.readProject({ projectName })).id; } else { projectId_ = projectId; } const response = await this.caller.call(fetch, `${this.apiUrl}/sessions/${projectId_}`, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); await raiseForStatus(response, `delete session ${projectId_} (${projectName})`); } async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description }) { const url = `${this.apiUrl}/datasets/upload`; const formData = new FormData(); formData.append("file", csvFile, fileName); formData.append("input_keys", inputKeys.join(",")); formData.append("output_keys", outputKeys.join(",")); if (description) { formData.append("description", description); } const response = await this.caller.call(fetch, url, { method: "POST", headers: this.headers, body: formData, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { const result2 = await response.json(); if (result2.detail && result2.detail.includes("already exists")) { throw new Error(`Dataset ${fileName} already exists`); } throw new Error(`Failed to upload CSV: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async createDataset(name, { description } = {}) { const response = await this.caller.call(fetch, `${this.apiUrl}/datasets`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify({ name, description }), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { const result2 = await response.json(); if (result2.detail && result2.detail.includes("already exists")) { throw new Error(`Dataset ${name} already exists`); } throw new Error(`Failed to create dataset ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async readDataset({ datasetId, datasetName }) { let path2 = "/datasets"; const params = new URLSearchParams({ limit: "1" }); if (datasetId !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId !== void 0) { path2 += `/${datasetId}`; } else if (datasetName !== void 0) { params.append("name", datasetName); } else { throw new Error("Must provide datasetName or datasetId"); } const response = await this._get(path2, params); let result; if (Array.isArray(response)) { if (response.length === 0) { throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); } result = response[0]; } else { result = response; } return result; } async listDatasets({ limit = 100, offset = 0 } = {}) { const path2 = "/datasets"; const params = new URLSearchParams({ limit: limit.toString(), offset: offset.toString() }); const response = await this._get(path2, params); if (!Array.isArray(response)) { throw new Error(`Expected ${path2} to return an array, but got ${response}`); } return response; } async deleteDataset({ datasetId, datasetName }) { let path2 = "/datasets"; let datasetId_ = datasetId; if (datasetId !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetName !== void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } if (datasetId_ !== void 0) { path2 += `/${datasetId_}`; } else { throw new Error("Must provide datasetName or datasetId"); } const response = await this.caller.call(fetch, this.apiUrl + path2, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to delete ${path2}: ${response.status} ${response.statusText}`); } await response.json(); } async createExample(inputs, outputs, { datasetId, datasetName, createdAt }) { let datasetId_ = datasetId; if (datasetId_ === void 0 && datasetName === void 0) { throw new Error("Must provide either datasetName or datasetId"); } else if (datasetId_ !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId_ === void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } const createdAt_ = createdAt || new Date(); const data = { dataset_id: datasetId_, inputs, outputs, created_at: createdAt_.toISOString() }; const response = await this.caller.call(fetch, `${this.apiUrl}/examples`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(data), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to create example: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async readExample(exampleId) { const path2 = `/examples/${exampleId}`; return await this._get(path2); } async listExamples({ datasetId, datasetName, limit, offset } = {}) { var _a, _b; let datasetId_; if (datasetId !== void 0 && datasetName !== void 0) { throw new Error("Must provide either datasetName or datasetId, not both"); } else if (datasetId !== void 0) { datasetId_ = datasetId; } else if (datasetName !== void 0) { const dataset = await this.readDataset({ datasetName }); datasetId_ = dataset.id; } else { throw new Error("Must provide a datasetName or datasetId"); } const response = await this._get("/examples", new URLSearchParams({ dataset: datasetId_, limit: (_a = limit == null ? void 0 : limit.toString()) != null ? _a : "100", offset: (_b = offset == null ? void 0 : offset.toString()) != null ? _b : "0" })); if (!Array.isArray(response)) { throw new Error(`Expected /examples to return an array, but got ${response}`); } return response; } async deleteExample(exampleId) { const path2 = `/examples/${exampleId}`; const response = await this.caller.call(fetch, this.apiUrl + path2, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to delete ${path2}: ${response.status} ${response.statusText}`); } await response.json(); } async updateExample(exampleId, update) { const response = await this.caller.call(fetch, `${this.apiUrl}/examples/${exampleId}`, { method: "PATCH", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(update), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to update example ${exampleId}: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async evaluateRun(run, evaluator, { sourceInfo, loadChildRuns } = { loadChildRuns: false }) { let run_; if (typeof run === "string") { run_ = await this.readRun(run, { loadChildRuns }); } else if (typeof run === "object" && "id" in run) { run_ = run; } else { throw new Error(`Invalid run type: ${typeof run}`); } let referenceExample = void 0; if (run_.reference_example_id !== null && run_.reference_example_id !== void 0) { referenceExample = await this.readExample(run_.reference_example_id); } const feedbackResult = await evaluator.evaluateRun(run_, referenceExample); let sourceInfo_ = sourceInfo != null ? sourceInfo : {}; if (feedbackResult.evaluatorInfo) { sourceInfo_ = { ...sourceInfo_, ...feedbackResult.evaluatorInfo }; } return await this.createFeedback(run_.id, feedbackResult.key, { score: feedbackResult.score, value: feedbackResult.value, comment: feedbackResult.comment, correction: feedbackResult.correction, sourceInfo: sourceInfo_, feedbackSourceType: "MODEL" }); } async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "API" }) { let feedback_source; if (feedbackSourceType === "API") { feedback_source = { type: "api", metadata: sourceInfo != null ? sourceInfo : {} }; } else if (feedbackSourceType === "MODEL") { feedback_source = { type: "model", metadata: sourceInfo != null ? sourceInfo : {} }; } else { throw new Error(`Unknown feedback source type ${feedbackSourceType}`); } const feedback = { id: v4_default(), run_id: runId, key, score, value, correction, comment, feedback_source }; const response = await this.caller.call(fetch, `${this.apiUrl}/feedback`, { method: "POST", headers: { ...this.headers, "Content-Type": "application/json" }, body: JSON.stringify(feedback), signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to create feedback for run ${runId}: ${response.status} ${response.statusText}`); } const result = await response.json(); return result; } async readFeedback(feedbackId) { const path2 = `/feedback/${feedbackId}`; const response = await this._get(path2); return response; } async deleteFeedback(feedbackId) { const path2 = `/feedback/${feedbackId}`; const response = await this.caller.call(fetch, this.apiUrl + path2, { method: "DELETE", headers: this.headers, signal: AbortSignal.timeout(this.timeout_ms) }); if (!response.ok) { throw new Error(`Failed to delete ${path2}: ${response.status} ${response.statusText}`); } await response.json(); } async listFeedback({ runIds, limit, offset } = {}) { const queryParams = new URLSearchParams(); if (runIds) { queryParams.append("run", runIds.join(",")); } if (limit !== void 0) { queryParams.append("limit", limit.toString()); } if (offset !== void 0) { queryParams.append("offset", offset.toString()); } const response = await this._get("/feedback", queryParams); return response; } }; } }); // node_modules/langchainplus-sdk/dist/run_trees.js var init_run_trees = __esm({ "node_modules/langchainplus-sdk/dist/run_trees.js"() { init_env(); init_client(); } }); // node_modules/langchainplus-sdk/dist/index.js var init_dist = __esm({ "node_modules/langchainplus-sdk/dist/index.js"() { init_client(); init_run_trees(); } }); // node_modules/langchainplus-sdk/index.js var init_langchainplus_sdk = __esm({ "node_modules/langchainplus-sdk/index.js"() { init_dist(); } }); // node_modules/langchain/dist/util/env.js async function getRuntimeEnvironment2() { if (runtimeEnvironment2 === void 0) { const env = getEnv2(); runtimeEnvironment2 = { library: "langchain-js", runtime: env }; } return runtimeEnvironment2; } function getEnvironmentVariable2(name) { var _a; try { return typeof process !== "undefined" ? ( // eslint-disable-next-line no-process-env (_a = process.env) == null ? void 0 : _a[name] ) : void 0; } catch (e) { return void 0; } } var isBrowser2, isWebWorker2, isJsDom2, isDeno2, isNode2, getEnv2, runtimeEnvironment2; var init_env2 = __esm({ "node_modules/langchain/dist/util/env.js"() { isBrowser2 = () => typeof window !== "undefined" && typeof window.document !== "undefined"; isWebWorker2 = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; isJsDom2 = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && (navigator.userAgent.includes("Node.js") || navigator.userAgent.includes("jsdom")); isDeno2 = () => typeof Deno !== "undefined"; isNode2 = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno2(); getEnv2 = () => { let env; if (isBrowser2()) { env = "browser"; } else if (isNode2()) { env = "node"; } else if (isWebWorker2()) { env = "webworker"; } else if (isJsDom2()) { env = "jsdom"; } else if (isDeno2()) { env = "deno"; } else { env = "other"; } return env; }; } }); // node_modules/langchain/dist/callbacks/handlers/tracer_langchain.js var LangChainTracer; var init_tracer_langchain = __esm({ "node_modules/langchain/dist/callbacks/handlers/tracer_langchain.js"() { init_langchainplus_sdk(); init_env2(); init_tracer(); LangChainTracer = class extends BaseTracer { constructor(fields = {}) { var _a; super(fields); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "langchain_tracer" }); Object.defineProperty(this, "projectName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "exampleId", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); const { exampleId, projectName, client } = fields; this.projectName = (_a = projectName != null ? projectName : getEnvironmentVariable2("LANGCHAIN_PROJECT")) != null ? _a : getEnvironmentVariable2("LANGCHAIN_SESSION"); this.exampleId = exampleId; this.client = client != null ? client : new Client({}); } async _convertToCreate(run, example_id = void 0) { return { ...run, extra: { ...run.extra, runtime: await getRuntimeEnvironment2() }, child_runs: void 0, session_name: this.projectName, reference_example_id: run.parent_run_id ? void 0 : example_id }; } async persistRun(_run) { } async _persistRunSingle(run) { const persistedRun = await this._convertToCreate(run, this.exampleId); await this.client.createRun(persistedRun); } async _updateRunSingle(run) { const runUpdate = { end_time: run.end_time, error: run.error, outputs: run.outputs, events: run.events }; await this.client.updateRun(run.id, runUpdate); } async onLLMStart(run) { await this._persistRunSingle(run); } async onLLMEnd(run) { await this._updateRunSingle(run); } async onLLMError(run) { await this._updateRunSingle(run); } async onChainStart(run) { await this._persistRunSingle(run); } async onChainEnd(run) { await this._updateRunSingle(run); } async onChainError(run) { await this._updateRunSingle(run); } async onToolStart(run) { await this._persistRunSingle(run); } async onToolEnd(run) { await this._updateRunSingle(run); } async onToolError(run) { await this._updateRunSingle(run); } }; } }); // node_modules/langchain/dist/memory/base.js function getBufferString(messages4, humanPrefix = "Human", aiPrefix = "AI") { const string_messages = []; for (const m of messages4) { let role; if (m._getType() === "human") { role = humanPrefix; } else if (m._getType() === "ai") { role = aiPrefix; } else if (m._getType() === "system") { role = "System"; } else if (m._getType() === "function") { role = "Function"; } else if (m._getType() === "generic") { role = m.role; } else { throw new Error(`Got unsupported message type: ${m}`); } const nameStr = m.name ? `${m.name}, ` : ""; string_messages.push(`${role}: ${nameStr}${m.content}`); } return string_messages.join("\n"); } var BaseMemory, getInputValue; var init_base2 = __esm({ "node_modules/langchain/dist/memory/base.js"() { BaseMemory = class { }; getInputValue = (inputValues, inputKey) => { if (inputKey !== void 0) { return inputValues[inputKey]; } const keys3 = Object.keys(inputValues); if (keys3.length === 1) { return inputValues[keys3[0]]; } throw new Error(`input values have ${keys3.length} keys, you must specify an input key or pass only 1 key as input`); }; } }); // node_modules/langchain/dist/callbacks/handlers/tracer_langchain_v1.js var LangChainTracerV1; var init_tracer_langchain_v1 = __esm({ "node_modules/langchain/dist/callbacks/handlers/tracer_langchain_v1.js"() { init_base2(); init_env2(); init_tracer(); LangChainTracerV1 = class extends BaseTracer { constructor() { super(); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "langchain_tracer" }); Object.defineProperty(this, "endpoint", { enumerable: true, configurable: true, writable: true, value: getEnvironmentVariable2("LANGCHAIN_ENDPOINT") || "http://localhost:1984" }); Object.defineProperty(this, "headers", { enumerable: true, configurable: true, writable: true, value: { "Content-Type": "application/json" } }); Object.defineProperty(this, "session", { enumerable: true, configurable: true, writable: true, value: void 0 }); const apiKey = getEnvironmentVariable2("LANGCHAIN_API_KEY"); if (apiKey) { this.headers["x-api-key"] = apiKey; } } async newSession(sessionName) { const sessionCreate = { start_time: Date.now(), name: sessionName }; const session = await this.persistSession(sessionCreate); this.session = session; return session; } async loadSession(sessionName) { const endpoint = `${this.endpoint}/sessions?name=${sessionName}`; return this._handleSessionResponse(endpoint); } async loadDefaultSession() { const endpoint = `${this.endpoint}/sessions?name=default`; return this._handleSessionResponse(endpoint); } async convertV2RunToRun(run) { var _a, _b; const session = (_a = this.session) != null ? _a : await this.loadDefaultSession(); const serialized = run.serialized; let runResult; if (run.run_type === "llm") { const prompts = run.inputs.prompts ? run.inputs.prompts : run.inputs.messages.map((x) => getBufferString(x)); const llmRun = { uuid: run.id, start_time: run.start_time, end_time: run.end_time, execution_order: run.execution_order, child_execution_order: run.child_execution_order, serialized, type: run.run_type, session_id: session.id, prompts, response: run.outputs }; runResult = llmRun; } else if (run.run_type === "chain") { const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); const chainRun = { uuid: run.id, start_time: run.start_time, end_time: run.end_time, execution_order: run.execution_order, child_execution_order: run.child_execution_order, serialized, type: run.run_type, session_id: session.id, inputs: run.inputs, outputs: run.outputs, child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool") }; runResult = chainRun; } else if (run.run_type === "tool") { const child_runs = await Promise.all(run.child_runs.map((child_run) => this.convertV2RunToRun(child_run))); const toolRun = { uuid: run.id, start_time: run.start_time, end_time: run.end_time, execution_order: run.execution_order, child_execution_order: run.child_execution_order, serialized, type: run.run_type, session_id: session.id, tool_input: run.inputs.input, output: (_b = run.outputs) == null ? void 0 : _b.output, action: JSON.stringify(serialized), child_llm_runs: child_runs.filter((child_run) => child_run.type === "llm"), child_chain_runs: child_runs.filter((child_run) => child_run.type === "chain"), child_tool_runs: child_runs.filter((child_run) => child_run.type === "tool") }; runResult = toolRun; } else { throw new Error(`Unknown run type: ${run.run_type}`); } return runResult; } async persistRun(run) { let endpoint; let v1Run; if (run.run_type !== void 0) { v1Run = await this.convertV2RunToRun(run); } else { v1Run = run; } if (v1Run.type === "llm") { endpoint = `${this.endpoint}/llm-runs`; } else if (v1Run.type === "chain") { endpoint = `${this.endpoint}/chain-runs`; } else { endpoint = `${this.endpoint}/tool-runs`; } const response = await fetch(endpoint, { method: "POST", headers: this.headers, body: JSON.stringify(v1Run) }); if (!response.ok) { console.error(`Failed to persist run: ${response.status} ${response.statusText}`); } } async persistSession(sessionCreate) { const endpoint = `${this.endpoint}/sessions`; const response = await fetch(endpoint, { method: "POST", headers: this.headers, body: JSON.stringify(sessionCreate) }); if (!response.ok) { console.error(`Failed to persist session: ${response.status} ${response.statusText}, using default session.`); return { id: 1, ...sessionCreate }; } return { id: (await response.json()).id, ...sessionCreate }; } async _handleSessionResponse(endpoint) { const response = await fetch(endpoint, { method: "GET", headers: this.headers }); let tracerSession; if (!response.ok) { console.error(`Failed to load session: ${response.status} ${response.statusText}`); tracerSession = { id: 1, start_time: Date.now() }; this.session = tracerSession; return tracerSession; } const resp = await response.json(); if (resp.length === 0) { tracerSession = { id: 1, start_time: Date.now() }; this.session = tracerSession; return tracerSession; } [tracerSession] = resp; this.session = tracerSession; return tracerSession; } }; } }); // node_modules/langchain/dist/callbacks/handlers/initialize.js async function getTracingCallbackHandler(session) { const tracer = new LangChainTracerV1(); if (session) { await tracer.loadSession(session); } else { await tracer.loadDefaultSession(); } return tracer; } async function getTracingV2CallbackHandler() { return new LangChainTracer(); } var init_initialize = __esm({ "node_modules/langchain/dist/callbacks/handlers/initialize.js"() { init_tracer_langchain(); init_tracer_langchain_v1(); } }); // node_modules/langchain/dist/callbacks/promises.js function createQueue() { const PQueue = "default" in import_p_queue2.default ? import_p_queue2.default.default : import_p_queue2.default; return new PQueue({ autoStart: true, concurrency: 1 }); } async function consumeCallback(promiseFn, wait) { if (wait === true) { await promiseFn(); } else { if (typeof queue === "undefined") { queue = createQueue(); } void queue.add(promiseFn); } } var import_p_queue2, queue; var init_promises = __esm({ "node_modules/langchain/dist/callbacks/promises.js"() { import_p_queue2 = __toESM(require_dist(), 1); } }); // node_modules/langchain/dist/callbacks/manager.js function parseCallbackConfigArg(arg) { if (!arg) { return {}; } else if (Array.isArray(arg) || "name" in arg) { return { callbacks: arg }; } else { return arg; } } function ensureHandler(handler) { if ("name" in handler) { return handler; } return BaseCallbackHandler.fromMethods(handler); } var BaseCallbackManager, BaseRunManager, CallbackManagerForLLMRun, CallbackManagerForChainRun, CallbackManagerForToolRun, CallbackManager; var init_manager = __esm({ "node_modules/langchain/dist/callbacks/manager.js"() { init_esm_browser(); init_base(); init_console(); init_initialize(); init_base2(); init_env2(); init_tracer_langchain(); init_promises(); BaseCallbackManager = class { setHandler(handler) { return this.setHandlers([handler]); } }; BaseRunManager = class { constructor(runId, handlers2, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { Object.defineProperty(this, "runId", { enumerable: true, configurable: true, writable: true, value: runId }); Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, value: handlers2 }); Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, value: inheritableHandlers }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: tags }); Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, value: inheritableTags }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: metadata }); Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, value: inheritableMetadata }); Object.defineProperty(this, "_parentRunId", { enumerable: true, configurable: true, writable: true, value: _parentRunId }); } async handleText(text4) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; try { await ((_a = handler.handleText) == null ? void 0 : _a.call(handler, text4, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleText: ${err}`); } }, handler.awaitHandlers))); } }; CallbackManagerForLLMRun = class extends BaseRunManager { async handleLLMNewToken(token, idx = { prompt: 0, completion: 0 }) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreLLM) { try { await ((_a = handler.handleLLMNewToken) == null ? void 0 : _a.call(handler, token, idx, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); } } }, handler.awaitHandlers))); } async handleLLMError(err) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreLLM) { try { await ((_a = handler.handleLLMError) == null ? void 0 : _a.call(handler, err, this.runId, this._parentRunId, this.tags)); } catch (err2) { console.error(`Error in handler ${handler.constructor.name}, handleLLMError: ${err2}`); } } }, handler.awaitHandlers))); } async handleLLMEnd(output) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreLLM) { try { await ((_a = handler.handleLLMEnd) == null ? void 0 : _a.call(handler, output, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); } } }, handler.awaitHandlers))); } }; CallbackManagerForChainRun = class extends BaseRunManager { getChild(tag) { const manager = new CallbackManager(this.runId); manager.setHandlers(this.inheritableHandlers); manager.addTags(this.inheritableTags); manager.addMetadata(this.inheritableMetadata); if (tag) { manager.addTags([tag], false); } return manager; } async handleChainError(err) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreChain) { try { await ((_a = handler.handleChainError) == null ? void 0 : _a.call(handler, err, this.runId, this._parentRunId, this.tags)); } catch (err2) { console.error(`Error in handler ${handler.constructor.name}, handleChainError: ${err2}`); } } }, handler.awaitHandlers))); } async handleChainEnd(output) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreChain) { try { await ((_a = handler.handleChainEnd) == null ? void 0 : _a.call(handler, output, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); } } }, handler.awaitHandlers))); } async handleAgentAction(action) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreAgent) { try { await ((_a = handler.handleAgentAction) == null ? void 0 : _a.call(handler, action, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); } } }, handler.awaitHandlers))); } async handleAgentEnd(action) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreAgent) { try { await ((_a = handler.handleAgentEnd) == null ? void 0 : _a.call(handler, action, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); } } }, handler.awaitHandlers))); } }; CallbackManagerForToolRun = class extends BaseRunManager { getChild(tag) { const manager = new CallbackManager(this.runId); manager.setHandlers(this.inheritableHandlers); manager.addTags(this.inheritableTags); manager.addMetadata(this.inheritableMetadata); if (tag) { manager.addTags([tag], false); } return manager; } async handleToolError(err) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreAgent) { try { await ((_a = handler.handleToolError) == null ? void 0 : _a.call(handler, err, this.runId, this._parentRunId, this.tags)); } catch (err2) { console.error(`Error in handler ${handler.constructor.name}, handleToolError: ${err2}`); } } }, handler.awaitHandlers))); } async handleToolEnd(output) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreAgent) { try { await ((_a = handler.handleToolEnd) == null ? void 0 : _a.call(handler, output, this.runId, this._parentRunId, this.tags)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); } } }, handler.awaitHandlers))); } }; CallbackManager = class extends BaseCallbackManager { constructor(parentRunId) { super(); Object.defineProperty(this, "handlers", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inheritableHandlers", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "inheritableTags", { enumerable: true, configurable: true, writable: true, value: [] }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "inheritableMetadata", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: "callback_manager" }); Object.defineProperty(this, "_parentRunId", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.handlers = []; this.inheritableHandlers = []; this._parentRunId = parentRunId; } async handleLLMStart(llm, prompts, _runId = void 0, _parentRunId = void 0, extraParams = void 0) { return Promise.all(prompts.map(async (prompt) => { const runId = v4_default(); await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreLLM) { try { await ((_a = handler.handleLLMStart) == null ? void 0 : _a.call(handler, llm, [prompt], runId, this._parentRunId, extraParams, this.tags, this.metadata)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); })); } async handleChatModelStart(llm, messages4, _runId = void 0, _parentRunId = void 0, extraParams = void 0) { return Promise.all(messages4.map(async (messageGroup) => { const runId = v4_default(); await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a, _b; if (!handler.ignoreLLM) { try { if (handler.handleChatModelStart) await ((_a = handler.handleChatModelStart) == null ? void 0 : _a.call(handler, llm, [messageGroup], runId, this._parentRunId, extraParams, this.tags, this.metadata)); else if (handler.handleLLMStart) { const messageString = getBufferString(messageGroup); await ((_b = handler.handleLLMStart) == null ? void 0 : _b.call(handler, llm, [messageString], runId, this._parentRunId, extraParams, this.tags, this.metadata)); } } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForLLMRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); })); } async handleChainStart(chain, inputs, runId = v4_default()) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreChain) { try { await ((_a = handler.handleChainStart) == null ? void 0 : _a.call(handler, chain, inputs, runId, this._parentRunId, this.tags, this.metadata)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } async handleToolStart(tool, input, runId = v4_default()) { await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { var _a; if (!handler.ignoreAgent) { try { await ((_a = handler.handleToolStart) == null ? void 0 : _a.call(handler, tool, input, runId, this._parentRunId, this.tags, this.metadata)); } catch (err) { console.error(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); } } }, handler.awaitHandlers))); return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); } addHandler(handler, inherit = true) { this.handlers.push(handler); if (inherit) { this.inheritableHandlers.push(handler); } } removeHandler(handler) { this.handlers = this.handlers.filter((_handler) => _handler !== handler); this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); } setHandlers(handlers2, inherit = true) { this.handlers = []; this.inheritableHandlers = []; for (const handler of handlers2) { this.addHandler(handler, inherit); } } addTags(tags, inherit = true) { this.removeTags(tags); this.tags.push(...tags); if (inherit) { this.inheritableTags.push(...tags); } } removeTags(tags) { this.tags = this.tags.filter((tag) => !tags.includes(tag)); this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); } addMetadata(metadata, inherit = true) { this.metadata = { ...this.metadata, ...metadata }; if (inherit) { this.inheritableMetadata = { ...this.inheritableMetadata, ...metadata }; } } removeMetadata(metadata) { for (const key of Object.keys(metadata)) { delete this.metadata[key]; delete this.inheritableMetadata[key]; } } copy(additionalHandlers = [], inherit = true) { const manager = new CallbackManager(this._parentRunId); for (const handler of this.handlers) { const inheritable = this.inheritableHandlers.includes(handler); manager.addHandler(handler, inheritable); } for (const tag of this.tags) { const inheritable = this.inheritableTags.includes(tag); manager.addTags([tag], inheritable); } for (const key of Object.keys(this.metadata)) { const inheritable = Object.keys(this.inheritableMetadata).includes(key); manager.addMetadata({ [key]: this.metadata[key] }, inheritable); } for (const handler of additionalHandlers) { if ( // Prevent multiple copies of console_callback_handler manager.handlers.filter((h2) => h2.name === "console_callback_handler").some((h2) => h2.name === handler.name) ) { continue; } manager.addHandler(handler, inherit); } return manager; } static fromHandlers(handlers2) { class Handler extends BaseCallbackHandler { constructor() { super(); Object.defineProperty(this, "name", { enumerable: true, configurable: true, writable: true, value: v4_default() }); Object.assign(this, handlers2); } } const manager = new this(); manager.addHandler(new Handler()); return manager; } static async configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { var _a, _b, _c; let callbackManager; if (inheritableHandlers || localHandlers) { if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { callbackManager = new CallbackManager(); callbackManager.setHandlers((_a = inheritableHandlers == null ? void 0 : inheritableHandlers.map(ensureHandler)) != null ? _a : [], true); } else { callbackManager = inheritableHandlers; } callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers == null ? void 0 : localHandlers.handlers, false); } const verboseEnabled = getEnvironmentVariable2("LANGCHAIN_VERBOSE") || (options == null ? void 0 : options.verbose); const tracingV2Enabled = (_b = getEnvironmentVariable2("LANGCHAIN_TRACING_V2")) != null ? _b : false; const tracingEnabled = tracingV2Enabled || ((_c = getEnvironmentVariable2("LANGCHAIN_TRACING")) != null ? _c : false); if (verboseEnabled || tracingEnabled) { if (!callbackManager) { callbackManager = new CallbackManager(); } if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { const consoleHandler = new ConsoleCallbackHandler(); callbackManager.addHandler(consoleHandler, true); } if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { if (tracingV2Enabled) { callbackManager.addHandler(await getTracingV2CallbackHandler(), true); } else { const session = getEnvironmentVariable2("LANGCHAIN_PROJECT") && getEnvironmentVariable2("LANGCHAIN_SESSION"); callbackManager.addHandler(await getTracingCallbackHandler(session), true); } } } if (inheritableTags || localTags) { if (callbackManager) { callbackManager.addTags(inheritableTags != null ? inheritableTags : []); callbackManager.addTags(localTags != null ? localTags : [], false); } } if (inheritableMetadata || localMetadata) { if (callbackManager) { callbackManager.addMetadata(inheritableMetadata != null ? inheritableMetadata : {}); callbackManager.addMetadata(localMetadata != null ? localMetadata : {}, false); } } return callbackManager; } }; } }); // node_modules/langchain/dist/util/async_caller.js var import_p_retry2, import_p_queue3, STATUS_NO_RETRY2, AsyncCaller2; var init_async_caller2 = __esm({ "node_modules/langchain/dist/util/async_caller.js"() { import_p_retry2 = __toESM(require_p_retry(), 1); import_p_queue3 = __toESM(require_dist(), 1); STATUS_NO_RETRY2 = [ 400, 401, 403, 404, 405, 406, 407, 408, 409 // Conflict ]; AsyncCaller2 = class { constructor(params) { var _a, _b; Object.defineProperty(this, "maxConcurrency", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "maxRetries", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "queue", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.maxConcurrency = (_a = params.maxConcurrency) != null ? _a : Infinity; this.maxRetries = (_b = params.maxRetries) != null ? _b : 6; const PQueue = "default" in import_p_queue3.default ? import_p_queue3.default.default : import_p_queue3.default; this.queue = new PQueue({ concurrency: this.maxConcurrency }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any call(callable, ...args) { return this.queue.add(() => (0, import_p_retry2.default)(() => callable(...args).catch((error) => { if (error instanceof Error) { throw error; } else { throw new Error(error); } }), { onFailedAttempt(error) { var _a; if (error.message.startsWith("Cancel") || error.message.startsWith("TimeoutError") || error.message.startsWith("AbortError")) { throw error; } if ((error == null ? void 0 : error.code) === "ECONNABORTED") { throw error; } const status = (_a = error == null ? void 0 : error.response) == null ? void 0 : _a.status; if (status && STATUS_NO_RETRY2.includes(+status)) { throw error; } }, retries: this.maxRetries, randomize: true // If needed we can change some of the defaults here, // but they're quite sensible. }), { throwOnTimeout: true }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any callWithOptions(options, callable, ...args) { if (options.signal) { return Promise.race([ this.call(callable, ...args), new Promise((_, reject) => { var _a; (_a = options.signal) == null ? void 0 : _a.addEventListener("abort", () => { reject(new Error("AbortError")); }); }) ]); } return this.call(callable, ...args); } fetch(...args) { return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); } }; } }); // node_modules/js-tiktoken/dist/chunk-XXPGZHWZ.js var __defProp2, __defNormalProp2, __publicField2; var init_chunk_XXPGZHWZ = __esm({ "node_modules/js-tiktoken/dist/chunk-XXPGZHWZ.js"() { __defProp2 = Object.defineProperty; __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; __publicField2 = (obj, key, value) => { __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; } }); // node_modules/base64-js/index.js var require_base64_js = __commonJS({ "node_modules/base64-js/index.js"(exports) { "use strict"; exports.byteLength = byteLength; exports.toByteArray = toByteArray; exports.fromByteArray = fromByteArray; var lookup = []; var revLookup = []; var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var code2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; for (i = 0, len = code2.length; i < len; ++i) { lookup[i] = code2[i]; revLookup[code2.charCodeAt(i)] = i; } var i; var len; revLookup["-".charCodeAt(0)] = 62; revLookup["_".charCodeAt(0)] = 63; function getLens(b64) { var len2 = b64.length; if (len2 % 4 > 0) { throw new Error("Invalid string. Length must be a multiple of 4"); } var validLen = b64.indexOf("="); if (validLen === -1) validLen = len2; var placeHoldersLen = validLen === len2 ? 0 : 4 - validLen % 4; return [validLen, placeHoldersLen]; } function byteLength(b64) { var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function _byteLength(b64, validLen, placeHoldersLen) { return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; } function toByteArray(b64) { var tmp; var lens = getLens(b64); var validLen = lens[0]; var placeHoldersLen = lens[1]; var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); var curByte = 0; var len2 = placeHoldersLen > 0 ? validLen - 4 : validLen; var i2; for (i2 = 0; i2 < len2; i2 += 4) { tmp = revLookup[b64.charCodeAt(i2)] << 18 | revLookup[b64.charCodeAt(i2 + 1)] << 12 | revLookup[b64.charCodeAt(i2 + 2)] << 6 | revLookup[b64.charCodeAt(i2 + 3)]; arr[curByte++] = tmp >> 16 & 255; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 2) { tmp = revLookup[b64.charCodeAt(i2)] << 2 | revLookup[b64.charCodeAt(i2 + 1)] >> 4; arr[curByte++] = tmp & 255; } if (placeHoldersLen === 1) { tmp = revLookup[b64.charCodeAt(i2)] << 10 | revLookup[b64.charCodeAt(i2 + 1)] << 4 | revLookup[b64.charCodeAt(i2 + 2)] >> 2; arr[curByte++] = tmp >> 8 & 255; arr[curByte++] = tmp & 255; } return arr; } function tripletToBase64(num) { return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; } function encodeChunk(uint8, start, end) { var tmp; var output = []; for (var i2 = start; i2 < end; i2 += 3) { tmp = (uint8[i2] << 16 & 16711680) + (uint8[i2 + 1] << 8 & 65280) + (uint8[i2 + 2] & 255); output.push(tripletToBase64(tmp)); } return output.join(""); } function fromByteArray(uint8) { var tmp; var len2 = uint8.length; var extraBytes = len2 % 3; var parts = []; var maxChunkLength = 16383; for (var i2 = 0, len22 = len2 - extraBytes; i2 < len22; i2 += maxChunkLength) { parts.push(encodeChunk(uint8, i2, i2 + maxChunkLength > len22 ? len22 : i2 + maxChunkLength)); } if (extraBytes === 1) { tmp = uint8[len2 - 1]; parts.push( lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" ); } else if (extraBytes === 2) { tmp = (uint8[len2 - 2] << 8) + uint8[len2 - 1]; parts.push( lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" ); } return parts.join(""); } } }); // node_modules/js-tiktoken/dist/chunk-THGZSONF.js function bytePairMerge(piece, ranks) { let parts = Array.from( { length: piece.length }, (_, i) => ({ start: i, end: i + 1 }) ); while (parts.length > 1) { let minRank = null; for (let i = 0; i < parts.length - 1; i++) { const slice = piece.slice(parts[i].start, parts[i + 1].end); const rank = ranks.get(slice.join(",")); if (rank == null) continue; if (minRank == null || rank < minRank[0]) { minRank = [rank, i]; } } if (minRank != null) { const i = minRank[1]; parts[i] = { start: parts[i].start, end: parts[i + 1].end }; parts.splice(i + 1, 1); } else { break; } } return parts; } function bytePairEncode(piece, ranks) { if (piece.length === 1) return [ranks.get(piece.join(","))]; return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); } function escapeRegex(str2) { return str2.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); } function getEncodingNameForModel(model) { switch (model) { case "gpt2": { return "gpt2"; } case "code-cushman-001": case "code-cushman-002": case "code-davinci-001": case "code-davinci-002": case "cushman-codex": case "davinci-codex": case "text-davinci-002": case "text-davinci-003": { return "p50k_base"; } case "code-davinci-edit-001": case "text-davinci-edit-001": { return "p50k_edit"; } case "ada": case "babbage": case "code-search-ada-code-001": case "code-search-babbage-code-001": case "curie": case "davinci": case "text-ada-001": case "text-babbage-001": case "text-curie-001": case "text-davinci-001": case "text-search-ada-doc-001": case "text-search-babbage-doc-001": case "text-search-curie-doc-001": case "text-search-davinci-doc-001": case "text-similarity-ada-001": case "text-similarity-babbage-001": case "text-similarity-curie-001": case "text-similarity-davinci-001": { return "r50k_base"; } case "gpt-3.5-turbo-16k-0613": case "gpt-3.5-turbo-16k": case "gpt-3.5-turbo-0613": case "gpt-3.5-turbo-0301": case "gpt-3.5-turbo": case "gpt-4-32k-0613": case "gpt-4-32k-0314": case "gpt-4-32k": case "gpt-4-0613": case "gpt-4-0314": case "gpt-4": case "text-embedding-ada-002": { return "cl100k_base"; } default: throw new Error("Unknown model"); } } var import_base64_js, _Tiktoken, Tiktoken; var init_chunk_THGZSONF = __esm({ "node_modules/js-tiktoken/dist/chunk-THGZSONF.js"() { init_chunk_XXPGZHWZ(); import_base64_js = __toESM(require_base64_js(), 1); _Tiktoken = class { constructor(ranks, extendedSpecialTokens) { /** @internal */ __publicField(this, "specialTokens"); /** @internal */ __publicField(this, "inverseSpecialTokens"); /** @internal */ __publicField(this, "patStr"); /** @internal */ __publicField(this, "textEncoder", new TextEncoder()); /** @internal */ __publicField(this, "textDecoder", new TextDecoder("utf-8")); /** @internal */ __publicField(this, "rankMap", /* @__PURE__ */ new Map()); /** @internal */ __publicField(this, "textMap", /* @__PURE__ */ new Map()); this.patStr = ranks.pat_str; const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo2, x) => { const [_, offsetStr, ...tokens] = x.split(" "); const offset = Number.parseInt(offsetStr, 10); tokens.forEach((token, i) => memo2[token] = offset + i); return memo2; }, {}); for (const [token, rank] of Object.entries(uncompressed)) { const bytes = import_base64_js.default.toByteArray(token); this.rankMap.set(bytes.join(","), rank); this.textMap.set(rank, bytes); } this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo2, [text4, rank]) => { memo2[rank] = this.textEncoder.encode(text4); return memo2; }, {}); } encode(text4, allowedSpecial = [], disallowedSpecial = "all") { var _a; const regexes = new RegExp(this.patStr, "ug"); const specialRegex = _Tiktoken.specialTokenRegex( Object.keys(this.specialTokens) ); const ret = []; const allowedSpecialSet = new Set( allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial ); const disallowedSpecialSet = new Set( disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( (x) => !allowedSpecialSet.has(x) ) : disallowedSpecial ); if (disallowedSpecialSet.size > 0) { const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ ...disallowedSpecialSet ]); const specialMatch = text4.match(disallowedSpecialRegex); if (specialMatch != null) { throw new Error( `The text contains a special token that is not allowed: ${specialMatch[0]}` ); } } let start = 0; while (true) { let nextSpecial = null; let startFind = start; while (true) { specialRegex.lastIndex = startFind; nextSpecial = specialRegex.exec(text4); if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) break; startFind = nextSpecial.index + 1; } const end = (_a = nextSpecial == null ? void 0 : nextSpecial.index) != null ? _a : text4.length; for (const match2 of text4.substring(start, end).matchAll(regexes)) { const piece = this.textEncoder.encode(match2[0]); const token2 = this.rankMap.get(piece.join(",")); if (token2 != null) { ret.push(token2); continue; } ret.push(...bytePairEncode(piece, this.rankMap)); } if (nextSpecial == null) break; let token = this.specialTokens[nextSpecial[0]]; ret.push(token); start = nextSpecial.index + nextSpecial[0].length; } return ret; } decode(tokens) { var _a; const res = []; let length = 0; for (let i2 = 0; i2 < tokens.length; ++i2) { const token = tokens[i2]; const bytes = (_a = this.textMap.get(token)) != null ? _a : this.inverseSpecialTokens[token]; if (bytes != null) { res.push(bytes); length += bytes.length; } } const mergedArray = new Uint8Array(length); let i = 0; for (const bytes of res) { mergedArray.set(bytes, i); i += bytes.length; } return this.textDecoder.decode(mergedArray); } }; Tiktoken = _Tiktoken; __publicField2(Tiktoken, "specialTokenRegex", (tokens) => { return new RegExp(tokens.map((i) => escapeRegex(i)).join("|"), "g"); }); } }); // node_modules/js-tiktoken/dist/lite.js var init_lite = __esm({ "node_modules/js-tiktoken/dist/lite.js"() { init_chunk_THGZSONF(); init_chunk_XXPGZHWZ(); } }); // node_modules/langchain/dist/util/tiktoken.js async function getEncoding(encoding, options) { if (!(encoding in cache)) { cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`, { signal: options == null ? void 0 : options.signal }).then((res) => res.json()).catch((e) => { delete cache[encoding]; throw e; }); } return new Tiktoken(await cache[encoding], options == null ? void 0 : options.extendedSpecialTokens); } async function encodingForModel(model, options) { return getEncoding(getEncodingNameForModel(model), options); } var cache, caller; var init_tiktoken = __esm({ "node_modules/langchain/dist/util/tiktoken.js"() { init_lite(); init_async_caller2(); cache = {}; caller = /* @__PURE__ */ new AsyncCaller2({}); } }); // node_modules/langchain/dist/base_language/count_tokens.js var getModelNameForTiktoken; var init_count_tokens = __esm({ "node_modules/langchain/dist/base_language/count_tokens.js"() { init_tiktoken(); getModelNameForTiktoken = (modelName) => { if (modelName.startsWith("gpt-3.5-turbo-16k-")) { return "gpt-3.5-turbo-16k"; } if (modelName.startsWith("gpt-3.5-turbo-")) { return "gpt-3.5-turbo"; } if (modelName.startsWith("gpt-4-32k-")) { return "gpt-4-32k"; } if (modelName.startsWith("gpt-4-")) { return "gpt-4"; } return modelName; }; } }); // node_modules/openai/node_modules/axios/lib/helpers/bind.js var require_bind = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/bind.js"(exports, module2) { "use strict"; module2.exports = function bind2(fn, thisArg) { return function wrap4() { var args = new Array(arguments.length); for (var i = 0; i < args.length; i++) { args[i] = arguments[i]; } return fn.apply(thisArg, args); }; }; } }); // node_modules/openai/node_modules/axios/lib/utils.js var require_utils = __commonJS({ "node_modules/openai/node_modules/axios/lib/utils.js"(exports, module2) { "use strict"; var bind2 = require_bind(); var toString7 = Object.prototype.toString; function isArray4(val) { return Array.isArray(val); } function isUndefined3(val) { return typeof val === "undefined"; } function isBuffer3(val) { return val !== null && !isUndefined3(val) && val.constructor !== null && !isUndefined3(val.constructor) && typeof val.constructor.isBuffer === "function" && val.constructor.isBuffer(val); } function isArrayBuffer2(val) { return toString7.call(val) === "[object ArrayBuffer]"; } function isFormData3(val) { return toString7.call(val) === "[object FormData]"; } function isArrayBufferView2(val) { var result; if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { result = ArrayBuffer.isView(val); } else { result = val && val.buffer && isArrayBuffer2(val.buffer); } return result; } function isString2(val) { return typeof val === "string"; } function isNumber2(val) { return typeof val === "number"; } function isObject4(val) { return val !== null && typeof val === "object"; } function isPlainObject4(val) { if (toString7.call(val) !== "[object Object]") { return false; } var prototype3 = Object.getPrototypeOf(val); return prototype3 === null || prototype3 === Object.prototype; } function isDate3(val) { return toString7.call(val) === "[object Date]"; } function isFile2(val) { return toString7.call(val) === "[object File]"; } function isBlob2(val) { return toString7.call(val) === "[object Blob]"; } function isFunction2(val) { return toString7.call(val) === "[object Function]"; } function isStream2(val) { return isObject4(val) && isFunction2(val.pipe); } function isURLSearchParams3(val) { return toString7.call(val) === "[object URLSearchParams]"; } function trim2(str2) { return str2.trim ? str2.trim() : str2.replace(/^\s+|\s+$/g, ""); } function isStandardBrowserEnv3() { if (typeof navigator !== "undefined" && (navigator.product === "ReactNative" || navigator.product === "NativeScript" || navigator.product === "NS")) { return false; } return typeof window !== "undefined" && typeof document !== "undefined"; } function forEach3(obj, fn) { if (obj === null || typeof obj === "undefined") { return; } if (typeof obj !== "object") { obj = [obj]; } if (isArray4(obj)) { for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } function merge5() { var result = {}; function assignValue(val, key) { if (isPlainObject4(result[key]) && isPlainObject4(val)) { result[key] = merge5(result[key], val); } else if (isPlainObject4(val)) { result[key] = merge5({}, val); } else if (isArray4(val)) { result[key] = val.slice(); } else { result[key] = val; } } for (var i = 0, l = arguments.length; i < l; i++) { forEach3(arguments[i], assignValue); } return result; } function extend5(a2, b, thisArg) { forEach3(b, function assignValue(val, key) { if (thisArg && typeof val === "function") { a2[key] = bind2(val, thisArg); } else { a2[key] = val; } }); return a2; } function stripBOM2(content3) { if (content3.charCodeAt(0) === 65279) { content3 = content3.slice(1); } return content3; } module2.exports = { isArray: isArray4, isArrayBuffer: isArrayBuffer2, isBuffer: isBuffer3, isFormData: isFormData3, isArrayBufferView: isArrayBufferView2, isString: isString2, isNumber: isNumber2, isObject: isObject4, isPlainObject: isPlainObject4, isUndefined: isUndefined3, isDate: isDate3, isFile: isFile2, isBlob: isBlob2, isFunction: isFunction2, isStream: isStream2, isURLSearchParams: isURLSearchParams3, isStandardBrowserEnv: isStandardBrowserEnv3, forEach: forEach3, merge: merge5, extend: extend5, trim: trim2, stripBOM: stripBOM2 }; } }); // node_modules/openai/node_modules/axios/lib/helpers/buildURL.js var require_buildURL = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/buildURL.js"(exports, module2) { "use strict"; var utils = require_utils(); function encode4(val) { return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); } module2.exports = function buildURL3(url, params, paramsSerializer) { if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (utils.isURLSearchParams(params)) { serializedParams = params.toString(); } else { var parts = []; utils.forEach(params, function serialize(val, key) { if (val === null || typeof val === "undefined") { return; } if (utils.isArray(val)) { key = key + "[]"; } else { val = [val]; } utils.forEach(val, function parseValue(v) { if (utils.isDate(v)) { v = v.toISOString(); } else if (utils.isObject(v)) { v = JSON.stringify(v); } parts.push(encode4(key) + "=" + encode4(v)); }); }); serializedParams = parts.join("&"); } if (serializedParams) { var hashmarkIndex = url.indexOf("#"); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; } return url; }; } }); // node_modules/openai/node_modules/axios/lib/core/InterceptorManager.js var require_InterceptorManager = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/InterceptorManager.js"(exports, module2) { "use strict"; var utils = require_utils(); function InterceptorManager2() { this.handlers = []; } InterceptorManager2.prototype.use = function use(fulfilled, rejected, options) { this.handlers.push({ fulfilled, rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; }; InterceptorManager2.prototype.eject = function eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } }; InterceptorManager2.prototype.forEach = function forEach3(fn) { utils.forEach(this.handlers, function forEachHandler(h2) { if (h2 !== null) { fn(h2); } }); }; module2.exports = InterceptorManager2; } }); // node_modules/openai/node_modules/axios/lib/helpers/normalizeHeaderName.js var require_normalizeHeaderName = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/normalizeHeaderName.js"(exports, module2) { "use strict"; var utils = require_utils(); module2.exports = function normalizeHeaderName(headers, normalizedName) { utils.forEach(headers, function processHeader(value, name) { if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) { headers[normalizedName] = value; delete headers[name]; } }); }; } }); // node_modules/openai/node_modules/axios/lib/core/enhanceError.js var require_enhanceError = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/enhanceError.js"(exports, module2) { "use strict"; module2.exports = function enhanceError2(error, config, code2, request, response) { error.config = config; if (code2) { error.code = code2; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON3() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code, status: this.response && this.response.status ? this.response.status : null }; }; return error; }; } }); // node_modules/openai/node_modules/axios/lib/defaults/transitional.js var require_transitional = __commonJS({ "node_modules/openai/node_modules/axios/lib/defaults/transitional.js"(exports, module2) { "use strict"; module2.exports = { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }; } }); // node_modules/openai/node_modules/axios/lib/core/createError.js var require_createError = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/createError.js"(exports, module2) { "use strict"; var enhanceError2 = require_enhanceError(); module2.exports = function createError3(message, config, code2, request, response) { var error = new Error(message); return enhanceError2(error, config, code2, request, response); }; } }); // node_modules/openai/node_modules/axios/lib/core/settle.js var require_settle = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/settle.js"(exports, module2) { "use strict"; var createError3 = require_createError(); module2.exports = function settle3(resolve, reject, response) { var validateStatus2 = response.config.validateStatus; if (!response.status || !validateStatus2 || validateStatus2(response.status)) { resolve(response); } else { reject(createError3( "Request failed with status code " + response.status, response.config, null, response.request, response )); } }; } }); // node_modules/openai/node_modules/axios/lib/helpers/cookies.js var require_cookies = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/cookies.js"(exports, module2) { "use strict"; var utils = require_utils(); module2.exports = utils.isStandardBrowserEnv() ? ( // Standard browser envs support document.cookie function standardBrowserEnv3() { return { write: function write(name, value, expires, path2, domain, secure) { var cookie = []; cookie.push(name + "=" + encodeURIComponent(value)); if (utils.isNumber(expires)) { cookie.push("expires=" + new Date(expires).toGMTString()); } if (utils.isString(path2)) { cookie.push("path=" + path2); } if (utils.isString(domain)) { cookie.push("domain=" + domain); } if (secure === true) { cookie.push("secure"); } document.cookie = cookie.join("; "); }, read: function read(name) { var match2 = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); return match2 ? decodeURIComponent(match2[3]) : null; }, remove: function remove(name) { this.write(name, "", Date.now() - 864e5); } }; }() ) : ( // Non standard browser env (web workers, react-native) lack needed support. function nonStandardBrowserEnv3() { return { write: function write() { }, read: function read() { return null; }, remove: function remove() { } }; }() ); } }); // node_modules/openai/node_modules/axios/lib/helpers/isAbsoluteURL.js var require_isAbsoluteURL = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/isAbsoluteURL.js"(exports, module2) { "use strict"; module2.exports = function isAbsoluteURL3(url) { return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); }; } }); // node_modules/openai/node_modules/axios/lib/helpers/combineURLs.js var require_combineURLs = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/combineURLs.js"(exports, module2) { "use strict"; module2.exports = function combineURLs3(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; }; } }); // node_modules/openai/node_modules/axios/lib/core/buildFullPath.js var require_buildFullPath = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/buildFullPath.js"(exports, module2) { "use strict"; var isAbsoluteURL3 = require_isAbsoluteURL(); var combineURLs3 = require_combineURLs(); module2.exports = function buildFullPath3(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL3(requestedURL)) { return combineURLs3(baseURL, requestedURL); } return requestedURL; }; } }); // node_modules/openai/node_modules/axios/lib/helpers/parseHeaders.js var require_parseHeaders = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/parseHeaders.js"(exports, module2) { "use strict"; var utils = require_utils(); var ignoreDuplicateOf2 = [ "age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent" ]; module2.exports = function parseHeaders(headers) { var parsed = {}; var key; var val; var i; if (!headers) { return parsed; } utils.forEach(headers.split("\n"), function parser2(line) { i = line.indexOf(":"); key = utils.trim(line.substr(0, i)).toLowerCase(); val = utils.trim(line.substr(i + 1)); if (key) { if (parsed[key] && ignoreDuplicateOf2.indexOf(key) >= 0) { return; } if (key === "set-cookie") { parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); } else { parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; } } }); return parsed; }; } }); // node_modules/openai/node_modules/axios/lib/helpers/isURLSameOrigin.js var require_isURLSameOrigin = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/isURLSameOrigin.js"(exports, module2) { "use strict"; var utils = require_utils(); module2.exports = utils.isStandardBrowserEnv() ? ( // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. function standardBrowserEnv3() { var msie = /(msie|trident)/i.test(navigator.userAgent); var urlParsingNode = document.createElement("a"); var originURL; function resolveURL(url) { var href = url; if (msie) { urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute("href", href); return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); return function isURLSameOrigin(requestURL) { var parsed = utils.isString(requestURL) ? resolveURL(requestURL) : requestURL; return parsed.protocol === originURL.protocol && parsed.host === originURL.host; }; }() ) : ( // Non standard browser envs (web workers, react-native) lack needed support. function nonStandardBrowserEnv3() { return function isURLSameOrigin() { return true; }; }() ); } }); // node_modules/openai/node_modules/axios/lib/cancel/Cancel.js var require_Cancel = __commonJS({ "node_modules/openai/node_modules/axios/lib/cancel/Cancel.js"(exports, module2) { "use strict"; function Cancel2(message) { this.message = message; } Cancel2.prototype.toString = function toString7() { return "Cancel" + (this.message ? ": " + this.message : ""); }; Cancel2.prototype.__CANCEL__ = true; module2.exports = Cancel2; } }); // node_modules/openai/node_modules/axios/lib/adapters/xhr.js var require_xhr = __commonJS({ "node_modules/openai/node_modules/axios/lib/adapters/xhr.js"(exports, module2) { "use strict"; var utils = require_utils(); var settle3 = require_settle(); var cookies = require_cookies(); var buildURL3 = require_buildURL(); var buildFullPath3 = require_buildFullPath(); var parseHeaders = require_parseHeaders(); var isURLSameOrigin = require_isURLSameOrigin(); var createError3 = require_createError(); var transitionalDefaults = require_transitional(); var Cancel2 = require_Cancel(); module2.exports = function xhrAdapter(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { var requestData = config.data; var requestHeaders = config.headers; var responseType = config.responseType; var onCanceled; function done() { if (config.cancelToken) { config.cancelToken.unsubscribe(onCanceled); } if (config.signal) { config.signal.removeEventListener("abort", onCanceled); } } if (utils.isFormData(requestData)) { delete requestHeaders["Content-Type"]; } var request = new XMLHttpRequest(); if (config.auth) { var username = config.auth.username || ""; var password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; requestHeaders.Authorization = "Basic " + btoa(username + ":" + password); } var fullPath = buildFullPath3(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL3(fullPath, config.params, config.paramsSerializer), true); request.timeout = config.timeout; function onloadend() { if (!request) { return; } var responseHeaders = "getAllResponseHeaders" in request ? parseHeaders(request.getAllResponseHeaders()) : null; var responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; var response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config, request }; settle3(function _resolve(value) { resolve(value); done(); }, function _reject(err) { reject(err); done(); }, response); request = null; } if ("onloadend" in request) { request.onloadend = onloadend; } else { request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { return; } setTimeout(onloadend); }; } request.onabort = function handleAbort() { if (!request) { return; } reject(createError3("Request aborted", config, "ECONNABORTED", request)); request = null; }; request.onerror = function handleError() { reject(createError3("Network Error", config, null, request)); request = null; }; request.ontimeout = function handleTimeout() { var timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; var transitional2 = config.transitional || transitionalDefaults; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(createError3( timeoutErrorMessage, config, transitional2.clarifyTimeoutError ? "ETIMEDOUT" : "ECONNABORTED", request )); request = null; }; if (utils.isStandardBrowserEnv()) { var xsrfValue = (config.withCredentials || isURLSameOrigin(fullPath)) && config.xsrfCookieName ? cookies.read(config.xsrfCookieName) : void 0; if (xsrfValue) { requestHeaders[config.xsrfHeaderName] = xsrfValue; } } if ("setRequestHeader" in request) { utils.forEach(requestHeaders, function setRequestHeader(val, key) { if (typeof requestData === "undefined" && key.toLowerCase() === "content-type") { delete requestHeaders[key]; } else { request.setRequestHeader(key, val); } }); } if (!utils.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } if (responseType && responseType !== "json") { request.responseType = config.responseType; } if (typeof config.onDownloadProgress === "function") { request.addEventListener("progress", config.onDownloadProgress); } if (typeof config.onUploadProgress === "function" && request.upload) { request.upload.addEventListener("progress", config.onUploadProgress); } if (config.cancelToken || config.signal) { onCanceled = function(cancel) { if (!request) { return; } reject(!cancel || cancel && cancel.type ? new Cancel2("canceled") : cancel); request.abort(); request = null; }; config.cancelToken && config.cancelToken.subscribe(onCanceled); if (config.signal) { config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); } } if (!requestData) { requestData = null; } request.send(requestData); }); }; } }); // node_modules/openai/node_modules/axios/lib/defaults/index.js var require_defaults = __commonJS({ "node_modules/openai/node_modules/axios/lib/defaults/index.js"(exports, module2) { "use strict"; var utils = require_utils(); var normalizeHeaderName = require_normalizeHeaderName(); var enhanceError2 = require_enhanceError(); var transitionalDefaults = require_transitional(); var DEFAULT_CONTENT_TYPE2 = { "Content-Type": "application/x-www-form-urlencoded" }; function setContentTypeIfUnset(headers, value) { if (!utils.isUndefined(headers) && utils.isUndefined(headers["Content-Type"])) { headers["Content-Type"] = value; } } function getDefaultAdapter() { var adapter; if (typeof XMLHttpRequest !== "undefined") { adapter = require_xhr(); } else if (typeof process !== "undefined" && Object.prototype.toString.call(process) === "[object process]") { adapter = require_xhr(); } return adapter; } function stringifySafely2(rawValue, parser2, encoder) { if (utils.isString(rawValue)) { try { (parser2 || JSON.parse)(rawValue); return utils.trim(rawValue); } catch (e) { if (e.name !== "SyntaxError") { throw e; } } } return (encoder || JSON.stringify)(rawValue); } var defaults2 = { transitional: transitionalDefaults, adapter: getDefaultAdapter(), transformRequest: [function transformRequest2(data, headers) { normalizeHeaderName(headers, "Accept"); normalizeHeaderName(headers, "Content-Type"); if (utils.isFormData(data) || utils.isArrayBuffer(data) || utils.isBuffer(data) || utils.isStream(data) || utils.isFile(data) || utils.isBlob(data)) { return data; } if (utils.isArrayBufferView(data)) { return data.buffer; } if (utils.isURLSearchParams(data)) { setContentTypeIfUnset(headers, "application/x-www-form-urlencoded;charset=utf-8"); return data.toString(); } if (utils.isObject(data) || headers && headers["Content-Type"] === "application/json") { setContentTypeIfUnset(headers, "application/json"); return stringifySafely2(data); } return data; }], transformResponse: [function transformResponse2(data) { var transitional2 = this.transitional || defaults2.transitional; var silentJSONParsing = transitional2 && transitional2.silentJSONParsing; var forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; var strictJSONParsing = !silentJSONParsing && this.responseType === "json"; if (strictJSONParsing || forcedJSONParsing && utils.isString(data) && data.length) { try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === "SyntaxError") { throw enhanceError2(e, this, "E_JSON_PARSE"); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", maxContentLength: -1, maxBodyLength: -1, validateStatus: function validateStatus2(status) { return status >= 200 && status < 300; }, headers: { common: { "Accept": "application/json, text/plain, */*" } } }; utils.forEach(["delete", "get", "head"], function forEachMethodNoData3(method) { defaults2.headers[method] = {}; }); utils.forEach(["post", "put", "patch"], function forEachMethodWithData3(method) { defaults2.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE2); }); module2.exports = defaults2; } }); // node_modules/openai/node_modules/axios/lib/core/transformData.js var require_transformData = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/transformData.js"(exports, module2) { "use strict"; var utils = require_utils(); var defaults2 = require_defaults(); module2.exports = function transformData2(data, headers, fns) { var context = this || defaults2; utils.forEach(fns, function transform(fn) { data = fn.call(context, data, headers); }); return data; }; } }); // node_modules/openai/node_modules/axios/lib/cancel/isCancel.js var require_isCancel = __commonJS({ "node_modules/openai/node_modules/axios/lib/cancel/isCancel.js"(exports, module2) { "use strict"; module2.exports = function isCancel3(value) { return !!(value && value.__CANCEL__); }; } }); // node_modules/openai/node_modules/axios/lib/core/dispatchRequest.js var require_dispatchRequest = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/dispatchRequest.js"(exports, module2) { "use strict"; var utils = require_utils(); var transformData2 = require_transformData(); var isCancel3 = require_isCancel(); var defaults2 = require_defaults(); var Cancel2 = require_Cancel(); function throwIfCancellationRequested2(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } if (config.signal && config.signal.aborted) { throw new Cancel2("canceled"); } } module2.exports = function dispatchRequest2(config) { throwIfCancellationRequested2(config); config.headers = config.headers || {}; config.data = transformData2.call( config, config.data, config.headers, config.transformRequest ); config.headers = utils.merge( config.headers.common || {}, config.headers[config.method] || {}, config.headers ); utils.forEach( ["delete", "get", "head", "post", "put", "patch", "common"], function cleanHeaderConfig(method) { delete config.headers[method]; } ); var adapter = config.adapter || defaults2.adapter; return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested2(config); response.data = transformData2.call( config, response.data, response.headers, config.transformResponse ); return response; }, function onAdapterRejection(reason) { if (!isCancel3(reason)) { throwIfCancellationRequested2(config); if (reason && reason.response) { reason.response.data = transformData2.call( config, reason.response.data, reason.response.headers, config.transformResponse ); } } return Promise.reject(reason); }); }; } }); // node_modules/openai/node_modules/axios/lib/core/mergeConfig.js var require_mergeConfig = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/mergeConfig.js"(exports, module2) { "use strict"; var utils = require_utils(); module2.exports = function mergeConfig3(config1, config2) { config2 = config2 || {}; var config = {}; function getMergedValue(target, source) { if (utils.isPlainObject(target) && utils.isPlainObject(source)) { return utils.merge(target, source); } else if (utils.isPlainObject(source)) { return utils.merge({}, source); } else if (utils.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(prop) { if (!utils.isUndefined(config2[prop])) { return getMergedValue(config1[prop], config2[prop]); } else if (!utils.isUndefined(config1[prop])) { return getMergedValue(void 0, config1[prop]); } } function valueFromConfig2(prop) { if (!utils.isUndefined(config2[prop])) { return getMergedValue(void 0, config2[prop]); } } function defaultToConfig2(prop) { if (!utils.isUndefined(config2[prop])) { return getMergedValue(void 0, config2[prop]); } else if (!utils.isUndefined(config1[prop])) { return getMergedValue(void 0, config1[prop]); } } function mergeDirectKeys(prop) { if (prop in config2) { return getMergedValue(config1[prop], config2[prop]); } else if (prop in config1) { return getMergedValue(void 0, config1[prop]); } } var mergeMap = { "url": valueFromConfig2, "method": valueFromConfig2, "data": valueFromConfig2, "baseURL": defaultToConfig2, "transformRequest": defaultToConfig2, "transformResponse": defaultToConfig2, "paramsSerializer": defaultToConfig2, "timeout": defaultToConfig2, "timeoutMessage": defaultToConfig2, "withCredentials": defaultToConfig2, "adapter": defaultToConfig2, "responseType": defaultToConfig2, "xsrfCookieName": defaultToConfig2, "xsrfHeaderName": defaultToConfig2, "onUploadProgress": defaultToConfig2, "onDownloadProgress": defaultToConfig2, "decompress": defaultToConfig2, "maxContentLength": defaultToConfig2, "maxBodyLength": defaultToConfig2, "transport": defaultToConfig2, "httpAgent": defaultToConfig2, "httpsAgent": defaultToConfig2, "cancelToken": defaultToConfig2, "socketPath": defaultToConfig2, "responseEncoding": defaultToConfig2, "validateStatus": mergeDirectKeys }; utils.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { var merge5 = mergeMap[prop] || mergeDeepProperties; var configValue = merge5(prop); utils.isUndefined(configValue) && merge5 !== mergeDirectKeys || (config[prop] = configValue); }); return config; }; } }); // node_modules/openai/node_modules/axios/lib/env/data.js var require_data = __commonJS({ "node_modules/openai/node_modules/axios/lib/env/data.js"(exports, module2) { module2.exports = { "version": "0.26.1" }; } }); // node_modules/openai/node_modules/axios/lib/helpers/validator.js var require_validator = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/validator.js"(exports, module2) { "use strict"; var VERSION3 = require_data().version; var validators3 = {}; ["object", "boolean", "number", "function", "string", "symbol"].forEach(function(type2, i) { validators3[type2] = function validator(thing) { return typeof thing === type2 || "a" + (i < 1 ? "n " : " ") + type2; }; }); var deprecatedWarnings2 = {}; validators3.transitional = function transitional2(validator, version2, message) { function formatMessage(opt, desc) { return "[Axios v" + VERSION3 + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); } return function(value, opt, opts) { if (validator === false) { throw new Error(formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : ""))); } if (version2 && !deprecatedWarnings2[opt]) { deprecatedWarnings2[opt] = true; console.warn( formatMessage( opt, " has been deprecated since v" + version2 + " and will be removed in the near future" ) ); } return validator ? validator(value, opt, opts) : true; }; }; function assertOptions2(options, schema2, allowUnknown) { if (typeof options !== "object") { throw new TypeError("options must be an object"); } var keys3 = Object.keys(options); var i = keys3.length; while (i-- > 0) { var opt = keys3[i]; var validator = schema2[opt]; if (validator) { var value = options[opt]; var result = value === void 0 || validator(value, opt, options); if (result !== true) { throw new TypeError("option " + opt + " must be " + result); } continue; } if (allowUnknown !== true) { throw Error("Unknown option " + opt); } } } module2.exports = { assertOptions: assertOptions2, validators: validators3 }; } }); // node_modules/openai/node_modules/axios/lib/core/Axios.js var require_Axios = __commonJS({ "node_modules/openai/node_modules/axios/lib/core/Axios.js"(exports, module2) { "use strict"; var utils = require_utils(); var buildURL3 = require_buildURL(); var InterceptorManager2 = require_InterceptorManager(); var dispatchRequest2 = require_dispatchRequest(); var mergeConfig3 = require_mergeConfig(); var validator = require_validator(); var validators3 = validator.validators; function Axios3(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager2(), response: new InterceptorManager2() }; } Axios3.prototype.request = function request(configOrUrl, config) { if (typeof configOrUrl === "string") { config = config || {}; config.url = configOrUrl; } else { config = configOrUrl || {}; } config = mergeConfig3(this.defaults, config); if (config.method) { config.method = config.method.toLowerCase(); } else if (this.defaults.method) { config.method = this.defaults.method.toLowerCase(); } else { config.method = "get"; } var transitional2 = config.transitional; if (transitional2 !== void 0) { validator.assertOptions(transitional2, { silentJSONParsing: validators3.transitional(validators3.boolean), forcedJSONParsing: validators3.transitional(validators3.boolean), clarifyTimeoutError: validators3.transitional(validators3.boolean) }, false); } var requestInterceptorChain = []; var synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); var responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); var promise; if (!synchronousRequestInterceptors) { var chain = [dispatchRequest2, void 0]; Array.prototype.unshift.apply(chain, requestInterceptorChain); chain = chain.concat(responseInterceptorChain); promise = Promise.resolve(config); while (chain.length) { promise = promise.then(chain.shift(), chain.shift()); } return promise; } var newConfig = config; while (requestInterceptorChain.length) { var onFulfilled = requestInterceptorChain.shift(); var onRejected = requestInterceptorChain.shift(); try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected(error); break; } } try { promise = dispatchRequest2(newConfig); } catch (error) { return Promise.reject(error); } while (responseInterceptorChain.length) { promise = promise.then(responseInterceptorChain.shift(), responseInterceptorChain.shift()); } return promise; }; Axios3.prototype.getUri = function getUri(config) { config = mergeConfig3(this.defaults, config); return buildURL3(config.url, config.params, config.paramsSerializer).replace(/^\?/, ""); }; utils.forEach(["delete", "get", "head", "options"], function forEachMethodNoData3(method) { Axios3.prototype[method] = function(url, config) { return this.request(mergeConfig3(config || {}, { method, url, data: (config || {}).data })); }; }); utils.forEach(["post", "put", "patch"], function forEachMethodWithData3(method) { Axios3.prototype[method] = function(url, data, config) { return this.request(mergeConfig3(config || {}, { method, url, data })); }; }); module2.exports = Axios3; } }); // node_modules/openai/node_modules/axios/lib/cancel/CancelToken.js var require_CancelToken = __commonJS({ "node_modules/openai/node_modules/axios/lib/cancel/CancelToken.js"(exports, module2) { "use strict"; var Cancel2 = require_Cancel(); function CancelToken3(executor) { if (typeof executor !== "function") { throw new TypeError("executor must be a function."); } var resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); var token = this; this.promise.then(function(cancel) { if (!token._listeners) return; var i; var l = token._listeners.length; for (i = 0; i < l; i++) { token._listeners[i](cancel); } token._listeners = null; }); this.promise.then = function(onfulfilled) { var _resolve; var promise = new Promise(function(resolve) { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = function reject() { token.unsubscribe(_resolve); }; return promise; }; executor(function cancel(message) { if (token.reason) { return; } token.reason = new Cancel2(message); resolvePromise(token.reason); }); } CancelToken3.prototype.throwIfRequested = function throwIfRequested() { if (this.reason) { throw this.reason; } }; CancelToken3.prototype.subscribe = function subscribe(listener) { if (this.reason) { listener(this.reason); return; } if (this._listeners) { this._listeners.push(listener); } else { this._listeners = [listener]; } }; CancelToken3.prototype.unsubscribe = function unsubscribe(listener) { if (!this._listeners) { return; } var index2 = this._listeners.indexOf(listener); if (index2 !== -1) { this._listeners.splice(index2, 1); } }; CancelToken3.source = function source() { var cancel; var token = new CancelToken3(function executor(c) { cancel = c; }); return { token, cancel }; }; module2.exports = CancelToken3; } }); // node_modules/openai/node_modules/axios/lib/helpers/spread.js var require_spread = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/spread.js"(exports, module2) { "use strict"; module2.exports = function spread3(callback) { return function wrap4(arr) { return callback.apply(null, arr); }; }; } }); // node_modules/openai/node_modules/axios/lib/helpers/isAxiosError.js var require_isAxiosError = __commonJS({ "node_modules/openai/node_modules/axios/lib/helpers/isAxiosError.js"(exports, module2) { "use strict"; var utils = require_utils(); module2.exports = function isAxiosError3(payload) { return utils.isObject(payload) && payload.isAxiosError === true; }; } }); // node_modules/openai/node_modules/axios/lib/axios.js var require_axios = __commonJS({ "node_modules/openai/node_modules/axios/lib/axios.js"(exports, module2) { "use strict"; var utils = require_utils(); var bind2 = require_bind(); var Axios3 = require_Axios(); var mergeConfig3 = require_mergeConfig(); var defaults2 = require_defaults(); function createInstance2(defaultConfig) { var context = new Axios3(defaultConfig); var instance = bind2(Axios3.prototype.request, context); utils.extend(instance, Axios3.prototype, context); utils.extend(instance, context); instance.create = function create2(instanceConfig) { return createInstance2(mergeConfig3(defaultConfig, instanceConfig)); }; return instance; } var axios2 = createInstance2(defaults2); axios2.Axios = Axios3; axios2.Cancel = require_Cancel(); axios2.CancelToken = require_CancelToken(); axios2.isCancel = require_isCancel(); axios2.VERSION = require_data().version; axios2.all = function all5(promises) { return Promise.all(promises); }; axios2.spread = require_spread(); axios2.isAxiosError = require_isAxiosError(); module2.exports = axios2; module2.exports.default = axios2; } }); // node_modules/openai/node_modules/axios/index.js var require_axios2 = __commonJS({ "node_modules/openai/node_modules/axios/index.js"(exports, module2) { module2.exports = require_axios(); } }); // node_modules/openai/dist/base.js var require_base = __commonJS({ "node_modules/openai/dist/base.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RequiredError = exports.BaseAPI = exports.COLLECTION_FORMATS = exports.BASE_PATH = void 0; var axios_1 = require_axios2(); exports.BASE_PATH = "https://api.openai.com/v1".replace(/\/+$/, ""); exports.COLLECTION_FORMATS = { csv: ",", ssv: " ", tsv: " ", pipes: "|" }; var BaseAPI = class { constructor(configuration, basePath = exports.BASE_PATH, axios2 = axios_1.default) { this.basePath = basePath; this.axios = axios2; if (configuration) { this.configuration = configuration; this.basePath = configuration.basePath || this.basePath; } } }; exports.BaseAPI = BaseAPI; var RequiredError = class extends Error { constructor(field, msg) { super(msg); this.field = field; this.name = "RequiredError"; } }; exports.RequiredError = RequiredError; } }); // node_modules/openai/dist/common.js var require_common = __commonJS({ "node_modules/openai/dist/common.js"(exports) { "use strict"; var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.createRequestFunction = exports.toPathString = exports.serializeDataIfNeeded = exports.setSearchParams = exports.setOAuthToObject = exports.setBearerAuthToObject = exports.setBasicAuthToObject = exports.setApiKeyToObject = exports.assertParamExists = exports.DUMMY_BASE_URL = void 0; var base_1 = require_base(); exports.DUMMY_BASE_URL = "https://example.com"; exports.assertParamExists = function(functionName, paramName, paramValue) { if (paramValue === null || paramValue === void 0) { throw new base_1.RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); } }; exports.setApiKeyToObject = function(object, keyParamName, configuration) { return __awaiter(this, void 0, void 0, function* () { if (configuration && configuration.apiKey) { const localVarApiKeyValue = typeof configuration.apiKey === "function" ? yield configuration.apiKey(keyParamName) : yield configuration.apiKey; object[keyParamName] = localVarApiKeyValue; } }); }; exports.setBasicAuthToObject = function(object, configuration) { if (configuration && (configuration.username || configuration.password)) { object["auth"] = { username: configuration.username, password: configuration.password }; } }; exports.setBearerAuthToObject = function(object, configuration) { return __awaiter(this, void 0, void 0, function* () { if (configuration && configuration.accessToken) { const accessToken = typeof configuration.accessToken === "function" ? yield configuration.accessToken() : yield configuration.accessToken; object["Authorization"] = "Bearer " + accessToken; } }); }; exports.setOAuthToObject = function(object, name, scopes, configuration) { return __awaiter(this, void 0, void 0, function* () { if (configuration && configuration.accessToken) { const localVarAccessTokenValue = typeof configuration.accessToken === "function" ? yield configuration.accessToken(name, scopes) : yield configuration.accessToken; object["Authorization"] = "Bearer " + localVarAccessTokenValue; } }); }; function setFlattenedQueryParams(urlSearchParams, parameter, key = "") { if (parameter == null) return; if (typeof parameter === "object") { if (Array.isArray(parameter)) { parameter.forEach((item) => setFlattenedQueryParams(urlSearchParams, item, key)); } else { Object.keys(parameter).forEach((currentKey) => setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== "" ? "." : ""}${currentKey}`)); } } else { if (urlSearchParams.has(key)) { urlSearchParams.append(key, parameter); } else { urlSearchParams.set(key, parameter); } } } exports.setSearchParams = function(url, ...objects) { const searchParams = new URLSearchParams(url.search); setFlattenedQueryParams(searchParams, objects); url.search = searchParams.toString(); }; exports.serializeDataIfNeeded = function(value, requestOptions, configuration) { const nonString = typeof value !== "string"; const needsSerialization = nonString && configuration && configuration.isJsonMime ? configuration.isJsonMime(requestOptions.headers["Content-Type"]) : nonString; return needsSerialization ? JSON.stringify(value !== void 0 ? value : {}) : value || ""; }; exports.toPathString = function(url) { return url.pathname + url.search + url.hash; }; exports.createRequestFunction = function(axiosArgs, globalAxios, BASE_PATH, configuration) { return (axios2 = globalAxios, basePath = BASE_PATH) => { const axiosRequestArgs = Object.assign(Object.assign({}, axiosArgs.options), { url: ((configuration === null || configuration === void 0 ? void 0 : configuration.basePath) || basePath) + axiosArgs.url }); return axios2.request(axiosRequestArgs); }; }; } }); // node_modules/openai/dist/api.js var require_api = __commonJS({ "node_modules/openai/dist/api.js"(exports) { "use strict"; var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.OpenAIApi = exports.OpenAIApiFactory = exports.OpenAIApiFp = exports.OpenAIApiAxiosParamCreator = exports.CreateImageRequestResponseFormatEnum = exports.CreateImageRequestSizeEnum = exports.ChatCompletionResponseMessageRoleEnum = exports.ChatCompletionRequestMessageRoleEnum = void 0; var axios_1 = require_axios2(); var common_1 = require_common(); var base_1 = require_base(); exports.ChatCompletionRequestMessageRoleEnum = { System: "system", User: "user", Assistant: "assistant", Function: "function" }; exports.ChatCompletionResponseMessageRoleEnum = { System: "system", User: "user", Assistant: "assistant", Function: "function" }; exports.CreateImageRequestSizeEnum = { _256x256: "256x256", _512x512: "512x512", _1024x1024: "1024x1024" }; exports.CreateImageRequestResponseFormatEnum = { Url: "url", B64Json: "b64_json" }; exports.OpenAIApiAxiosParamCreator = function(configuration) { return { /** * * @summary Immediately cancel a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to cancel * @param {*} [options] Override http request option. * @throws {RequiredError} */ cancelFineTune: (fineTuneId, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("cancelFineTune", "fineTuneId", fineTuneId); const localVarPath = `/fine-tunes/{fine_tune_id}/cancel`.replace(`{${"fine_tune_id"}}`, encodeURIComponent(String(fineTuneId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions). * @param {CreateAnswerRequest} createAnswerRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createAnswer: (createAnswerRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createAnswer", "createAnswerRequest", createAnswerRequest); const localVarPath = `/answers`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createAnswerRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates a model response for the given chat conversation. * @param {CreateChatCompletionRequest} createChatCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createChatCompletion: (createChatCompletionRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createChatCompletion", "createChatCompletionRequest", createChatCompletionRequest); const localVarPath = `/chat/completions`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createChatCompletionRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases. * @param {CreateClassificationRequest} createClassificationRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createClassification: (createClassificationRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createClassification", "createClassificationRequest", createClassificationRequest); const localVarPath = `/classifications`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createClassificationRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates a completion for the provided prompt and parameters. * @param {CreateCompletionRequest} createCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createCompletion: (createCompletionRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createCompletion", "createCompletionRequest", createCompletionRequest); const localVarPath = `/completions`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createCompletionRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates a new edit for the provided input, instruction, and parameters. * @param {CreateEditRequest} createEditRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createEdit: (createEditRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createEdit", "createEditRequest", createEditRequest); const localVarPath = `/edits`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createEditRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates an embedding vector representing the input text. * @param {CreateEmbeddingRequest} createEmbeddingRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createEmbedding: (createEmbeddingRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createEmbedding", "createEmbeddingRequest", createEmbeddingRequest); const localVarPath = `/embeddings`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createEmbeddingRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit. * @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the `purpose` is set to \\\"fine-tune\\\", each line is a JSON record with \\\"prompt\\\" and \\\"completion\\\" fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data). * @param {string} purpose The intended purpose of the uploaded documents. Use \\\"fine-tune\\\" for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createFile: (file, purpose, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createFile", "file", file); common_1.assertParamExists("createFile", "purpose", purpose); const localVarPath = `/files`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; const localVarFormParams = new (configuration && configuration.formDataCtor || FormData)(); if (file !== void 0) { localVarFormParams.append("file", file); } if (purpose !== void 0) { localVarFormParams.append("purpose", purpose); } localVarHeaderParameter["Content-Type"] = "multipart/form-data"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers); localVarRequestOptions.data = localVarFormParams; return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {CreateFineTuneRequest} createFineTuneRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createFineTune: (createFineTuneRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createFineTune", "createFineTuneRequest", createFineTuneRequest); const localVarPath = `/fine-tunes`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createFineTuneRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates an image given a prompt. * @param {CreateImageRequest} createImageRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImage: (createImageRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createImage", "createImageRequest", createImageRequest); const localVarPath = `/images/generations`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createImageRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates an edited or extended image given an original image and a prompt. * @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. * @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters. * @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImageEdit: (image2, prompt, mask, n, size, responseFormat, user, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createImageEdit", "image", image2); common_1.assertParamExists("createImageEdit", "prompt", prompt); const localVarPath = `/images/edits`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; const localVarFormParams = new (configuration && configuration.formDataCtor || FormData)(); if (image2 !== void 0) { localVarFormParams.append("image", image2); } if (mask !== void 0) { localVarFormParams.append("mask", mask); } if (prompt !== void 0) { localVarFormParams.append("prompt", prompt); } if (n !== void 0) { localVarFormParams.append("n", n); } if (size !== void 0) { localVarFormParams.append("size", size); } if (responseFormat !== void 0) { localVarFormParams.append("response_format", responseFormat); } if (user !== void 0) { localVarFormParams.append("user", user); } localVarHeaderParameter["Content-Type"] = "multipart/form-data"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers); localVarRequestOptions.data = localVarFormParams; return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Creates a variation of a given image. * @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImageVariation: (image2, n, size, responseFormat, user, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createImageVariation", "image", image2); const localVarPath = `/images/variations`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; const localVarFormParams = new (configuration && configuration.formDataCtor || FormData)(); if (image2 !== void 0) { localVarFormParams.append("image", image2); } if (n !== void 0) { localVarFormParams.append("n", n); } if (size !== void 0) { localVarFormParams.append("size", size); } if (responseFormat !== void 0) { localVarFormParams.append("response_format", responseFormat); } if (user !== void 0) { localVarFormParams.append("user", user); } localVarHeaderParameter["Content-Type"] = "multipart/form-data"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers); localVarRequestOptions.data = localVarFormParams; return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Classifies if text violates OpenAI\'s Content Policy * @param {CreateModerationRequest} createModerationRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createModeration: (createModerationRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createModeration", "createModerationRequest", createModerationRequest); const localVarPath = `/moderations`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createModerationRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query. * @param {string} engineId The ID of the engine to use for this request. You can select one of `ada`, `babbage`, `curie`, or `davinci`. * @param {CreateSearchRequest} createSearchRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createSearch: (engineId, createSearchRequest, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createSearch", "engineId", engineId); common_1.assertParamExists("createSearch", "createSearchRequest", createSearchRequest); const localVarPath = `/engines/{engine_id}/search`.replace(`{${"engine_id"}}`, encodeURIComponent(String(engineId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; localVarHeaderParameter["Content-Type"] = "application/json"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); localVarRequestOptions.data = common_1.serializeDataIfNeeded(createSearchRequest, localVarRequestOptions, configuration); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Transcribes audio into the input language. * @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createTranscription: (file, model, prompt, responseFormat, temperature, language, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createTranscription", "file", file); common_1.assertParamExists("createTranscription", "model", model); const localVarPath = `/audio/transcriptions`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; const localVarFormParams = new (configuration && configuration.formDataCtor || FormData)(); if (file !== void 0) { localVarFormParams.append("file", file); } if (model !== void 0) { localVarFormParams.append("model", model); } if (prompt !== void 0) { localVarFormParams.append("prompt", prompt); } if (responseFormat !== void 0) { localVarFormParams.append("response_format", responseFormat); } if (temperature !== void 0) { localVarFormParams.append("temperature", temperature); } if (language !== void 0) { localVarFormParams.append("language", language); } localVarHeaderParameter["Content-Type"] = "multipart/form-data"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers); localVarRequestOptions.data = localVarFormParams; return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Translates audio into into English. * @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createTranslation: (file, model, prompt, responseFormat, temperature, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("createTranslation", "file", file); common_1.assertParamExists("createTranslation", "model", model); const localVarPath = `/audio/translations`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "POST" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; const localVarFormParams = new (configuration && configuration.formDataCtor || FormData)(); if (file !== void 0) { localVarFormParams.append("file", file); } if (model !== void 0) { localVarFormParams.append("model", model); } if (prompt !== void 0) { localVarFormParams.append("prompt", prompt); } if (responseFormat !== void 0) { localVarFormParams.append("response_format", responseFormat); } if (temperature !== void 0) { localVarFormParams.append("temperature", temperature); } localVarHeaderParameter["Content-Type"] = "multipart/form-data"; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), localVarFormParams.getHeaders()), headersFromBaseOptions), options.headers); localVarRequestOptions.data = localVarFormParams; return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Delete a file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteFile: (fileId, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("deleteFile", "fileId", fileId); const localVarPath = `/files/{file_id}`.replace(`{${"file_id"}}`, encodeURIComponent(String(fileId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "DELETE" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Delete a fine-tuned model. You must have the Owner role in your organization. * @param {string} model The model to delete * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteModel: (model, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("deleteModel", "model", model); const localVarPath = `/models/{model}`.replace(`{${"model"}}`, encodeURIComponent(String(model))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "DELETE" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Returns the contents of the specified file * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ downloadFile: (fileId, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("downloadFile", "fileId", fileId); const localVarPath = `/files/{file_id}/content`.replace(`{${"file_id"}}`, encodeURIComponent(String(fileId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ listEngines: (options = {}) => __awaiter(this, void 0, void 0, function* () { const localVarPath = `/engines`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Returns a list of files that belong to the user\'s organization. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFiles: (options = {}) => __awaiter(this, void 0, void 0, function* () { const localVarPath = `/files`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Get fine-grained status updates for a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to get events for. * @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a `data: [DONE]` message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFineTuneEvents: (fineTuneId, stream, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("listFineTuneEvents", "fineTuneId", fineTuneId); const localVarPath = `/fine-tunes/{fine_tune_id}/events`.replace(`{${"fine_tune_id"}}`, encodeURIComponent(String(fineTuneId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; if (stream !== void 0) { localVarQueryParameter["stream"] = stream; } common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary List your organization\'s fine-tuning jobs * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFineTunes: (options = {}) => __awaiter(this, void 0, void 0, function* () { const localVarPath = `/fine-tunes`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Lists the currently available models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listModels: (options = {}) => __awaiter(this, void 0, void 0, function* () { const localVarPath = `/models`; const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Retrieves a model instance, providing basic information about it such as the owner and availability. * @param {string} engineId The ID of the engine to use for this request * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ retrieveEngine: (engineId, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("retrieveEngine", "engineId", engineId); const localVarPath = `/engines/{engine_id}`.replace(`{${"engine_id"}}`, encodeURIComponent(String(engineId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Returns information about a specific file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveFile: (fileId, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("retrieveFile", "fileId", fileId); const localVarPath = `/files/{file_id}`.replace(`{${"file_id"}}`, encodeURIComponent(String(fileId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {string} fineTuneId The ID of the fine-tune job * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveFineTune: (fineTuneId, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("retrieveFineTune", "fineTuneId", fineTuneId); const localVarPath = `/fine-tunes/{fine_tune_id}`.replace(`{${"fine_tune_id"}}`, encodeURIComponent(String(fineTuneId))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }), /** * * @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning. * @param {string} model The ID of the model to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveModel: (model, options = {}) => __awaiter(this, void 0, void 0, function* () { common_1.assertParamExists("retrieveModel", "model", model); const localVarPath = `/models/{model}`.replace(`{${"model"}}`, encodeURIComponent(String(model))); const localVarUrlObj = new URL(localVarPath, common_1.DUMMY_BASE_URL); let baseOptions; if (configuration) { baseOptions = configuration.baseOptions; } const localVarRequestOptions = Object.assign(Object.assign({ method: "GET" }, baseOptions), options); const localVarHeaderParameter = {}; const localVarQueryParameter = {}; common_1.setSearchParams(localVarUrlObj, localVarQueryParameter); let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; localVarRequestOptions.headers = Object.assign(Object.assign(Object.assign({}, localVarHeaderParameter), headersFromBaseOptions), options.headers); return { url: common_1.toPathString(localVarUrlObj), options: localVarRequestOptions }; }) }; }; exports.OpenAIApiFp = function(configuration) { const localVarAxiosParamCreator = exports.OpenAIApiAxiosParamCreator(configuration); return { /** * * @summary Immediately cancel a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to cancel * @param {*} [options] Override http request option. * @throws {RequiredError} */ cancelFineTune(fineTuneId, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.cancelFineTune(fineTuneId, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions). * @param {CreateAnswerRequest} createAnswerRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createAnswer(createAnswerRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createAnswer(createAnswerRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates a model response for the given chat conversation. * @param {CreateChatCompletionRequest} createChatCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createChatCompletion(createChatCompletionRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createChatCompletion(createChatCompletionRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases. * @param {CreateClassificationRequest} createClassificationRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createClassification(createClassificationRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createClassification(createClassificationRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates a completion for the provided prompt and parameters. * @param {CreateCompletionRequest} createCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createCompletion(createCompletionRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createCompletion(createCompletionRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates a new edit for the provided input, instruction, and parameters. * @param {CreateEditRequest} createEditRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createEdit(createEditRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createEdit(createEditRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates an embedding vector representing the input text. * @param {CreateEmbeddingRequest} createEmbeddingRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createEmbedding(createEmbeddingRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createEmbedding(createEmbeddingRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit. * @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the `purpose` is set to \\\"fine-tune\\\", each line is a JSON record with \\\"prompt\\\" and \\\"completion\\\" fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data). * @param {string} purpose The intended purpose of the uploaded documents. Use \\\"fine-tune\\\" for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createFile(file, purpose, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createFile(file, purpose, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {CreateFineTuneRequest} createFineTuneRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createFineTune(createFineTuneRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createFineTune(createFineTuneRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates an image given a prompt. * @param {CreateImageRequest} createImageRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImage(createImageRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createImage(createImageRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates an edited or extended image given an original image and a prompt. * @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. * @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters. * @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImageEdit(image2, prompt, mask, n, size, responseFormat, user, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createImageEdit(image2, prompt, mask, n, size, responseFormat, user, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Creates a variation of a given image. * @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImageVariation(image2, n, size, responseFormat, user, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createImageVariation(image2, n, size, responseFormat, user, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Classifies if text violates OpenAI\'s Content Policy * @param {CreateModerationRequest} createModerationRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createModeration(createModerationRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createModeration(createModerationRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query. * @param {string} engineId The ID of the engine to use for this request. You can select one of `ada`, `babbage`, `curie`, or `davinci`. * @param {CreateSearchRequest} createSearchRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createSearch(engineId, createSearchRequest, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createSearch(engineId, createSearchRequest, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Transcribes audio into the input language. * @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createTranscription(file, model, prompt, responseFormat, temperature, language, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createTranscription(file, model, prompt, responseFormat, temperature, language, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Translates audio into into English. * @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createTranslation(file, model, prompt, responseFormat, temperature, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.createTranslation(file, model, prompt, responseFormat, temperature, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Delete a file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteFile(fileId, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.deleteFile(fileId, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Delete a fine-tuned model. You must have the Owner role in your organization. * @param {string} model The model to delete * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteModel(model, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.deleteModel(model, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Returns the contents of the specified file * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ downloadFile(fileId, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.downloadFile(fileId, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ listEngines(options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.listEngines(options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Returns a list of files that belong to the user\'s organization. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFiles(options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.listFiles(options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Get fine-grained status updates for a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to get events for. * @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a `data: [DONE]` message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFineTuneEvents(fineTuneId, stream, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.listFineTuneEvents(fineTuneId, stream, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary List your organization\'s fine-tuning jobs * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFineTunes(options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.listFineTunes(options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Lists the currently available models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listModels(options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.listModels(options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Retrieves a model instance, providing basic information about it such as the owner and availability. * @param {string} engineId The ID of the engine to use for this request * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ retrieveEngine(engineId, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveEngine(engineId, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Returns information about a specific file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveFile(fileId, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveFile(fileId, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {string} fineTuneId The ID of the fine-tune job * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveFineTune(fineTuneId, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveFineTune(fineTuneId, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); }, /** * * @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning. * @param {string} model The ID of the model to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveModel(model, options) { return __awaiter(this, void 0, void 0, function* () { const localVarAxiosArgs = yield localVarAxiosParamCreator.retrieveModel(model, options); return common_1.createRequestFunction(localVarAxiosArgs, axios_1.default, base_1.BASE_PATH, configuration); }); } }; }; exports.OpenAIApiFactory = function(configuration, basePath, axios2) { const localVarFp = exports.OpenAIApiFp(configuration); return { /** * * @summary Immediately cancel a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to cancel * @param {*} [options] Override http request option. * @throws {RequiredError} */ cancelFineTune(fineTuneId, options) { return localVarFp.cancelFineTune(fineTuneId, options).then((request) => request(axios2, basePath)); }, /** * * @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions). * @param {CreateAnswerRequest} createAnswerRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createAnswer(createAnswerRequest, options) { return localVarFp.createAnswer(createAnswerRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates a model response for the given chat conversation. * @param {CreateChatCompletionRequest} createChatCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createChatCompletion(createChatCompletionRequest, options) { return localVarFp.createChatCompletion(createChatCompletionRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases. * @param {CreateClassificationRequest} createClassificationRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createClassification(createClassificationRequest, options) { return localVarFp.createClassification(createClassificationRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates a completion for the provided prompt and parameters. * @param {CreateCompletionRequest} createCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createCompletion(createCompletionRequest, options) { return localVarFp.createCompletion(createCompletionRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates a new edit for the provided input, instruction, and parameters. * @param {CreateEditRequest} createEditRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createEdit(createEditRequest, options) { return localVarFp.createEdit(createEditRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates an embedding vector representing the input text. * @param {CreateEmbeddingRequest} createEmbeddingRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createEmbedding(createEmbeddingRequest, options) { return localVarFp.createEmbedding(createEmbeddingRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit. * @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the `purpose` is set to \\\"fine-tune\\\", each line is a JSON record with \\\"prompt\\\" and \\\"completion\\\" fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data). * @param {string} purpose The intended purpose of the uploaded documents. Use \\\"fine-tune\\\" for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createFile(file, purpose, options) { return localVarFp.createFile(file, purpose, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {CreateFineTuneRequest} createFineTuneRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createFineTune(createFineTuneRequest, options) { return localVarFp.createFineTune(createFineTuneRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates an image given a prompt. * @param {CreateImageRequest} createImageRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImage(createImageRequest, options) { return localVarFp.createImage(createImageRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates an edited or extended image given an original image and a prompt. * @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. * @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters. * @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImageEdit(image2, prompt, mask, n, size, responseFormat, user, options) { return localVarFp.createImageEdit(image2, prompt, mask, n, size, responseFormat, user, options).then((request) => request(axios2, basePath)); }, /** * * @summary Creates a variation of a given image. * @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} */ createImageVariation(image2, n, size, responseFormat, user, options) { return localVarFp.createImageVariation(image2, n, size, responseFormat, user, options).then((request) => request(axios2, basePath)); }, /** * * @summary Classifies if text violates OpenAI\'s Content Policy * @param {CreateModerationRequest} createModerationRequest * @param {*} [options] Override http request option. * @throws {RequiredError} */ createModeration(createModerationRequest, options) { return localVarFp.createModeration(createModerationRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query. * @param {string} engineId The ID of the engine to use for this request. You can select one of `ada`, `babbage`, `curie`, or `davinci`. * @param {CreateSearchRequest} createSearchRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ createSearch(engineId, createSearchRequest, options) { return localVarFp.createSearch(engineId, createSearchRequest, options).then((request) => request(axios2, basePath)); }, /** * * @summary Transcribes audio into the input language. * @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createTranscription(file, model, prompt, responseFormat, temperature, language, options) { return localVarFp.createTranscription(file, model, prompt, responseFormat, temperature, language, options).then((request) => request(axios2, basePath)); }, /** * * @summary Translates audio into into English. * @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {*} [options] Override http request option. * @throws {RequiredError} */ createTranslation(file, model, prompt, responseFormat, temperature, options) { return localVarFp.createTranslation(file, model, prompt, responseFormat, temperature, options).then((request) => request(axios2, basePath)); }, /** * * @summary Delete a file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteFile(fileId, options) { return localVarFp.deleteFile(fileId, options).then((request) => request(axios2, basePath)); }, /** * * @summary Delete a fine-tuned model. You must have the Owner role in your organization. * @param {string} model The model to delete * @param {*} [options] Override http request option. * @throws {RequiredError} */ deleteModel(model, options) { return localVarFp.deleteModel(model, options).then((request) => request(axios2, basePath)); }, /** * * @summary Returns the contents of the specified file * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ downloadFile(fileId, options) { return localVarFp.downloadFile(fileId, options).then((request) => request(axios2, basePath)); }, /** * * @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ listEngines(options) { return localVarFp.listEngines(options).then((request) => request(axios2, basePath)); }, /** * * @summary Returns a list of files that belong to the user\'s organization. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFiles(options) { return localVarFp.listFiles(options).then((request) => request(axios2, basePath)); }, /** * * @summary Get fine-grained status updates for a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to get events for. * @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a `data: [DONE]` message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFineTuneEvents(fineTuneId, stream, options) { return localVarFp.listFineTuneEvents(fineTuneId, stream, options).then((request) => request(axios2, basePath)); }, /** * * @summary List your organization\'s fine-tuning jobs * @param {*} [options] Override http request option. * @throws {RequiredError} */ listFineTunes(options) { return localVarFp.listFineTunes(options).then((request) => request(axios2, basePath)); }, /** * * @summary Lists the currently available models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @throws {RequiredError} */ listModels(options) { return localVarFp.listModels(options).then((request) => request(axios2, basePath)); }, /** * * @summary Retrieves a model instance, providing basic information about it such as the owner and availability. * @param {string} engineId The ID of the engine to use for this request * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} */ retrieveEngine(engineId, options) { return localVarFp.retrieveEngine(engineId, options).then((request) => request(axios2, basePath)); }, /** * * @summary Returns information about a specific file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveFile(fileId, options) { return localVarFp.retrieveFile(fileId, options).then((request) => request(axios2, basePath)); }, /** * * @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {string} fineTuneId The ID of the fine-tune job * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveFineTune(fineTuneId, options) { return localVarFp.retrieveFineTune(fineTuneId, options).then((request) => request(axios2, basePath)); }, /** * * @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning. * @param {string} model The ID of the model to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} */ retrieveModel(model, options) { return localVarFp.retrieveModel(model, options).then((request) => request(axios2, basePath)); } }; }; var OpenAIApi5 = class extends base_1.BaseAPI { /** * * @summary Immediately cancel a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to cancel * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ cancelFineTune(fineTuneId, options) { return exports.OpenAIApiFp(this.configuration).cancelFineTune(fineTuneId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Answers the specified question using the provided documents and examples. The endpoint first [searches](/docs/api-reference/searches) over provided documents or files to find relevant context. The relevant context is combined with the provided examples and question to create the prompt for [completion](/docs/api-reference/completions). * @param {CreateAnswerRequest} createAnswerRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} * @memberof OpenAIApi */ createAnswer(createAnswerRequest, options) { return exports.OpenAIApiFp(this.configuration).createAnswer(createAnswerRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates a model response for the given chat conversation. * @param {CreateChatCompletionRequest} createChatCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createChatCompletion(createChatCompletionRequest, options) { return exports.OpenAIApiFp(this.configuration).createChatCompletion(createChatCompletionRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Classifies the specified `query` using provided examples. The endpoint first [searches](/docs/api-reference/searches) over the labeled examples to select the ones most relevant for the particular query. Then, the relevant examples are combined with the query to construct a prompt to produce the final label via the [completions](/docs/api-reference/completions) endpoint. Labeled examples can be provided via an uploaded `file`, or explicitly listed in the request using the `examples` parameter for quick tests and small scale use cases. * @param {CreateClassificationRequest} createClassificationRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} * @memberof OpenAIApi */ createClassification(createClassificationRequest, options) { return exports.OpenAIApiFp(this.configuration).createClassification(createClassificationRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates a completion for the provided prompt and parameters. * @param {CreateCompletionRequest} createCompletionRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createCompletion(createCompletionRequest, options) { return exports.OpenAIApiFp(this.configuration).createCompletion(createCompletionRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates a new edit for the provided input, instruction, and parameters. * @param {CreateEditRequest} createEditRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createEdit(createEditRequest, options) { return exports.OpenAIApiFp(this.configuration).createEdit(createEditRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates an embedding vector representing the input text. * @param {CreateEmbeddingRequest} createEmbeddingRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createEmbedding(createEmbeddingRequest, options) { return exports.OpenAIApiFp(this.configuration).createEmbedding(createEmbeddingRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Upload a file that contains document(s) to be used across various endpoints/features. Currently, the size of all the files uploaded by one organization can be up to 1 GB. Please contact us if you need to increase the storage limit. * @param {File} file Name of the [JSON Lines](https://jsonlines.readthedocs.io/en/latest/) file to be uploaded. If the `purpose` is set to \\\"fine-tune\\\", each line is a JSON record with \\\"prompt\\\" and \\\"completion\\\" fields representing your [training examples](/docs/guides/fine-tuning/prepare-training-data). * @param {string} purpose The intended purpose of the uploaded documents. Use \\\"fine-tune\\\" for [Fine-tuning](/docs/api-reference/fine-tunes). This allows us to validate the format of the uploaded file. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createFile(file, purpose, options) { return exports.OpenAIApiFp(this.configuration).createFile(file, purpose, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates a job that fine-tunes a specified model from a given dataset. Response includes details of the enqueued job including job status and the name of the fine-tuned models once complete. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {CreateFineTuneRequest} createFineTuneRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createFineTune(createFineTuneRequest, options) { return exports.OpenAIApiFp(this.configuration).createFineTune(createFineTuneRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates an image given a prompt. * @param {CreateImageRequest} createImageRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createImage(createImageRequest, options) { return exports.OpenAIApiFp(this.configuration).createImage(createImageRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates an edited or extended image given an original image and a prompt. * @param {File} image The image to edit. Must be a valid PNG file, less than 4MB, and square. If mask is not provided, image must have transparency, which will be used as the mask. * @param {string} prompt A text description of the desired image(s). The maximum length is 1000 characters. * @param {File} [mask] An additional image whose fully transparent areas (e.g. where alpha is zero) indicate where `image` should be edited. Must be a valid PNG file, less than 4MB, and have the same dimensions as `image`. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createImageEdit(image2, prompt, mask, n, size, responseFormat, user, options) { return exports.OpenAIApiFp(this.configuration).createImageEdit(image2, prompt, mask, n, size, responseFormat, user, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Creates a variation of a given image. * @param {File} image The image to use as the basis for the variation(s). Must be a valid PNG file, less than 4MB, and square. * @param {number} [n] The number of images to generate. Must be between 1 and 10. * @param {string} [size] The size of the generated images. Must be one of `256x256`, `512x512`, or `1024x1024`. * @param {string} [responseFormat] The format in which the generated images are returned. Must be one of `url` or `b64_json`. * @param {string} [user] A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. [Learn more](/docs/guides/safety-best-practices/end-user-ids). * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createImageVariation(image2, n, size, responseFormat, user, options) { return exports.OpenAIApiFp(this.configuration).createImageVariation(image2, n, size, responseFormat, user, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Classifies if text violates OpenAI\'s Content Policy * @param {CreateModerationRequest} createModerationRequest * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createModeration(createModerationRequest, options) { return exports.OpenAIApiFp(this.configuration).createModeration(createModerationRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary The search endpoint computes similarity scores between provided query and documents. Documents can be passed directly to the API if there are no more than 200 of them. To go beyond the 200 document limit, documents can be processed offline and then used for efficient retrieval at query time. When `file` is set, the search endpoint searches over all the documents in the given file and returns up to the `max_rerank` number of documents. These documents will be returned along with their search scores. The similarity score is a positive score that usually ranges from 0 to 300 (but can sometimes go higher), where a score above 200 usually means the document is semantically similar to the query. * @param {string} engineId The ID of the engine to use for this request. You can select one of `ada`, `babbage`, `curie`, or `davinci`. * @param {CreateSearchRequest} createSearchRequest * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} * @memberof OpenAIApi */ createSearch(engineId, createSearchRequest, options) { return exports.OpenAIApiFp(this.configuration).createSearch(engineId, createSearchRequest, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Transcribes audio into the input language. * @param {File} file The audio file object (not file name) to transcribe, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should match the audio language. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {string} [language] The language of the input audio. Supplying the input language in [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will improve accuracy and latency. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createTranscription(file, model, prompt, responseFormat, temperature, language, options) { return exports.OpenAIApiFp(this.configuration).createTranscription(file, model, prompt, responseFormat, temperature, language, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Translates audio into into English. * @param {File} file The audio file object (not file name) translate, in one of these formats: mp3, mp4, mpeg, mpga, m4a, wav, or webm. * @param {string} model ID of the model to use. Only `whisper-1` is currently available. * @param {string} [prompt] An optional text to guide the model\\\'s style or continue a previous audio segment. The [prompt](/docs/guides/speech-to-text/prompting) should be in English. * @param {string} [responseFormat] The format of the transcript output, in one of these options: json, text, srt, verbose_json, or vtt. * @param {number} [temperature] The sampling temperature, between 0 and 1. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. If set to 0, the model will use [log probability](https://en.wikipedia.org/wiki/Log_probability) to automatically increase the temperature until certain thresholds are hit. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ createTranslation(file, model, prompt, responseFormat, temperature, options) { return exports.OpenAIApiFp(this.configuration).createTranslation(file, model, prompt, responseFormat, temperature, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Delete a file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ deleteFile(fileId, options) { return exports.OpenAIApiFp(this.configuration).deleteFile(fileId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Delete a fine-tuned model. You must have the Owner role in your organization. * @param {string} model The model to delete * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ deleteModel(model, options) { return exports.OpenAIApiFp(this.configuration).deleteModel(model, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Returns the contents of the specified file * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ downloadFile(fileId, options) { return exports.OpenAIApiFp(this.configuration).downloadFile(fileId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Lists the currently available (non-finetuned) models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} * @memberof OpenAIApi */ listEngines(options) { return exports.OpenAIApiFp(this.configuration).listEngines(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Returns a list of files that belong to the user\'s organization. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ listFiles(options) { return exports.OpenAIApiFp(this.configuration).listFiles(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Get fine-grained status updates for a fine-tune job. * @param {string} fineTuneId The ID of the fine-tune job to get events for. * @param {boolean} [stream] Whether to stream events for the fine-tune job. If set to true, events will be sent as data-only [server-sent events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Event_stream_format) as they become available. The stream will terminate with a `data: [DONE]` message when the job is finished (succeeded, cancelled, or failed). If set to false, only events generated so far will be returned. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ listFineTuneEvents(fineTuneId, stream, options) { return exports.OpenAIApiFp(this.configuration).listFineTuneEvents(fineTuneId, stream, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary List your organization\'s fine-tuning jobs * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ listFineTunes(options) { return exports.OpenAIApiFp(this.configuration).listFineTunes(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Lists the currently available models, and provides basic information about each one such as the owner and availability. * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ listModels(options) { return exports.OpenAIApiFp(this.configuration).listModels(options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Retrieves a model instance, providing basic information about it such as the owner and availability. * @param {string} engineId The ID of the engine to use for this request * @param {*} [options] Override http request option. * @deprecated * @throws {RequiredError} * @memberof OpenAIApi */ retrieveEngine(engineId, options) { return exports.OpenAIApiFp(this.configuration).retrieveEngine(engineId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Returns information about a specific file. * @param {string} fileId The ID of the file to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ retrieveFile(fileId, options) { return exports.OpenAIApiFp(this.configuration).retrieveFile(fileId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Gets info about the fine-tune job. [Learn more about Fine-tuning](/docs/guides/fine-tuning) * @param {string} fineTuneId The ID of the fine-tune job * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ retrieveFineTune(fineTuneId, options) { return exports.OpenAIApiFp(this.configuration).retrieveFineTune(fineTuneId, options).then((request) => request(this.axios, this.basePath)); } /** * * @summary Retrieves a model instance, providing basic information about the model such as the owner and permissioning. * @param {string} model The ID of the model to use for this request * @param {*} [options] Override http request option. * @throws {RequiredError} * @memberof OpenAIApi */ retrieveModel(model, options) { return exports.OpenAIApiFp(this.configuration).retrieveModel(model, options).then((request) => request(this.axios, this.basePath)); } }; exports.OpenAIApi = OpenAIApi5; } }); // node_modules/openai/package.json var require_package = __commonJS({ "node_modules/openai/package.json"(exports, module2) { module2.exports = { name: "openai", version: "3.3.0", description: "Node.js library for the OpenAI API", repository: { type: "git", url: "git@github.com:openai/openai-node.git" }, keywords: [ "openai", "open", "ai", "gpt-3", "gpt3" ], author: "OpenAI", license: "MIT", main: "./dist/index.js", types: "./dist/index.d.ts", scripts: { build: "tsc --outDir dist/" }, dependencies: { axios: "^0.26.0", "form-data": "^4.0.0" }, devDependencies: { "@types/node": "^12.11.5", typescript: "^3.6.4" } }; } }); // node_modules/form-data/lib/browser.js var require_browser = __commonJS({ "node_modules/form-data/lib/browser.js"(exports, module2) { module2.exports = typeof self == "object" ? self.FormData : window.FormData; } }); // node_modules/openai/dist/configuration.js var require_configuration = __commonJS({ "node_modules/openai/dist/configuration.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Configuration = void 0; var packageJson = require_package(); var Configuration5 = class { constructor(param = {}) { this.apiKey = param.apiKey; this.organization = param.organization; this.username = param.username; this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; if (!this.baseOptions) { this.baseOptions = {}; } this.baseOptions.headers = Object.assign({ "User-Agent": `OpenAI/NodeJS/${packageJson.version}`, "Authorization": `Bearer ${this.apiKey}` }, this.baseOptions.headers); if (this.organization) { this.baseOptions.headers["OpenAI-Organization"] = this.organization; } if (!this.formDataCtor) { this.formDataCtor = require_browser(); } } /** * Check if the given MIME is a JSON MIME. * JSON MIME examples: * application/json * application/json; charset=UTF8 * APPLICATION/JSON * application/vnd.company+json * @param mime - MIME (Multipurpose Internet Mail Extensions) * @return True if the given MIME is JSON, false otherwise. */ isJsonMime(mime) { const jsonMime = new RegExp("^(application/json|[^;/ ]+/[^;/ ]+[+]json)[ ]*(;.*)?$", "i"); return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === "application/json-patch+json"); } }; exports.Configuration = Configuration5; } }); // node_modules/openai/dist/index.js var require_dist2 = __commonJS({ "node_modules/openai/dist/index.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !exports2.hasOwnProperty(p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(require_api(), exports); __exportStar(require_configuration(), exports); } }); // node_modules/axios/lib/helpers/bind.js function bind(fn, thisArg) { return function wrap4() { return fn.apply(thisArg, arguments); }; } var init_bind = __esm({ "node_modules/axios/lib/helpers/bind.js"() { "use strict"; } }); // node_modules/axios/lib/utils.js function isBuffer(val) { return val !== null && !isUndefined(val) && val.constructor !== null && !isUndefined(val.constructor) && isFunction(val.constructor.isBuffer) && val.constructor.isBuffer(val); } function isArrayBufferView(val) { let result; if (typeof ArrayBuffer !== "undefined" && ArrayBuffer.isView) { result = ArrayBuffer.isView(val); } else { result = val && val.buffer && isArrayBuffer(val.buffer); } return result; } function forEach(obj, fn, { allOwnKeys = false } = {}) { if (obj === null || typeof obj === "undefined") { return; } let i; let l; if (typeof obj !== "object") { obj = [obj]; } if (isArray(obj)) { for (i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { const keys3 = allOwnKeys ? Object.getOwnPropertyNames(obj) : Object.keys(obj); const len = keys3.length; let key; for (i = 0; i < len; i++) { key = keys3[i]; fn.call(null, obj[key], key, obj); } } } function findKey(obj, key) { key = key.toLowerCase(); const keys3 = Object.keys(obj); let i = keys3.length; let _key; while (i-- > 0) { _key = keys3[i]; if (key === _key.toLowerCase()) { return _key; } } return null; } function merge() { const { caseless } = isContextDefined(this) && this || {}; const result = {}; const assignValue = (val, key) => { const targetKey = caseless && findKey(result, key) || key; if (isPlainObject(result[targetKey]) && isPlainObject(val)) { result[targetKey] = merge(result[targetKey], val); } else if (isPlainObject(val)) { result[targetKey] = merge({}, val); } else if (isArray(val)) { result[targetKey] = val.slice(); } else { result[targetKey] = val; } }; for (let i = 0, l = arguments.length; i < l; i++) { arguments[i] && forEach(arguments[i], assignValue); } return result; } function isSpecCompliantForm(thing) { return !!(thing && isFunction(thing.append) && thing[Symbol.toStringTag] === "FormData" && thing[Symbol.iterator]); } var toString2, getPrototypeOf, kindOf, kindOfTest, typeOfTest, isArray, isUndefined, isArrayBuffer, isString, isFunction, isNumber, isObject, isBoolean, isPlainObject, isDate, isFile, isBlob, isFileList, isStream, isFormData, isURLSearchParams, trim, _global, isContextDefined, extend, stripBOM, inherits, toFlatObject, endsWith, toArray, isTypedArray, forEachEntry, matchAll, isHTMLForm, toCamelCase, hasOwnProperty, isRegExp, reduceDescriptors, freezeMethods, toObjectSet, noop, toFiniteNumber, ALPHA, DIGIT, ALPHABET, generateString, toJSONObject, utils_default; var init_utils = __esm({ "node_modules/axios/lib/utils.js"() { "use strict"; init_bind(); ({ toString: toString2 } = Object.prototype); ({ getPrototypeOf } = Object); kindOf = ((cache2) => (thing) => { const str2 = toString2.call(thing); return cache2[str2] || (cache2[str2] = str2.slice(8, -1).toLowerCase()); })(/* @__PURE__ */ Object.create(null)); kindOfTest = (type2) => { type2 = type2.toLowerCase(); return (thing) => kindOf(thing) === type2; }; typeOfTest = (type2) => (thing) => typeof thing === type2; ({ isArray } = Array); isUndefined = typeOfTest("undefined"); isArrayBuffer = kindOfTest("ArrayBuffer"); isString = typeOfTest("string"); isFunction = typeOfTest("function"); isNumber = typeOfTest("number"); isObject = (thing) => thing !== null && typeof thing === "object"; isBoolean = (thing) => thing === true || thing === false; isPlainObject = (val) => { if (kindOf(val) !== "object") { return false; } const prototype3 = getPrototypeOf(val); return (prototype3 === null || prototype3 === Object.prototype || Object.getPrototypeOf(prototype3) === null) && !(Symbol.toStringTag in val) && !(Symbol.iterator in val); }; isDate = kindOfTest("Date"); isFile = kindOfTest("File"); isBlob = kindOfTest("Blob"); isFileList = kindOfTest("FileList"); isStream = (val) => isObject(val) && isFunction(val.pipe); isFormData = (thing) => { let kind; return thing && (typeof FormData === "function" && thing instanceof FormData || isFunction(thing.append) && ((kind = kindOf(thing)) === "formdata" || // detect form-data instance kind === "object" && isFunction(thing.toString) && thing.toString() === "[object FormData]")); }; isURLSearchParams = kindOfTest("URLSearchParams"); trim = (str2) => str2.trim ? str2.trim() : str2.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ""); _global = (() => { if (typeof globalThis !== "undefined") return globalThis; return typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : global; })(); isContextDefined = (context) => !isUndefined(context) && context !== _global; extend = (a2, b, thisArg, { allOwnKeys } = {}) => { forEach(b, (val, key) => { if (thisArg && isFunction(val)) { a2[key] = bind(val, thisArg); } else { a2[key] = val; } }, { allOwnKeys }); return a2; }; stripBOM = (content3) => { if (content3.charCodeAt(0) === 65279) { content3 = content3.slice(1); } return content3; }; inherits = (constructor, superConstructor, props, descriptors2) => { constructor.prototype = Object.create(superConstructor.prototype, descriptors2); constructor.prototype.constructor = constructor; Object.defineProperty(constructor, "super", { value: superConstructor.prototype }); props && Object.assign(constructor.prototype, props); }; toFlatObject = (sourceObj, destObj, filter3, propFilter) => { let props; let i; let prop; const merged = {}; destObj = destObj || {}; if (sourceObj == null) return destObj; do { props = Object.getOwnPropertyNames(sourceObj); i = props.length; while (i-- > 0) { prop = props[i]; if ((!propFilter || propFilter(prop, sourceObj, destObj)) && !merged[prop]) { destObj[prop] = sourceObj[prop]; merged[prop] = true; } } sourceObj = filter3 !== false && getPrototypeOf(sourceObj); } while (sourceObj && (!filter3 || filter3(sourceObj, destObj)) && sourceObj !== Object.prototype); return destObj; }; endsWith = (str2, searchString, position3) => { str2 = String(str2); if (position3 === void 0 || position3 > str2.length) { position3 = str2.length; } position3 -= searchString.length; const lastIndex = str2.indexOf(searchString, position3); return lastIndex !== -1 && lastIndex === position3; }; toArray = (thing) => { if (!thing) return null; if (isArray(thing)) return thing; let i = thing.length; if (!isNumber(i)) return null; const arr = new Array(i); while (i-- > 0) { arr[i] = thing[i]; } return arr; }; isTypedArray = ((TypedArray) => { return (thing) => { return TypedArray && thing instanceof TypedArray; }; })(typeof Uint8Array !== "undefined" && getPrototypeOf(Uint8Array)); forEachEntry = (obj, fn) => { const generator = obj && obj[Symbol.iterator]; const iterator = generator.call(obj); let result; while ((result = iterator.next()) && !result.done) { const pair = result.value; fn.call(obj, pair[0], pair[1]); } }; matchAll = (regExp, str2) => { let matches; const arr = []; while ((matches = regExp.exec(str2)) !== null) { arr.push(matches); } return arr; }; isHTMLForm = kindOfTest("HTMLFormElement"); toCamelCase = (str2) => { return str2.toLowerCase().replace( /[-_\s]([a-z\d])(\w*)/g, function replacer(m, p1, p2) { return p1.toUpperCase() + p2; } ); }; hasOwnProperty = (({ hasOwnProperty: hasOwnProperty3 }) => (obj, prop) => hasOwnProperty3.call(obj, prop))(Object.prototype); isRegExp = kindOfTest("RegExp"); reduceDescriptors = (obj, reducer2) => { const descriptors2 = Object.getOwnPropertyDescriptors(obj); const reducedDescriptors = {}; forEach(descriptors2, (descriptor, name) => { if (reducer2(descriptor, name, obj) !== false) { reducedDescriptors[name] = descriptor; } }); Object.defineProperties(obj, reducedDescriptors); }; freezeMethods = (obj) => { reduceDescriptors(obj, (descriptor, name) => { if (isFunction(obj) && ["arguments", "caller", "callee"].indexOf(name) !== -1) { return false; } const value = obj[name]; if (!isFunction(value)) return; descriptor.enumerable = false; if ("writable" in descriptor) { descriptor.writable = false; return; } if (!descriptor.set) { descriptor.set = () => { throw Error("Can not rewrite read-only method '" + name + "'"); }; } }); }; toObjectSet = (arrayOrString, delimiter) => { const obj = {}; const define2 = (arr) => { arr.forEach((value) => { obj[value] = true; }); }; isArray(arrayOrString) ? define2(arrayOrString) : define2(String(arrayOrString).split(delimiter)); return obj; }; noop = () => { }; toFiniteNumber = (value, defaultValue) => { value = +value; return Number.isFinite(value) ? value : defaultValue; }; ALPHA = "abcdefghijklmnopqrstuvwxyz"; DIGIT = "0123456789"; ALPHABET = { DIGIT, ALPHA, ALPHA_DIGIT: ALPHA + ALPHA.toUpperCase() + DIGIT }; generateString = (size = 16, alphabet = ALPHABET.ALPHA_DIGIT) => { let str2 = ""; const { length } = alphabet; while (size--) { str2 += alphabet[Math.random() * length | 0]; } return str2; }; toJSONObject = (obj) => { const stack = new Array(10); const visit2 = (source, i) => { if (isObject(source)) { if (stack.indexOf(source) >= 0) { return; } if (!("toJSON" in source)) { stack[i] = source; const target = isArray(source) ? [] : {}; forEach(source, (value, key) => { const reducedValue = visit2(value, i + 1); !isUndefined(reducedValue) && (target[key] = reducedValue); }); stack[i] = void 0; return target; } } return source; }; return visit2(obj, 0); }; utils_default = { isArray, isArrayBuffer, isBuffer, isFormData, isArrayBufferView, isString, isNumber, isBoolean, isObject, isPlainObject, isUndefined, isDate, isFile, isBlob, isRegExp, isFunction, isStream, isURLSearchParams, isTypedArray, isFileList, forEach, merge, extend, trim, stripBOM, inherits, toFlatObject, kindOf, kindOfTest, endsWith, toArray, forEachEntry, matchAll, isHTMLForm, hasOwnProperty, hasOwnProp: hasOwnProperty, // an alias to avoid ESLint no-prototype-builtins detection reduceDescriptors, freezeMethods, toObjectSet, toCamelCase, noop, toFiniteNumber, findKey, global: _global, isContextDefined, ALPHABET, generateString, isSpecCompliantForm, toJSONObject }; } }); // node_modules/axios/lib/core/AxiosError.js function AxiosError(message, code2, config, request, response) { Error.call(this); if (Error.captureStackTrace) { Error.captureStackTrace(this, this.constructor); } else { this.stack = new Error().stack; } this.message = message; this.name = "AxiosError"; code2 && (this.code = code2); config && (this.config = config); request && (this.request = request); response && (this.response = response); } var prototype, descriptors, AxiosError_default; var init_AxiosError = __esm({ "node_modules/axios/lib/core/AxiosError.js"() { "use strict"; init_utils(); utils_default.inherits(AxiosError, Error, { toJSON: function toJSON() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: utils_default.toJSONObject(this.config), code: this.code, status: this.response && this.response.status ? this.response.status : null }; } }); prototype = AxiosError.prototype; descriptors = {}; [ "ERR_BAD_OPTION_VALUE", "ERR_BAD_OPTION", "ECONNABORTED", "ETIMEDOUT", "ERR_NETWORK", "ERR_FR_TOO_MANY_REDIRECTS", "ERR_DEPRECATED", "ERR_BAD_RESPONSE", "ERR_BAD_REQUEST", "ERR_CANCELED", "ERR_NOT_SUPPORT", "ERR_INVALID_URL" // eslint-disable-next-line func-names ].forEach((code2) => { descriptors[code2] = { value: code2 }; }); Object.defineProperties(AxiosError, descriptors); Object.defineProperty(prototype, "isAxiosError", { value: true }); AxiosError.from = (error, code2, config, request, response, customProps) => { const axiosError = Object.create(prototype); utils_default.toFlatObject(error, axiosError, function filter3(obj) { return obj !== Error.prototype; }, (prop) => { return prop !== "isAxiosError"; }); AxiosError.call(axiosError, error.message, code2, config, request, response); axiosError.cause = error; axiosError.name = error.name; customProps && Object.assign(axiosError, customProps); return axiosError; }; AxiosError_default = AxiosError; } }); // node_modules/axios/lib/helpers/null.js var null_default; var init_null = __esm({ "node_modules/axios/lib/helpers/null.js"() { null_default = null; } }); // node_modules/axios/lib/helpers/toFormData.js function isVisitable(thing) { return utils_default.isPlainObject(thing) || utils_default.isArray(thing); } function removeBrackets(key) { return utils_default.endsWith(key, "[]") ? key.slice(0, -2) : key; } function renderKey(path2, key, dots) { if (!path2) return key; return path2.concat(key).map(function each(token, i) { token = removeBrackets(token); return !dots && i ? "[" + token + "]" : token; }).join(dots ? "." : ""); } function isFlatArray(arr) { return utils_default.isArray(arr) && !arr.some(isVisitable); } function toFormData(obj, formData, options) { if (!utils_default.isObject(obj)) { throw new TypeError("target must be an object"); } formData = formData || new (null_default || FormData)(); options = utils_default.toFlatObject(options, { metaTokens: true, dots: false, indexes: false }, false, function defined(option, source) { return !utils_default.isUndefined(source[option]); }); const metaTokens = options.metaTokens; const visitor = options.visitor || defaultVisitor; const dots = options.dots; const indexes = options.indexes; const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; const useBlob = _Blob && utils_default.isSpecCompliantForm(formData); if (!utils_default.isFunction(visitor)) { throw new TypeError("visitor must be a function"); } function convertValue(value) { if (value === null) return ""; if (utils_default.isDate(value)) { return value.toISOString(); } if (!useBlob && utils_default.isBlob(value)) { throw new AxiosError_default("Blob is not supported. Use a Buffer instead."); } if (utils_default.isArrayBuffer(value) || utils_default.isTypedArray(value)) { return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); } return value; } function defaultVisitor(value, key, path2) { let arr = value; if (value && !path2 && typeof value === "object") { if (utils_default.endsWith(key, "{}")) { key = metaTokens ? key : key.slice(0, -2); value = JSON.stringify(value); } else if (utils_default.isArray(value) && isFlatArray(value) || (utils_default.isFileList(value) || utils_default.endsWith(key, "[]")) && (arr = utils_default.toArray(value))) { key = removeBrackets(key); arr.forEach(function each(el, index2) { !(utils_default.isUndefined(el) || el === null) && formData.append( // eslint-disable-next-line no-nested-ternary indexes === true ? renderKey([key], index2, dots) : indexes === null ? key : key + "[]", convertValue(el) ); }); return false; } } if (isVisitable(value)) { return true; } formData.append(renderKey(path2, key, dots), convertValue(value)); return false; } const stack = []; const exposedHelpers = Object.assign(predicates, { defaultVisitor, convertValue, isVisitable }); function build(value, path2) { if (utils_default.isUndefined(value)) return; if (stack.indexOf(value) !== -1) { throw Error("Circular reference detected in " + path2.join(".")); } stack.push(value); utils_default.forEach(value, function each(el, key) { const result = !(utils_default.isUndefined(el) || el === null) && visitor.call( formData, el, utils_default.isString(key) ? key.trim() : key, path2, exposedHelpers ); if (result === true) { build(el, path2 ? path2.concat(key) : [key]); } }); stack.pop(); } if (!utils_default.isObject(obj)) { throw new TypeError("data must be an object"); } build(obj); return formData; } var predicates, toFormData_default; var init_toFormData = __esm({ "node_modules/axios/lib/helpers/toFormData.js"() { "use strict"; init_utils(); init_AxiosError(); init_null(); predicates = utils_default.toFlatObject(utils_default, {}, null, function filter(prop) { return /^is[A-Z]/.test(prop); }); toFormData_default = toFormData; } }); // node_modules/axios/lib/helpers/AxiosURLSearchParams.js function encode(str2) { const charMap = { "!": "%21", "'": "%27", "(": "%28", ")": "%29", "~": "%7E", "%20": "+", "%00": "\0" }; return encodeURIComponent(str2).replace(/[!'()~]|%20|%00/g, function replacer(match2) { return charMap[match2]; }); } function AxiosURLSearchParams(params, options) { this._pairs = []; params && toFormData_default(params, this, options); } var prototype2, AxiosURLSearchParams_default; var init_AxiosURLSearchParams = __esm({ "node_modules/axios/lib/helpers/AxiosURLSearchParams.js"() { "use strict"; init_toFormData(); prototype2 = AxiosURLSearchParams.prototype; prototype2.append = function append(name, value) { this._pairs.push([name, value]); }; prototype2.toString = function toString3(encoder) { const _encode = encoder ? function(value) { return encoder.call(this, value, encode); } : encode; return this._pairs.map(function each(pair) { return _encode(pair[0]) + "=" + _encode(pair[1]); }, "").join("&"); }; AxiosURLSearchParams_default = AxiosURLSearchParams; } }); // node_modules/axios/lib/helpers/buildURL.js function encode2(val) { return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); } function buildURL(url, params, options) { if (!params) { return url; } const _encode = options && options.encode || encode2; const serializeFn = options && options.serialize; let serializedParams; if (serializeFn) { serializedParams = serializeFn(params, options); } else { serializedParams = utils_default.isURLSearchParams(params) ? params.toString() : new AxiosURLSearchParams_default(params, options).toString(_encode); } if (serializedParams) { const hashmarkIndex = url.indexOf("#"); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; } return url; } var init_buildURL = __esm({ "node_modules/axios/lib/helpers/buildURL.js"() { "use strict"; init_utils(); init_AxiosURLSearchParams(); } }); // node_modules/axios/lib/core/InterceptorManager.js var InterceptorManager, InterceptorManager_default; var init_InterceptorManager = __esm({ "node_modules/axios/lib/core/InterceptorManager.js"() { "use strict"; init_utils(); InterceptorManager = class { constructor() { this.handlers = []; } /** * Add a new interceptor to the stack * * @param {Function} fulfilled The function to handle `then` for a `Promise` * @param {Function} rejected The function to handle `reject` for a `Promise` * * @return {Number} An ID used to remove interceptor later */ use(fulfilled, rejected, options) { this.handlers.push({ fulfilled, rejected, synchronous: options ? options.synchronous : false, runWhen: options ? options.runWhen : null }); return this.handlers.length - 1; } /** * Remove an interceptor from the stack * * @param {Number} id The ID that was returned by `use` * * @returns {Boolean} `true` if the interceptor was removed, `false` otherwise */ eject(id) { if (this.handlers[id]) { this.handlers[id] = null; } } /** * Clear all interceptors from the stack * * @returns {void} */ clear() { if (this.handlers) { this.handlers = []; } } /** * Iterate over all the registered interceptors * * This method is particularly useful for skipping over any * interceptors that may have become `null` calling `eject`. * * @param {Function} fn The function to call for each interceptor * * @returns {void} */ forEach(fn) { utils_default.forEach(this.handlers, function forEachHandler(h2) { if (h2 !== null) { fn(h2); } }); } }; InterceptorManager_default = InterceptorManager; } }); // node_modules/axios/lib/defaults/transitional.js var transitional_default; var init_transitional = __esm({ "node_modules/axios/lib/defaults/transitional.js"() { "use strict"; transitional_default = { silentJSONParsing: true, forcedJSONParsing: true, clarifyTimeoutError: false }; } }); // node_modules/axios/lib/platform/browser/classes/URLSearchParams.js var URLSearchParams_default; var init_URLSearchParams = __esm({ "node_modules/axios/lib/platform/browser/classes/URLSearchParams.js"() { "use strict"; init_AxiosURLSearchParams(); URLSearchParams_default = typeof URLSearchParams !== "undefined" ? URLSearchParams : AxiosURLSearchParams_default; } }); // node_modules/axios/lib/platform/browser/classes/FormData.js var FormData_default; var init_FormData = __esm({ "node_modules/axios/lib/platform/browser/classes/FormData.js"() { "use strict"; FormData_default = typeof FormData !== "undefined" ? FormData : null; } }); // node_modules/axios/lib/platform/browser/classes/Blob.js var Blob_default; var init_Blob = __esm({ "node_modules/axios/lib/platform/browser/classes/Blob.js"() { "use strict"; Blob_default = typeof Blob !== "undefined" ? Blob : null; } }); // node_modules/axios/lib/platform/browser/index.js var isStandardBrowserEnv, isStandardBrowserWebWorkerEnv, browser_default; var init_browser = __esm({ "node_modules/axios/lib/platform/browser/index.js"() { init_URLSearchParams(); init_FormData(); init_Blob(); isStandardBrowserEnv = (() => { let product; if (typeof navigator !== "undefined" && ((product = navigator.product) === "ReactNative" || product === "NativeScript" || product === "NS")) { return false; } return typeof window !== "undefined" && typeof document !== "undefined"; })(); isStandardBrowserWebWorkerEnv = (() => { return typeof WorkerGlobalScope !== "undefined" && // eslint-disable-next-line no-undef self instanceof WorkerGlobalScope && typeof self.importScripts === "function"; })(); browser_default = { isBrowser: true, classes: { URLSearchParams: URLSearchParams_default, FormData: FormData_default, Blob: Blob_default }, isStandardBrowserEnv, isStandardBrowserWebWorkerEnv, protocols: ["http", "https", "file", "blob", "url", "data"] }; } }); // node_modules/axios/lib/platform/index.js var init_platform = __esm({ "node_modules/axios/lib/platform/index.js"() { init_browser(); } }); // node_modules/axios/lib/helpers/toURLEncodedForm.js function toURLEncodedForm(data, options) { return toFormData_default(data, new browser_default.classes.URLSearchParams(), Object.assign({ visitor: function(value, key, path2, helpers) { if (browser_default.isNode && utils_default.isBuffer(value)) { this.append(key, value.toString("base64")); return false; } return helpers.defaultVisitor.apply(this, arguments); } }, options)); } var init_toURLEncodedForm = __esm({ "node_modules/axios/lib/helpers/toURLEncodedForm.js"() { "use strict"; init_utils(); init_toFormData(); init_platform(); } }); // node_modules/axios/lib/helpers/formDataToJSON.js function parsePropPath(name) { return utils_default.matchAll(/\w+|\[(\w*)]/g, name).map((match2) => { return match2[0] === "[]" ? "" : match2[1] || match2[0]; }); } function arrayToObject(arr) { const obj = {}; const keys3 = Object.keys(arr); let i; const len = keys3.length; let key; for (i = 0; i < len; i++) { key = keys3[i]; obj[key] = arr[key]; } return obj; } function formDataToJSON(formData) { function buildPath(path2, value, target, index2) { let name = path2[index2++]; const isNumericKey = Number.isFinite(+name); const isLast = index2 >= path2.length; name = !name && utils_default.isArray(target) ? target.length : name; if (isLast) { if (utils_default.hasOwnProp(target, name)) { target[name] = [target[name], value]; } else { target[name] = value; } return !isNumericKey; } if (!target[name] || !utils_default.isObject(target[name])) { target[name] = []; } const result = buildPath(path2, value, target[name], index2); if (result && utils_default.isArray(target[name])) { target[name] = arrayToObject(target[name]); } return !isNumericKey; } if (utils_default.isFormData(formData) && utils_default.isFunction(formData.entries)) { const obj = {}; utils_default.forEachEntry(formData, (name, value) => { buildPath(parsePropPath(name), value, obj, 0); }); return obj; } return null; } var formDataToJSON_default; var init_formDataToJSON = __esm({ "node_modules/axios/lib/helpers/formDataToJSON.js"() { "use strict"; init_utils(); formDataToJSON_default = formDataToJSON; } }); // node_modules/axios/lib/defaults/index.js function stringifySafely(rawValue, parser2, encoder) { if (utils_default.isString(rawValue)) { try { (parser2 || JSON.parse)(rawValue); return utils_default.trim(rawValue); } catch (e) { if (e.name !== "SyntaxError") { throw e; } } } return (encoder || JSON.stringify)(rawValue); } var DEFAULT_CONTENT_TYPE, defaults, defaults_default; var init_defaults = __esm({ "node_modules/axios/lib/defaults/index.js"() { "use strict"; init_utils(); init_AxiosError(); init_transitional(); init_toFormData(); init_toURLEncodedForm(); init_platform(); init_formDataToJSON(); DEFAULT_CONTENT_TYPE = { "Content-Type": void 0 }; defaults = { transitional: transitional_default, adapter: ["xhr", "http"], transformRequest: [function transformRequest(data, headers) { const contentType = headers.getContentType() || ""; const hasJSONContentType = contentType.indexOf("application/json") > -1; const isObjectPayload = utils_default.isObject(data); if (isObjectPayload && utils_default.isHTMLForm(data)) { data = new FormData(data); } const isFormData3 = utils_default.isFormData(data); if (isFormData3) { if (!hasJSONContentType) { return data; } return hasJSONContentType ? JSON.stringify(formDataToJSON_default(data)) : data; } if (utils_default.isArrayBuffer(data) || utils_default.isBuffer(data) || utils_default.isStream(data) || utils_default.isFile(data) || utils_default.isBlob(data)) { return data; } if (utils_default.isArrayBufferView(data)) { return data.buffer; } if (utils_default.isURLSearchParams(data)) { headers.setContentType("application/x-www-form-urlencoded;charset=utf-8", false); return data.toString(); } let isFileList2; if (isObjectPayload) { if (contentType.indexOf("application/x-www-form-urlencoded") > -1) { return toURLEncodedForm(data, this.formSerializer).toString(); } if ((isFileList2 = utils_default.isFileList(data)) || contentType.indexOf("multipart/form-data") > -1) { const _FormData = this.env && this.env.FormData; return toFormData_default( isFileList2 ? { "files[]": data } : data, _FormData && new _FormData(), this.formSerializer ); } } if (isObjectPayload || hasJSONContentType) { headers.setContentType("application/json", false); return stringifySafely(data); } return data; }], transformResponse: [function transformResponse(data) { const transitional2 = this.transitional || defaults.transitional; const forcedJSONParsing = transitional2 && transitional2.forcedJSONParsing; const JSONRequested = this.responseType === "json"; if (data && utils_default.isString(data) && (forcedJSONParsing && !this.responseType || JSONRequested)) { const silentJSONParsing = transitional2 && transitional2.silentJSONParsing; const strictJSONParsing = !silentJSONParsing && JSONRequested; try { return JSON.parse(data); } catch (e) { if (strictJSONParsing) { if (e.name === "SyntaxError") { throw AxiosError_default.from(e, AxiosError_default.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } } } return data; }], /** * A timeout in milliseconds to abort a request. If set to 0 (default) a * timeout is not created. */ timeout: 0, xsrfCookieName: "XSRF-TOKEN", xsrfHeaderName: "X-XSRF-TOKEN", maxContentLength: -1, maxBodyLength: -1, env: { FormData: browser_default.classes.FormData, Blob: browser_default.classes.Blob }, validateStatus: function validateStatus(status) { return status >= 200 && status < 300; }, headers: { common: { "Accept": "application/json, text/plain, */*" } } }; utils_default.forEach(["delete", "get", "head"], function forEachMethodNoData(method) { defaults.headers[method] = {}; }); utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData(method) { defaults.headers[method] = utils_default.merge(DEFAULT_CONTENT_TYPE); }); defaults_default = defaults; } }); // node_modules/axios/lib/helpers/parseHeaders.js var ignoreDuplicateOf, parseHeaders_default; var init_parseHeaders = __esm({ "node_modules/axios/lib/helpers/parseHeaders.js"() { "use strict"; init_utils(); ignoreDuplicateOf = utils_default.toObjectSet([ "age", "authorization", "content-length", "content-type", "etag", "expires", "from", "host", "if-modified-since", "if-unmodified-since", "last-modified", "location", "max-forwards", "proxy-authorization", "referer", "retry-after", "user-agent" ]); parseHeaders_default = (rawHeaders) => { const parsed = {}; let key; let val; let i; rawHeaders && rawHeaders.split("\n").forEach(function parser2(line) { i = line.indexOf(":"); key = line.substring(0, i).trim().toLowerCase(); val = line.substring(i + 1).trim(); if (!key || parsed[key] && ignoreDuplicateOf[key]) { return; } if (key === "set-cookie") { if (parsed[key]) { parsed[key].push(val); } else { parsed[key] = [val]; } } else { parsed[key] = parsed[key] ? parsed[key] + ", " + val : val; } }); return parsed; }; } }); // node_modules/axios/lib/core/AxiosHeaders.js function normalizeHeader(header) { return header && String(header).trim().toLowerCase(); } function normalizeValue(value) { if (value === false || value == null) { return value; } return utils_default.isArray(value) ? value.map(normalizeValue) : String(value); } function parseTokens(str2) { const tokens = /* @__PURE__ */ Object.create(null); const tokensRE = /([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g; let match2; while (match2 = tokensRE.exec(str2)) { tokens[match2[1]] = match2[2]; } return tokens; } function matchHeaderValue(context, value, header, filter3, isHeaderNameFilter) { if (utils_default.isFunction(filter3)) { return filter3.call(this, value, header); } if (isHeaderNameFilter) { value = header; } if (!utils_default.isString(value)) return; if (utils_default.isString(filter3)) { return value.indexOf(filter3) !== -1; } if (utils_default.isRegExp(filter3)) { return filter3.test(value); } } function formatHeader(header) { return header.trim().toLowerCase().replace(/([a-z\d])(\w*)/g, (w, char, str2) => { return char.toUpperCase() + str2; }); } function buildAccessors(obj, header) { const accessorName = utils_default.toCamelCase(" " + header); ["get", "set", "has"].forEach((methodName) => { Object.defineProperty(obj, methodName + accessorName, { value: function(arg1, arg2, arg3) { return this[methodName].call(this, header, arg1, arg2, arg3); }, configurable: true }); }); } var $internals, isValidHeaderName, AxiosHeaders, AxiosHeaders_default; var init_AxiosHeaders = __esm({ "node_modules/axios/lib/core/AxiosHeaders.js"() { "use strict"; init_utils(); init_parseHeaders(); $internals = Symbol("internals"); isValidHeaderName = (str2) => /^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(str2.trim()); AxiosHeaders = class { constructor(headers) { headers && this.set(headers); } set(header, valueOrRewrite, rewrite) { const self2 = this; function setHeader(_value, _header, _rewrite) { const lHeader = normalizeHeader(_header); if (!lHeader) { throw new Error("header name must be a non-empty string"); } const key = utils_default.findKey(self2, lHeader); if (!key || self2[key] === void 0 || _rewrite === true || _rewrite === void 0 && self2[key] !== false) { self2[key || _header] = normalizeValue(_value); } } const setHeaders = (headers, _rewrite) => utils_default.forEach(headers, (_value, _header) => setHeader(_value, _header, _rewrite)); if (utils_default.isPlainObject(header) || header instanceof this.constructor) { setHeaders(header, valueOrRewrite); } else if (utils_default.isString(header) && (header = header.trim()) && !isValidHeaderName(header)) { setHeaders(parseHeaders_default(header), valueOrRewrite); } else { header != null && setHeader(valueOrRewrite, header, rewrite); } return this; } get(header, parser2) { header = normalizeHeader(header); if (header) { const key = utils_default.findKey(this, header); if (key) { const value = this[key]; if (!parser2) { return value; } if (parser2 === true) { return parseTokens(value); } if (utils_default.isFunction(parser2)) { return parser2.call(this, value, key); } if (utils_default.isRegExp(parser2)) { return parser2.exec(value); } throw new TypeError("parser must be boolean|regexp|function"); } } } has(header, matcher) { header = normalizeHeader(header); if (header) { const key = utils_default.findKey(this, header); return !!(key && this[key] !== void 0 && (!matcher || matchHeaderValue(this, this[key], key, matcher))); } return false; } delete(header, matcher) { const self2 = this; let deleted = false; function deleteHeader(_header) { _header = normalizeHeader(_header); if (_header) { const key = utils_default.findKey(self2, _header); if (key && (!matcher || matchHeaderValue(self2, self2[key], key, matcher))) { delete self2[key]; deleted = true; } } } if (utils_default.isArray(header)) { header.forEach(deleteHeader); } else { deleteHeader(header); } return deleted; } clear(matcher) { const keys3 = Object.keys(this); let i = keys3.length; let deleted = false; while (i--) { const key = keys3[i]; if (!matcher || matchHeaderValue(this, this[key], key, matcher, true)) { delete this[key]; deleted = true; } } return deleted; } normalize(format) { const self2 = this; const headers = {}; utils_default.forEach(this, (value, header) => { const key = utils_default.findKey(headers, header); if (key) { self2[key] = normalizeValue(value); delete self2[header]; return; } const normalized = format ? formatHeader(header) : String(header).trim(); if (normalized !== header) { delete self2[header]; } self2[normalized] = normalizeValue(value); headers[normalized] = true; }); return this; } concat(...targets) { return this.constructor.concat(this, ...targets); } toJSON(asStrings) { const obj = /* @__PURE__ */ Object.create(null); utils_default.forEach(this, (value, header) => { value != null && value !== false && (obj[header] = asStrings && utils_default.isArray(value) ? value.join(", ") : value); }); return obj; } [Symbol.iterator]() { return Object.entries(this.toJSON())[Symbol.iterator](); } toString() { return Object.entries(this.toJSON()).map(([header, value]) => header + ": " + value).join("\n"); } get [Symbol.toStringTag]() { return "AxiosHeaders"; } static from(thing) { return thing instanceof this ? thing : new this(thing); } static concat(first, ...targets) { const computed = new this(first); targets.forEach((target) => computed.set(target)); return computed; } static accessor(header) { const internals = this[$internals] = this[$internals] = { accessors: {} }; const accessors = internals.accessors; const prototype3 = this.prototype; function defineAccessor(_header) { const lHeader = normalizeHeader(_header); if (!accessors[lHeader]) { buildAccessors(prototype3, _header); accessors[lHeader] = true; } } utils_default.isArray(header) ? header.forEach(defineAccessor) : defineAccessor(header); return this; } }; AxiosHeaders.accessor(["Content-Type", "Content-Length", "Accept", "Accept-Encoding", "User-Agent", "Authorization"]); utils_default.freezeMethods(AxiosHeaders.prototype); utils_default.freezeMethods(AxiosHeaders); AxiosHeaders_default = AxiosHeaders; } }); // node_modules/axios/lib/core/transformData.js function transformData(fns, response) { const config = this || defaults_default; const context = response || config; const headers = AxiosHeaders_default.from(context.headers); let data = context.data; utils_default.forEach(fns, function transform(fn) { data = fn.call(config, data, headers.normalize(), response ? response.status : void 0); }); headers.normalize(); return data; } var init_transformData = __esm({ "node_modules/axios/lib/core/transformData.js"() { "use strict"; init_utils(); init_defaults(); init_AxiosHeaders(); } }); // node_modules/axios/lib/cancel/isCancel.js function isCancel(value) { return !!(value && value.__CANCEL__); } var init_isCancel = __esm({ "node_modules/axios/lib/cancel/isCancel.js"() { "use strict"; } }); // node_modules/axios/lib/cancel/CanceledError.js function CanceledError(message, config, request) { AxiosError_default.call(this, message == null ? "canceled" : message, AxiosError_default.ERR_CANCELED, config, request); this.name = "CanceledError"; } var CanceledError_default; var init_CanceledError = __esm({ "node_modules/axios/lib/cancel/CanceledError.js"() { "use strict"; init_AxiosError(); init_utils(); utils_default.inherits(CanceledError, AxiosError_default, { __CANCEL__: true }); CanceledError_default = CanceledError; } }); // node_modules/axios/lib/core/settle.js function settle(resolve, reject, response) { const validateStatus2 = response.config.validateStatus; if (!response.status || !validateStatus2 || validateStatus2(response.status)) { resolve(response); } else { reject(new AxiosError_default( "Request failed with status code " + response.status, [AxiosError_default.ERR_BAD_REQUEST, AxiosError_default.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response )); } } var init_settle = __esm({ "node_modules/axios/lib/core/settle.js"() { "use strict"; init_AxiosError(); } }); // node_modules/axios/lib/helpers/cookies.js var cookies_default; var init_cookies = __esm({ "node_modules/axios/lib/helpers/cookies.js"() { "use strict"; init_utils(); init_platform(); cookies_default = browser_default.isStandardBrowserEnv ? ( // Standard browser envs support document.cookie function standardBrowserEnv() { return { write: function write(name, value, expires, path2, domain, secure) { const cookie = []; cookie.push(name + "=" + encodeURIComponent(value)); if (utils_default.isNumber(expires)) { cookie.push("expires=" + new Date(expires).toGMTString()); } if (utils_default.isString(path2)) { cookie.push("path=" + path2); } if (utils_default.isString(domain)) { cookie.push("domain=" + domain); } if (secure === true) { cookie.push("secure"); } document.cookie = cookie.join("; "); }, read: function read(name) { const match2 = document.cookie.match(new RegExp("(^|;\\s*)(" + name + ")=([^;]*)")); return match2 ? decodeURIComponent(match2[3]) : null; }, remove: function remove(name) { this.write(name, "", Date.now() - 864e5); } }; }() ) : ( // Non standard browser env (web workers, react-native) lack needed support. function nonStandardBrowserEnv() { return { write: function write() { }, read: function read() { return null; }, remove: function remove() { } }; }() ); } }); // node_modules/axios/lib/helpers/isAbsoluteURL.js function isAbsoluteURL(url) { return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } var init_isAbsoluteURL = __esm({ "node_modules/axios/lib/helpers/isAbsoluteURL.js"() { "use strict"; } }); // node_modules/axios/lib/helpers/combineURLs.js function combineURLs(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; } var init_combineURLs = __esm({ "node_modules/axios/lib/helpers/combineURLs.js"() { "use strict"; } }); // node_modules/axios/lib/core/buildFullPath.js function buildFullPath(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL(requestedURL)) { return combineURLs(baseURL, requestedURL); } return requestedURL; } var init_buildFullPath = __esm({ "node_modules/axios/lib/core/buildFullPath.js"() { "use strict"; init_isAbsoluteURL(); init_combineURLs(); } }); // node_modules/axios/lib/helpers/isURLSameOrigin.js var isURLSameOrigin_default; var init_isURLSameOrigin = __esm({ "node_modules/axios/lib/helpers/isURLSameOrigin.js"() { "use strict"; init_utils(); init_platform(); isURLSameOrigin_default = browser_default.isStandardBrowserEnv ? ( // Standard browser envs have full support of the APIs needed to test // whether the request URL is of the same origin as current location. function standardBrowserEnv2() { const msie = /(msie|trident)/i.test(navigator.userAgent); const urlParsingNode = document.createElement("a"); let originURL; function resolveURL(url) { let href = url; if (msie) { urlParsingNode.setAttribute("href", href); href = urlParsingNode.href; } urlParsingNode.setAttribute("href", href); return { href: urlParsingNode.href, protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, "") : "", host: urlParsingNode.host, search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, "") : "", hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, "") : "", hostname: urlParsingNode.hostname, port: urlParsingNode.port, pathname: urlParsingNode.pathname.charAt(0) === "/" ? urlParsingNode.pathname : "/" + urlParsingNode.pathname }; } originURL = resolveURL(window.location.href); return function isURLSameOrigin(requestURL) { const parsed = utils_default.isString(requestURL) ? resolveURL(requestURL) : requestURL; return parsed.protocol === originURL.protocol && parsed.host === originURL.host; }; }() ) : ( // Non standard browser envs (web workers, react-native) lack needed support. function nonStandardBrowserEnv2() { return function isURLSameOrigin() { return true; }; }() ); } }); // node_modules/axios/lib/helpers/parseProtocol.js function parseProtocol(url) { const match2 = /^([-+\w]{1,25})(:?\/\/|:)/.exec(url); return match2 && match2[1] || ""; } var init_parseProtocol = __esm({ "node_modules/axios/lib/helpers/parseProtocol.js"() { "use strict"; } }); // node_modules/axios/lib/helpers/speedometer.js function speedometer(samplesCount, min) { samplesCount = samplesCount || 10; const bytes = new Array(samplesCount); const timestamps = new Array(samplesCount); let head = 0; let tail = 0; let firstSampleTS; min = min !== void 0 ? min : 1e3; return function push2(chunkLength) { const now = Date.now(); const startedAt = timestamps[tail]; if (!firstSampleTS) { firstSampleTS = now; } bytes[head] = chunkLength; timestamps[head] = now; let i = tail; let bytesCount = 0; while (i !== head) { bytesCount += bytes[i++]; i = i % samplesCount; } head = (head + 1) % samplesCount; if (head === tail) { tail = (tail + 1) % samplesCount; } if (now - firstSampleTS < min) { return; } const passed = startedAt && now - startedAt; return passed ? Math.round(bytesCount * 1e3 / passed) : void 0; }; } var speedometer_default; var init_speedometer = __esm({ "node_modules/axios/lib/helpers/speedometer.js"() { "use strict"; speedometer_default = speedometer; } }); // node_modules/axios/lib/adapters/xhr.js function progressEventReducer(listener, isDownloadStream) { let bytesNotified = 0; const _speedometer = speedometer_default(50, 250); return (e) => { const loaded = e.loaded; const total = e.lengthComputable ? e.total : void 0; const progressBytes = loaded - bytesNotified; const rate = _speedometer(progressBytes); const inRange = loaded <= total; bytesNotified = loaded; const data = { loaded, total, progress: total ? loaded / total : void 0, bytes: progressBytes, rate: rate ? rate : void 0, estimated: rate && total && inRange ? (total - loaded) / rate : void 0, event: e }; data[isDownloadStream ? "download" : "upload"] = true; listener(data); }; } var isXHRAdapterSupported, xhr_default; var init_xhr = __esm({ "node_modules/axios/lib/adapters/xhr.js"() { "use strict"; init_utils(); init_settle(); init_cookies(); init_buildURL(); init_buildFullPath(); init_isURLSameOrigin(); init_transitional(); init_AxiosError(); init_CanceledError(); init_parseProtocol(); init_platform(); init_AxiosHeaders(); init_speedometer(); isXHRAdapterSupported = typeof XMLHttpRequest !== "undefined"; xhr_default = isXHRAdapterSupported && function(config) { return new Promise(function dispatchXhrRequest(resolve, reject) { let requestData = config.data; const requestHeaders = AxiosHeaders_default.from(config.headers).normalize(); const responseType = config.responseType; let onCanceled; function done() { if (config.cancelToken) { config.cancelToken.unsubscribe(onCanceled); } if (config.signal) { config.signal.removeEventListener("abort", onCanceled); } } if (utils_default.isFormData(requestData) && (browser_default.isStandardBrowserEnv || browser_default.isStandardBrowserWebWorkerEnv)) { requestHeaders.setContentType(false); } let request = new XMLHttpRequest(); if (config.auth) { const username = config.auth.username || ""; const password = config.auth.password ? unescape(encodeURIComponent(config.auth.password)) : ""; requestHeaders.set("Authorization", "Basic " + btoa(username + ":" + password)); } const fullPath = buildFullPath(config.baseURL, config.url); request.open(config.method.toUpperCase(), buildURL(fullPath, config.params, config.paramsSerializer), true); request.timeout = config.timeout; function onloadend() { if (!request) { return; } const responseHeaders = AxiosHeaders_default.from( "getAllResponseHeaders" in request && request.getAllResponseHeaders() ); const responseData = !responseType || responseType === "text" || responseType === "json" ? request.responseText : request.response; const response = { data: responseData, status: request.status, statusText: request.statusText, headers: responseHeaders, config, request }; settle(function _resolve(value) { resolve(value); done(); }, function _reject(err) { reject(err); done(); }, response); request = null; } if ("onloadend" in request) { request.onloadend = onloadend; } else { request.onreadystatechange = function handleLoad() { if (!request || request.readyState !== 4) { return; } if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf("file:") === 0)) { return; } setTimeout(onloadend); }; } request.onabort = function handleAbort() { if (!request) { return; } reject(new AxiosError_default("Request aborted", AxiosError_default.ECONNABORTED, config, request)); request = null; }; request.onerror = function handleError() { reject(new AxiosError_default("Network Error", AxiosError_default.ERR_NETWORK, config, request)); request = null; }; request.ontimeout = function handleTimeout() { let timeoutErrorMessage = config.timeout ? "timeout of " + config.timeout + "ms exceeded" : "timeout exceeded"; const transitional2 = config.transitional || transitional_default; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } reject(new AxiosError_default( timeoutErrorMessage, transitional2.clarifyTimeoutError ? AxiosError_default.ETIMEDOUT : AxiosError_default.ECONNABORTED, config, request )); request = null; }; if (browser_default.isStandardBrowserEnv) { const xsrfValue = (config.withCredentials || isURLSameOrigin_default(fullPath)) && config.xsrfCookieName && cookies_default.read(config.xsrfCookieName); if (xsrfValue) { requestHeaders.set(config.xsrfHeaderName, xsrfValue); } } requestData === void 0 && requestHeaders.setContentType(null); if ("setRequestHeader" in request) { utils_default.forEach(requestHeaders.toJSON(), function setRequestHeader(val, key) { request.setRequestHeader(key, val); }); } if (!utils_default.isUndefined(config.withCredentials)) { request.withCredentials = !!config.withCredentials; } if (responseType && responseType !== "json") { request.responseType = config.responseType; } if (typeof config.onDownloadProgress === "function") { request.addEventListener("progress", progressEventReducer(config.onDownloadProgress, true)); } if (typeof config.onUploadProgress === "function" && request.upload) { request.upload.addEventListener("progress", progressEventReducer(config.onUploadProgress)); } if (config.cancelToken || config.signal) { onCanceled = (cancel) => { if (!request) { return; } reject(!cancel || cancel.type ? new CanceledError_default(null, config, request) : cancel); request.abort(); request = null; }; config.cancelToken && config.cancelToken.subscribe(onCanceled); if (config.signal) { config.signal.aborted ? onCanceled() : config.signal.addEventListener("abort", onCanceled); } } const protocol = parseProtocol(fullPath); if (protocol && browser_default.protocols.indexOf(protocol) === -1) { reject(new AxiosError_default("Unsupported protocol " + protocol + ":", AxiosError_default.ERR_BAD_REQUEST, config)); return; } request.send(requestData || null); }); }; } }); // node_modules/axios/lib/adapters/adapters.js var knownAdapters, adapters_default; var init_adapters = __esm({ "node_modules/axios/lib/adapters/adapters.js"() { init_utils(); init_null(); init_xhr(); init_AxiosError(); knownAdapters = { http: null_default, xhr: xhr_default }; utils_default.forEach(knownAdapters, (fn, value) => { if (fn) { try { Object.defineProperty(fn, "name", { value }); } catch (e) { } Object.defineProperty(fn, "adapterName", { value }); } }); adapters_default = { getAdapter: (adapters) => { adapters = utils_default.isArray(adapters) ? adapters : [adapters]; const { length } = adapters; let nameOrAdapter; let adapter; for (let i = 0; i < length; i++) { nameOrAdapter = adapters[i]; if (adapter = utils_default.isString(nameOrAdapter) ? knownAdapters[nameOrAdapter.toLowerCase()] : nameOrAdapter) { break; } } if (!adapter) { if (adapter === false) { throw new AxiosError_default( `Adapter ${nameOrAdapter} is not supported by the environment`, "ERR_NOT_SUPPORT" ); } throw new Error( utils_default.hasOwnProp(knownAdapters, nameOrAdapter) ? `Adapter '${nameOrAdapter}' is not available in the build` : `Unknown adapter '${nameOrAdapter}'` ); } if (!utils_default.isFunction(adapter)) { throw new TypeError("adapter is not a function"); } return adapter; }, adapters: knownAdapters }; } }); // node_modules/axios/lib/core/dispatchRequest.js function throwIfCancellationRequested(config) { if (config.cancelToken) { config.cancelToken.throwIfRequested(); } if (config.signal && config.signal.aborted) { throw new CanceledError_default(null, config); } } function dispatchRequest(config) { throwIfCancellationRequested(config); config.headers = AxiosHeaders_default.from(config.headers); config.data = transformData.call( config, config.transformRequest ); if (["post", "put", "patch"].indexOf(config.method) !== -1) { config.headers.setContentType("application/x-www-form-urlencoded", false); } const adapter = adapters_default.getAdapter(config.adapter || defaults_default.adapter); return adapter(config).then(function onAdapterResolution(response) { throwIfCancellationRequested(config); response.data = transformData.call( config, config.transformResponse, response ); response.headers = AxiosHeaders_default.from(response.headers); return response; }, function onAdapterRejection(reason) { if (!isCancel(reason)) { throwIfCancellationRequested(config); if (reason && reason.response) { reason.response.data = transformData.call( config, config.transformResponse, reason.response ); reason.response.headers = AxiosHeaders_default.from(reason.response.headers); } } return Promise.reject(reason); }); } var init_dispatchRequest = __esm({ "node_modules/axios/lib/core/dispatchRequest.js"() { "use strict"; init_transformData(); init_isCancel(); init_defaults(); init_CanceledError(); init_AxiosHeaders(); init_adapters(); } }); // node_modules/axios/lib/core/mergeConfig.js function mergeConfig(config1, config2) { config2 = config2 || {}; const config = {}; function getMergedValue(target, source, caseless) { if (utils_default.isPlainObject(target) && utils_default.isPlainObject(source)) { return utils_default.merge.call({ caseless }, target, source); } else if (utils_default.isPlainObject(source)) { return utils_default.merge({}, source); } else if (utils_default.isArray(source)) { return source.slice(); } return source; } function mergeDeepProperties(a2, b, caseless) { if (!utils_default.isUndefined(b)) { return getMergedValue(a2, b, caseless); } else if (!utils_default.isUndefined(a2)) { return getMergedValue(void 0, a2, caseless); } } function valueFromConfig2(a2, b) { if (!utils_default.isUndefined(b)) { return getMergedValue(void 0, b); } } function defaultToConfig2(a2, b) { if (!utils_default.isUndefined(b)) { return getMergedValue(void 0, b); } else if (!utils_default.isUndefined(a2)) { return getMergedValue(void 0, a2); } } function mergeDirectKeys(a2, b, prop) { if (prop in config2) { return getMergedValue(a2, b); } else if (prop in config1) { return getMergedValue(void 0, a2); } } const mergeMap = { url: valueFromConfig2, method: valueFromConfig2, data: valueFromConfig2, baseURL: defaultToConfig2, transformRequest: defaultToConfig2, transformResponse: defaultToConfig2, paramsSerializer: defaultToConfig2, timeout: defaultToConfig2, timeoutMessage: defaultToConfig2, withCredentials: defaultToConfig2, adapter: defaultToConfig2, responseType: defaultToConfig2, xsrfCookieName: defaultToConfig2, xsrfHeaderName: defaultToConfig2, onUploadProgress: defaultToConfig2, onDownloadProgress: defaultToConfig2, decompress: defaultToConfig2, maxContentLength: defaultToConfig2, maxBodyLength: defaultToConfig2, beforeRedirect: defaultToConfig2, transport: defaultToConfig2, httpAgent: defaultToConfig2, httpsAgent: defaultToConfig2, cancelToken: defaultToConfig2, socketPath: defaultToConfig2, responseEncoding: defaultToConfig2, validateStatus: mergeDirectKeys, headers: (a2, b) => mergeDeepProperties(headersToObject(a2), headersToObject(b), true) }; utils_default.forEach(Object.keys(config1).concat(Object.keys(config2)), function computeConfigValue(prop) { const merge5 = mergeMap[prop] || mergeDeepProperties; const configValue = merge5(config1[prop], config2[prop], prop); utils_default.isUndefined(configValue) && merge5 !== mergeDirectKeys || (config[prop] = configValue); }); return config; } var headersToObject; var init_mergeConfig = __esm({ "node_modules/axios/lib/core/mergeConfig.js"() { "use strict"; init_utils(); init_AxiosHeaders(); headersToObject = (thing) => thing instanceof AxiosHeaders_default ? thing.toJSON() : thing; } }); // node_modules/axios/lib/env/data.js var VERSION; var init_data = __esm({ "node_modules/axios/lib/env/data.js"() { VERSION = "1.3.6"; } }); // node_modules/axios/lib/helpers/validator.js function assertOptions(options, schema2, allowUnknown) { if (typeof options !== "object") { throw new AxiosError_default("options must be an object", AxiosError_default.ERR_BAD_OPTION_VALUE); } const keys3 = Object.keys(options); let i = keys3.length; while (i-- > 0) { const opt = keys3[i]; const validator = schema2[opt]; if (validator) { const value = options[opt]; const result = value === void 0 || validator(value, opt, options); if (result !== true) { throw new AxiosError_default("option " + opt + " must be " + result, AxiosError_default.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { throw new AxiosError_default("Unknown option " + opt, AxiosError_default.ERR_BAD_OPTION); } } } var validators, deprecatedWarnings, validator_default; var init_validator = __esm({ "node_modules/axios/lib/helpers/validator.js"() { "use strict"; init_data(); init_AxiosError(); validators = {}; ["object", "boolean", "number", "function", "string", "symbol"].forEach((type2, i) => { validators[type2] = function validator(thing) { return typeof thing === type2 || "a" + (i < 1 ? "n " : " ") + type2; }; }); deprecatedWarnings = {}; validators.transitional = function transitional(validator, version2, message) { function formatMessage(opt, desc) { return "[Axios v" + VERSION + "] Transitional option '" + opt + "'" + desc + (message ? ". " + message : ""); } return (value, opt, opts) => { if (validator === false) { throw new AxiosError_default( formatMessage(opt, " has been removed" + (version2 ? " in " + version2 : "")), AxiosError_default.ERR_DEPRECATED ); } if (version2 && !deprecatedWarnings[opt]) { deprecatedWarnings[opt] = true; console.warn( formatMessage( opt, " has been deprecated since v" + version2 + " and will be removed in the near future" ) ); } return validator ? validator(value, opt, opts) : true; }; }; validator_default = { assertOptions, validators }; } }); // node_modules/axios/lib/core/Axios.js var validators2, Axios, Axios_default; var init_Axios = __esm({ "node_modules/axios/lib/core/Axios.js"() { "use strict"; init_utils(); init_buildURL(); init_InterceptorManager(); init_dispatchRequest(); init_mergeConfig(); init_buildFullPath(); init_validator(); init_AxiosHeaders(); validators2 = validator_default.validators; Axios = class { constructor(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { request: new InterceptorManager_default(), response: new InterceptorManager_default() }; } /** * Dispatch a request * * @param {String|Object} configOrUrl The config specific for this request (merged with this.defaults) * @param {?Object} config * * @returns {Promise} The Promise to be fulfilled */ request(configOrUrl, config) { if (typeof configOrUrl === "string") { config = config || {}; config.url = configOrUrl; } else { config = configOrUrl || {}; } config = mergeConfig(this.defaults, config); const { transitional: transitional2, paramsSerializer, headers } = config; if (transitional2 !== void 0) { validator_default.assertOptions(transitional2, { silentJSONParsing: validators2.transitional(validators2.boolean), forcedJSONParsing: validators2.transitional(validators2.boolean), clarifyTimeoutError: validators2.transitional(validators2.boolean) }, false); } if (paramsSerializer != null) { if (utils_default.isFunction(paramsSerializer)) { config.paramsSerializer = { serialize: paramsSerializer }; } else { validator_default.assertOptions(paramsSerializer, { encode: validators2.function, serialize: validators2.function }, true); } } config.method = (config.method || this.defaults.method || "get").toLowerCase(); let contextHeaders; contextHeaders = headers && utils_default.merge( headers.common, headers[config.method] ); contextHeaders && utils_default.forEach( ["delete", "get", "head", "post", "put", "patch", "common"], (method) => { delete headers[method]; } ); config.headers = AxiosHeaders_default.concat(contextHeaders, headers); const requestInterceptorChain = []; let synchronousRequestInterceptors = true; this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { if (typeof interceptor.runWhen === "function" && interceptor.runWhen(config) === false) { return; } synchronousRequestInterceptors = synchronousRequestInterceptors && interceptor.synchronous; requestInterceptorChain.unshift(interceptor.fulfilled, interceptor.rejected); }); const responseInterceptorChain = []; this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { responseInterceptorChain.push(interceptor.fulfilled, interceptor.rejected); }); let promise; let i = 0; let len; if (!synchronousRequestInterceptors) { const chain = [dispatchRequest.bind(this), void 0]; chain.unshift.apply(chain, requestInterceptorChain); chain.push.apply(chain, responseInterceptorChain); len = chain.length; promise = Promise.resolve(config); while (i < len) { promise = promise.then(chain[i++], chain[i++]); } return promise; } len = requestInterceptorChain.length; let newConfig = config; i = 0; while (i < len) { const onFulfilled = requestInterceptorChain[i++]; const onRejected = requestInterceptorChain[i++]; try { newConfig = onFulfilled(newConfig); } catch (error) { onRejected.call(this, error); break; } } try { promise = dispatchRequest.call(this, newConfig); } catch (error) { return Promise.reject(error); } i = 0; len = responseInterceptorChain.length; while (i < len) { promise = promise.then(responseInterceptorChain[i++], responseInterceptorChain[i++]); } return promise; } getUri(config) { config = mergeConfig(this.defaults, config); const fullPath = buildFullPath(config.baseURL, config.url); return buildURL(fullPath, config.params, config.paramsSerializer); } }; utils_default.forEach(["delete", "get", "head", "options"], function forEachMethodNoData2(method) { Axios.prototype[method] = function(url, config) { return this.request(mergeConfig(config || {}, { method, url, data: (config || {}).data })); }; }); utils_default.forEach(["post", "put", "patch"], function forEachMethodWithData2(method) { function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { return this.request(mergeConfig(config || {}, { method, headers: isForm ? { "Content-Type": "multipart/form-data" } : {}, url, data })); }; } Axios.prototype[method] = generateHTTPMethod(); Axios.prototype[method + "Form"] = generateHTTPMethod(true); }); Axios_default = Axios; } }); // node_modules/axios/lib/cancel/CancelToken.js var CancelToken, CancelToken_default; var init_CancelToken = __esm({ "node_modules/axios/lib/cancel/CancelToken.js"() { "use strict"; init_CanceledError(); CancelToken = class { constructor(executor) { if (typeof executor !== "function") { throw new TypeError("executor must be a function."); } let resolvePromise; this.promise = new Promise(function promiseExecutor(resolve) { resolvePromise = resolve; }); const token = this; this.promise.then((cancel) => { if (!token._listeners) return; let i = token._listeners.length; while (i-- > 0) { token._listeners[i](cancel); } token._listeners = null; }); this.promise.then = (onfulfilled) => { let _resolve; const promise = new Promise((resolve) => { token.subscribe(resolve); _resolve = resolve; }).then(onfulfilled); promise.cancel = function reject() { token.unsubscribe(_resolve); }; return promise; }; executor(function cancel(message, config, request) { if (token.reason) { return; } token.reason = new CanceledError_default(message, config, request); resolvePromise(token.reason); }); } /** * Throws a `CanceledError` if cancellation has been requested. */ throwIfRequested() { if (this.reason) { throw this.reason; } } /** * Subscribe to the cancel signal */ subscribe(listener) { if (this.reason) { listener(this.reason); return; } if (this._listeners) { this._listeners.push(listener); } else { this._listeners = [listener]; } } /** * Unsubscribe from the cancel signal */ unsubscribe(listener) { if (!this._listeners) { return; } const index2 = this._listeners.indexOf(listener); if (index2 !== -1) { this._listeners.splice(index2, 1); } } /** * Returns an object that contains a new `CancelToken` and a function that, when called, * cancels the `CancelToken`. */ static source() { let cancel; const token = new CancelToken(function executor(c) { cancel = c; }); return { token, cancel }; } }; CancelToken_default = CancelToken; } }); // node_modules/axios/lib/helpers/spread.js function spread(callback) { return function wrap4(arr) { return callback.apply(null, arr); }; } var init_spread = __esm({ "node_modules/axios/lib/helpers/spread.js"() { "use strict"; } }); // node_modules/axios/lib/helpers/isAxiosError.js function isAxiosError(payload) { return utils_default.isObject(payload) && payload.isAxiosError === true; } var init_isAxiosError = __esm({ "node_modules/axios/lib/helpers/isAxiosError.js"() { "use strict"; init_utils(); } }); // node_modules/axios/lib/helpers/HttpStatusCode.js var HttpStatusCode, HttpStatusCode_default; var init_HttpStatusCode = __esm({ "node_modules/axios/lib/helpers/HttpStatusCode.js"() { HttpStatusCode = { Continue: 100, SwitchingProtocols: 101, Processing: 102, EarlyHints: 103, Ok: 200, Created: 201, Accepted: 202, NonAuthoritativeInformation: 203, NoContent: 204, ResetContent: 205, PartialContent: 206, MultiStatus: 207, AlreadyReported: 208, ImUsed: 226, MultipleChoices: 300, MovedPermanently: 301, Found: 302, SeeOther: 303, NotModified: 304, UseProxy: 305, Unused: 306, TemporaryRedirect: 307, PermanentRedirect: 308, BadRequest: 400, Unauthorized: 401, PaymentRequired: 402, Forbidden: 403, NotFound: 404, MethodNotAllowed: 405, NotAcceptable: 406, ProxyAuthenticationRequired: 407, RequestTimeout: 408, Conflict: 409, Gone: 410, LengthRequired: 411, PreconditionFailed: 412, PayloadTooLarge: 413, UriTooLong: 414, UnsupportedMediaType: 415, RangeNotSatisfiable: 416, ExpectationFailed: 417, ImATeapot: 418, MisdirectedRequest: 421, UnprocessableEntity: 422, Locked: 423, FailedDependency: 424, TooEarly: 425, UpgradeRequired: 426, PreconditionRequired: 428, TooManyRequests: 429, RequestHeaderFieldsTooLarge: 431, UnavailableForLegalReasons: 451, InternalServerError: 500, NotImplemented: 501, BadGateway: 502, ServiceUnavailable: 503, GatewayTimeout: 504, HttpVersionNotSupported: 505, VariantAlsoNegotiates: 506, InsufficientStorage: 507, LoopDetected: 508, NotExtended: 510, NetworkAuthenticationRequired: 511 }; Object.entries(HttpStatusCode).forEach(([key, value]) => { HttpStatusCode[value] = key; }); HttpStatusCode_default = HttpStatusCode; } }); // node_modules/axios/lib/axios.js function createInstance(defaultConfig) { const context = new Axios_default(defaultConfig); const instance = bind(Axios_default.prototype.request, context); utils_default.extend(instance, Axios_default.prototype, context, { allOwnKeys: true }); utils_default.extend(instance, context, null, { allOwnKeys: true }); instance.create = function create2(instanceConfig) { return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; return instance; } var axios, axios_default; var init_axios = __esm({ "node_modules/axios/lib/axios.js"() { "use strict"; init_utils(); init_bind(); init_Axios(); init_mergeConfig(); init_defaults(); init_formDataToJSON(); init_CanceledError(); init_CancelToken(); init_isCancel(); init_data(); init_toFormData(); init_AxiosError(); init_spread(); init_isAxiosError(); init_AxiosHeaders(); init_HttpStatusCode(); axios = createInstance(defaults_default); axios.Axios = Axios_default; axios.CanceledError = CanceledError_default; axios.CancelToken = CancelToken_default; axios.isCancel = isCancel; axios.VERSION = VERSION; axios.toFormData = toFormData_default; axios.AxiosError = AxiosError_default; axios.Cancel = axios.CanceledError; axios.all = function all(promises) { return Promise.all(promises); }; axios.spread = spread; axios.isAxiosError = isAxiosError; axios.mergeConfig = mergeConfig; axios.AxiosHeaders = AxiosHeaders_default; axios.formToJSON = (thing) => formDataToJSON_default(utils_default.isHTMLForm(thing) ? new FormData(thing) : thing); axios.HttpStatusCode = HttpStatusCode_default; axios.default = axios; axios_default = axios; } }); // node_modules/axios/index.js var Axios2, AxiosError2, CanceledError2, isCancel2, CancelToken2, VERSION2, all2, Cancel, isAxiosError2, spread2, toFormData2, AxiosHeaders2, HttpStatusCode2, formToJSON, mergeConfig2; var init_axios2 = __esm({ "node_modules/axios/index.js"() { init_axios(); ({ Axios: Axios2, AxiosError: AxiosError2, CanceledError: CanceledError2, isCancel: isCancel2, CancelToken: CancelToken2, VERSION: VERSION2, all: all2, Cancel, isAxiosError: isAxiosError2, spread: spread2, toFormData: toFormData2, AxiosHeaders: AxiosHeaders2, HttpStatusCode: HttpStatusCode2, formToJSON, mergeConfig: mergeConfig2 } = axios_default); } }); // node_modules/langchain/dist/util/event-source-parse.js async function getBytes(stream, onChunk) { const reader = stream.getReader(); while (true) { const result = await reader.read(); if (result.done) { onChunk(new Uint8Array(), true); break; } onChunk(result.value); } } function getLines(onLine) { let buffer2; let position3; let fieldLength; let discardTrailingNewline = false; return function onChunk(arr, flush) { if (flush) { onLine(arr, 0, true); return; } if (buffer2 === void 0) { buffer2 = arr; position3 = 0; fieldLength = -1; } else { buffer2 = concat(buffer2, arr); } const bufLength = buffer2.length; let lineStart = 0; while (position3 < bufLength) { if (discardTrailingNewline) { if (buffer2[position3] === 10) { lineStart = ++position3; } discardTrailingNewline = false; } let lineEnd = -1; for (; position3 < bufLength && lineEnd === -1; ++position3) { switch (buffer2[position3]) { case 58: if (fieldLength === -1) { fieldLength = position3 - lineStart; } break; case 13: discardTrailingNewline = true; case 10: lineEnd = position3; break; } } if (lineEnd === -1) { break; } onLine(buffer2.subarray(lineStart, lineEnd), fieldLength); lineStart = position3; fieldLength = -1; } if (lineStart === bufLength) { buffer2 = void 0; } else if (lineStart !== 0) { buffer2 = buffer2.subarray(lineStart); position3 -= lineStart; } }; } function getMessages(onMessage, onId, onRetry) { let message = newMessage(); const decoder = new TextDecoder(); return function onLine(line, fieldLength, flush) { if (flush) { if (!isEmpty(message)) { onMessage == null ? void 0 : onMessage(message); message = newMessage(); } return; } if (line.length === 0) { onMessage == null ? void 0 : onMessage(message); message = newMessage(); } else if (fieldLength > 0) { const field = decoder.decode(line.subarray(0, fieldLength)); const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1); const value = decoder.decode(line.subarray(valueOffset)); switch (field) { case "data": message.data = message.data ? message.data + "\n" + value : value; break; case "event": message.event = value; break; case "id": onId == null ? void 0 : onId(message.id = value); break; case "retry": { const retry = parseInt(value, 10); if (!Number.isNaN(retry)) { onRetry == null ? void 0 : onRetry(message.retry = retry); } break; } } } }; } function concat(a2, b) { const res = new Uint8Array(a2.length + b.length); res.set(a2); res.set(b, a2.length); return res; } function newMessage() { return { data: "", event: "", id: "", retry: void 0 }; } function isEmpty(message) { return message.data === "" && message.event === "" && message.id === "" && message.retry === void 0; } var EventStreamContentType; var init_event_source_parse = __esm({ "node_modules/langchain/dist/util/event-source-parse.js"() { EventStreamContentType = "text/event-stream"; } }); // node_modules/langchain/dist/util/axios-fetch-adapter.js function tryJsonStringify2(data) { try { return JSON.stringify(data); } catch (e) { return data; } } function settle2(resolve, reject, response) { const { validateStatus: validateStatus2 } = response.config; if (!response.status || !validateStatus2 || validateStatus2(response.status)) { resolve(response); } else { reject(createError(`Request failed with status code ${response.status} and body ${typeof response.data === "string" ? response.data : tryJsonStringify2(response.data)}`, response.config, null, response.request, response)); } } function isAbsoluteURL2(url) { return /^([a-z][a-z\d+\-.]*:)?\/\//i.test(url); } function combineURLs2(baseURL, relativeURL) { return relativeURL ? baseURL.replace(/\/+$/, "") + "/" + relativeURL.replace(/^\/+/, "") : baseURL; } function encode3(val) { return encodeURIComponent(val).replace(/%3A/gi, ":").replace(/%24/g, "$").replace(/%2C/gi, ",").replace(/%20/g, "+").replace(/%5B/gi, "[").replace(/%5D/gi, "]"); } function buildURL2(url, params, paramsSerializer) { if (!params) { return url; } var serializedParams; if (paramsSerializer) { serializedParams = paramsSerializer(params); } else if (isURLSearchParams2(params)) { serializedParams = params.toString(); } else { var parts = []; forEach2(params, function serialize(val, key) { if (val === null || typeof val === "undefined") { return; } if (isArray2(val)) { key = `${key}[]`; } else { val = [val]; } forEach2(val, function parseValue(v) { if (isDate2(v)) { v = v.toISOString(); } else if (isObject2(v)) { v = JSON.stringify(v); } parts.push(`${encode3(key)}=${encode3(v)}`); }); }); serializedParams = parts.join("&"); } if (serializedParams) { var hashmarkIndex = url.indexOf("#"); if (hashmarkIndex !== -1) { url = url.slice(0, hashmarkIndex); } url += (url.indexOf("?") === -1 ? "?" : "&") + serializedParams; } return url; } function buildFullPath2(baseURL, requestedURL) { if (baseURL && !isAbsoluteURL2(requestedURL)) { return combineURLs2(baseURL, requestedURL); } return requestedURL; } function isUndefined2(val) { return typeof val === "undefined"; } function isObject2(val) { return val !== null && typeof val === "object"; } function isDate2(val) { return toString.call(val) === "[object Date]"; } function isURLSearchParams2(val) { return toString.call(val) === "[object URLSearchParams]"; } function isArray2(val) { return Array.isArray(val); } function forEach2(obj, fn) { if (obj === null || typeof obj === "undefined") { return; } if (typeof obj !== "object") { obj = [obj]; } if (isArray2(obj)) { for (var i = 0, l = obj.length; i < l; i++) { fn.call(null, obj[i], i, obj); } } else { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { fn.call(null, obj[key], key, obj); } } } } function isFormData2(val) { return toString.call(val) === "[object FormData]"; } function isStandardBrowserEnv2() { if (typeof navigator !== "undefined" && // eslint-disable-next-line no-undef (navigator.product === "ReactNative" || // eslint-disable-next-line no-undef navigator.product === "NativeScript" || // eslint-disable-next-line no-undef navigator.product === "NS")) { return false; } return typeof window !== "undefined" && typeof document !== "undefined"; } async function fetchAdapter(config) { const request = createRequest(config); const data = await getResponse(request, config); return new Promise((resolve, reject) => { if (data instanceof Error) { reject(data); } else { Object.prototype.toString.call(config.settle) === "[object Function]" ? config.settle(resolve, reject, data) : settle2(resolve, reject, data); } }); } async function getResponse(request, config) { let stageOne; try { stageOne = await fetch(request); } catch (e) { if (e && e.name === "AbortError") { return createError("Request aborted", config, "ECONNABORTED", request); } if (e && e.name === "TimeoutError") { return createError("Request timeout", config, "ECONNABORTED", request); } return createError("Network Error", config, "ERR_NETWORK", request); } const headers = {}; stageOne.headers.forEach((value, key) => { headers[key] = value; }); const response = { ok: stageOne.ok, status: stageOne.status, statusText: stageOne.statusText, headers, config, request }; if (stageOne.status >= 200 && stageOne.status !== 204) { if (config.responseType === "stream") { const contentType = stageOne.headers.get("content-type"); if (!(contentType == null ? void 0 : contentType.startsWith(EventStreamContentType))) { if (stageOne.status >= 400) { if (contentType == null ? void 0 : contentType.startsWith("application/json")) { response.data = await stageOne.json(); return response; } else { response.data = await stageOne.text(); return response; } } throw new Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${contentType}`); } await getBytes(stageOne.body, getLines(getMessages(config.onmessage))); } else { switch (config.responseType) { case "arraybuffer": response.data = await stageOne.arrayBuffer(); break; case "blob": response.data = await stageOne.blob(); break; case "json": response.data = await stageOne.json(); break; case "formData": response.data = await stageOne.formData(); break; default: response.data = await stageOne.text(); break; } } } return response; } function createRequest(config) { const headers = new Headers(config.headers); if (config.auth) { const username = config.auth.username || ""; const password = config.auth.password ? decodeURI(encodeURIComponent(config.auth.password)) : ""; headers.set("Authorization", `Basic ${btoa(`${username}:${password}`)}`); } const method = config.method.toUpperCase(); const options = { headers, method }; if (method !== "GET" && method !== "HEAD") { options.body = config.data; if (isFormData2(options.body) && isStandardBrowserEnv2()) { headers.delete("Content-Type"); } } if (typeof options.body === "string") { options.body = new TextEncoder().encode(options.body); } if (config.mode) { options.mode = config.mode; } if (config.cache) { options.cache = config.cache; } if (config.integrity) { options.integrity = config.integrity; } if (config.redirect) { options.redirect = config.redirect; } if (config.referrer) { options.referrer = config.referrer; } if (config.timeout && config.timeout > 0) { options.signal = AbortSignal.timeout(config.timeout); } if (config.signal) { options.signal = config.signal; } if (!isUndefined2(config.withCredentials)) { options.credentials = config.withCredentials ? "include" : "omit"; } if (config.responseType === "stream") { options.headers.set("Accept", EventStreamContentType); } const fullPath = buildFullPath2(config.baseURL, config.url); const url = buildURL2(fullPath, config.params, config.paramsSerializer); return new Request(url, options); } function createError(message, config, code2, request, response) { if (axios_default.AxiosError && typeof axios_default.AxiosError === "function") { return new axios_default.AxiosError(message, axios_default.AxiosError[code2], config, request, response); } const error = new Error(message); return enhanceError(error, config, code2, request, response); } function enhanceError(error, config, code2, request, response) { error.config = config; if (code2) { error.code = code2; } error.request = request; error.response = response; error.isAxiosError = true; error.toJSON = function toJSON3() { return { // Standard message: this.message, name: this.name, // Microsoft description: this.description, number: this.number, // Mozilla fileName: this.fileName, lineNumber: this.lineNumber, columnNumber: this.columnNumber, stack: this.stack, // Axios config: this.config, code: this.code, status: this.response && this.response.status ? this.response.status : null }; }; return error; } var init_axios_fetch_adapter = __esm({ "node_modules/langchain/dist/util/axios-fetch-adapter.js"() { init_axios2(); init_event_source_parse(); } }); // node_modules/langchain/dist/chat_models/base.js var BaseChatModel; var init_base3 = __esm({ "node_modules/langchain/dist/chat_models/base.js"() { init_schema(); init_base_language(); init_manager(); BaseChatModel = class extends BaseLanguageModel { constructor(fields) { super(fields); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "chat_models", this._llmType()] }); } async generate(messages4, options, callbacks) { var _a, _b; let parsedOptions; if (Array.isArray(options)) { parsedOptions = { stop: options }; } else if ((options == null ? void 0 : options.timeout) && !options.signal) { parsedOptions = { ...options, signal: AbortSignal.timeout(options.timeout) }; } else { parsedOptions = options != null ? options : {}; } const handledOptions = { tags: parsedOptions.tags, metadata: parsedOptions.metadata, callbacks: (_a = parsedOptions.callbacks) != null ? _a : callbacks }; delete parsedOptions.tags; delete parsedOptions.metadata; delete parsedOptions.callbacks; const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); const extra = { options: parsedOptions, invocation_params: this == null ? void 0 : this.invocationParams(parsedOptions) }; const runManagers = await (callbackManager_ == null ? void 0 : callbackManager_.handleChatModelStart(this.toJSON(), messages4, void 0, void 0, extra)); const results = await Promise.allSettled(messages4.map((messageList, i) => this._generate(messageList, { ...parsedOptions, promptIndex: i }, runManagers == null ? void 0 : runManagers[i]))); const generations = []; const llmOutputs = []; await Promise.all(results.map(async (pResult, i) => { var _a2, _b2; if (pResult.status === "fulfilled") { const result = pResult.value; generations[i] = result.generations; llmOutputs[i] = result.llmOutput; return (_a2 = runManagers == null ? void 0 : runManagers[i]) == null ? void 0 : _a2.handleLLMEnd({ generations: [result.generations], llmOutput: result.llmOutput }); } else { await ((_b2 = runManagers == null ? void 0 : runManagers[i]) == null ? void 0 : _b2.handleLLMError(pResult.reason)); return Promise.reject(pResult.reason); } })); const output = { generations, llmOutput: llmOutputs.length ? (_b = this._combineLLMOutput) == null ? void 0 : _b.call(this, ...llmOutputs) : void 0 }; Object.defineProperty(output, RUN_KEY, { value: runManagers ? { runIds: runManagers == null ? void 0 : runManagers.map((manager) => manager.runId) } : void 0, configurable: true }); return output; } /** * Get the parameters used to invoke the model */ // eslint-disable-next-line @typescript-eslint/no-explicit-any invocationParams(_options) { return {}; } _modelType() { return "base_chat_model"; } async generatePrompt(promptValues, options, callbacks) { const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); return this.generate(promptMessages, options, callbacks); } async call(messages4, options, callbacks) { const result = await this.generate([messages4], options, callbacks); const generations = result.generations; return generations[0][0].message; } async callPrompt(promptValue, options, callbacks) { const promptMessages = promptValue.toChatMessages(); return this.call(promptMessages, options, callbacks); } async predictMessages(messages4, options, callbacks) { return this.call(messages4, options, callbacks); } async predict(text4, options, callbacks) { const message = new HumanMessage(text4); const result = await this.call([message], options, callbacks); return result.content; } }; } }); // node_modules/langchain/dist/util/prompt-layer.js var promptLayerTrackRequest; var init_prompt_layer = __esm({ "node_modules/langchain/dist/util/prompt-layer.js"() { promptLayerTrackRequest = async (callerFunc, functionName, prompt, kwargs, plTags, requestResponse, startTime, endTime, apiKey) => { const promptLayerResp = await callerFunc.call(fetch, "https://api.promptlayer.com/track-request", { method: "POST", headers: { "Content-Type": "application/json", Accept: "application/json" }, body: JSON.stringify({ function_name: functionName, provider: "langchain", args: prompt, kwargs, tags: plTags, request_response: requestResponse, request_start_time: Math.floor(startTime / 1e3), request_end_time: Math.floor(endTime / 1e3), api_key: apiKey }) }); return promptLayerResp.json(); }; } }); // node_modules/zod/lib/helpers/util.js var require_util = __commonJS({ "node_modules/zod/lib/helpers/util.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getParsedType = exports.ZodParsedType = exports.objectUtil = exports.util = void 0; var util; (function(util2) { util2.assertEqual = (val) => val; function assertIs(_arg) { } util2.assertIs = assertIs; function assertNever(_x) { throw new Error(); } util2.assertNever = assertNever; util2.arrayToEnum = (items) => { const obj = {}; for (const item of items) { obj[item] = item; } return obj; }; util2.getValidEnumValues = (obj) => { const validKeys = util2.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); const filtered = {}; for (const k of validKeys) { filtered[k] = obj[k]; } return util2.objectValues(filtered); }; util2.objectValues = (obj) => { return util2.objectKeys(obj).map(function(e) { return obj[e]; }); }; util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object) => { const keys3 = []; for (const key in object) { if (Object.prototype.hasOwnProperty.call(object, key)) { keys3.push(key); } } return keys3; }; util2.find = (arr, checker) => { for (const item of arr) { if (checker(item)) return item; } return void 0; }; util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && isFinite(val) && Math.floor(val) === val; function joinValues(array, separator = " | ") { return array.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator); } util2.joinValues = joinValues; util2.jsonStringifyReplacer = (_, value) => { if (typeof value === "bigint") { return value.toString(); } return value; }; })(util = exports.util || (exports.util = {})); var objectUtil; (function(objectUtil2) { objectUtil2.mergeShapes = (first, second) => { return { ...first, ...second }; }; })(objectUtil = exports.objectUtil || (exports.objectUtil = {})); exports.ZodParsedType = util.arrayToEnum([ "string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set" ]); var getParsedType = (data) => { const t = typeof data; switch (t) { case "undefined": return exports.ZodParsedType.undefined; case "string": return exports.ZodParsedType.string; case "number": return isNaN(data) ? exports.ZodParsedType.nan : exports.ZodParsedType.number; case "boolean": return exports.ZodParsedType.boolean; case "function": return exports.ZodParsedType.function; case "bigint": return exports.ZodParsedType.bigint; case "symbol": return exports.ZodParsedType.symbol; case "object": if (Array.isArray(data)) { return exports.ZodParsedType.array; } if (data === null) { return exports.ZodParsedType.null; } if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { return exports.ZodParsedType.promise; } if (typeof Map !== "undefined" && data instanceof Map) { return exports.ZodParsedType.map; } if (typeof Set !== "undefined" && data instanceof Set) { return exports.ZodParsedType.set; } if (typeof Date !== "undefined" && data instanceof Date) { return exports.ZodParsedType.date; } return exports.ZodParsedType.object; default: return exports.ZodParsedType.unknown; } }; exports.getParsedType = getParsedType; } }); // node_modules/zod/lib/ZodError.js var require_ZodError = __commonJS({ "node_modules/zod/lib/ZodError.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ZodError = exports.quotelessJson = exports.ZodIssueCode = void 0; var util_1 = require_util(); exports.ZodIssueCode = util_1.util.arrayToEnum([ "invalid_type", "invalid_literal", "custom", "invalid_union", "invalid_union_discriminator", "invalid_enum_value", "unrecognized_keys", "invalid_arguments", "invalid_return_type", "invalid_date", "invalid_string", "too_small", "too_big", "invalid_intersection_types", "not_multiple_of", "not_finite" ]); var quotelessJson = (obj) => { const json2 = JSON.stringify(obj, null, 2); return json2.replace(/"([^"]+)":/g, "$1:"); }; exports.quotelessJson = quotelessJson; var ZodError = class extends Error { constructor(issues) { super(); this.issues = []; this.addIssue = (sub) => { this.issues = [...this.issues, sub]; }; this.addIssues = (subs = []) => { this.issues = [...this.issues, ...subs]; }; const actualProto = new.target.prototype; if (Object.setPrototypeOf) { Object.setPrototypeOf(this, actualProto); } else { this.__proto__ = actualProto; } this.name = "ZodError"; this.issues = issues; } get errors() { return this.issues; } format(_mapper) { const mapper2 = _mapper || function(issue) { return issue.message; }; const fieldErrors = { _errors: [] }; const processError = (error) => { for (const issue of error.issues) { if (issue.code === "invalid_union") { issue.unionErrors.map(processError); } else if (issue.code === "invalid_return_type") { processError(issue.returnTypeError); } else if (issue.code === "invalid_arguments") { processError(issue.argumentsError); } else if (issue.path.length === 0) { fieldErrors._errors.push(mapper2(issue)); } else { let curr = fieldErrors; let i = 0; while (i < issue.path.length) { const el = issue.path[i]; const terminal = i === issue.path.length - 1; if (!terminal) { curr[el] = curr[el] || { _errors: [] }; } else { curr[el] = curr[el] || { _errors: [] }; curr[el]._errors.push(mapper2(issue)); } curr = curr[el]; i++; } } } }; processError(this); return fieldErrors; } toString() { return this.message; } get message() { return JSON.stringify(this.issues, util_1.util.jsonStringifyReplacer, 2); } get isEmpty() { return this.issues.length === 0; } flatten(mapper2 = (issue) => issue.message) { const fieldErrors = {}; const formErrors = []; for (const sub of this.issues) { if (sub.path.length > 0) { fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; fieldErrors[sub.path[0]].push(mapper2(sub)); } else { formErrors.push(mapper2(sub)); } } return { formErrors, fieldErrors }; } get formErrors() { return this.flatten(); } }; exports.ZodError = ZodError; ZodError.create = (issues) => { const error = new ZodError(issues); return error; }; } }); // node_modules/zod/lib/locales/en.js var require_en = __commonJS({ "node_modules/zod/lib/locales/en.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util_1 = require_util(); var ZodError_1 = require_ZodError(); var errorMap = (issue, _ctx) => { let message; switch (issue.code) { case ZodError_1.ZodIssueCode.invalid_type: if (issue.received === util_1.ZodParsedType.undefined) { message = "Required"; } else { message = `Expected ${issue.expected}, received ${issue.received}`; } break; case ZodError_1.ZodIssueCode.invalid_literal: message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util_1.util.jsonStringifyReplacer)}`; break; case ZodError_1.ZodIssueCode.unrecognized_keys: message = `Unrecognized key(s) in object: ${util_1.util.joinValues(issue.keys, ", ")}`; break; case ZodError_1.ZodIssueCode.invalid_union: message = `Invalid input`; break; case ZodError_1.ZodIssueCode.invalid_union_discriminator: message = `Invalid discriminator value. Expected ${util_1.util.joinValues(issue.options)}`; break; case ZodError_1.ZodIssueCode.invalid_enum_value: message = `Invalid enum value. Expected ${util_1.util.joinValues(issue.options)}, received '${issue.received}'`; break; case ZodError_1.ZodIssueCode.invalid_arguments: message = `Invalid function arguments`; break; case ZodError_1.ZodIssueCode.invalid_return_type: message = `Invalid function return type`; break; case ZodError_1.ZodIssueCode.invalid_date: message = `Invalid date`; break; case ZodError_1.ZodIssueCode.invalid_string: if (typeof issue.validation === "object") { if ("includes" in issue.validation) { message = `Invalid input: must include "${issue.validation.includes}"`; if (typeof issue.validation.position === "number") { message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; } } else if ("startsWith" in issue.validation) { message = `Invalid input: must start with "${issue.validation.startsWith}"`; } else if ("endsWith" in issue.validation) { message = `Invalid input: must end with "${issue.validation.endsWith}"`; } else { util_1.util.assertNever(issue.validation); } } else if (issue.validation !== "regex") { message = `Invalid ${issue.validation}`; } else { message = "Invalid"; } break; case ZodError_1.ZodIssueCode.too_small: if (issue.type === "array") message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; else message = "Invalid input"; break; case ZodError_1.ZodIssueCode.too_big: if (issue.type === "array") message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; else if (issue.type === "string") message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; else if (issue.type === "number") message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "bigint") message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; else if (issue.type === "date") message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; else message = "Invalid input"; break; case ZodError_1.ZodIssueCode.custom: message = `Invalid input`; break; case ZodError_1.ZodIssueCode.invalid_intersection_types: message = `Intersection results could not be merged`; break; case ZodError_1.ZodIssueCode.not_multiple_of: message = `Number must be a multiple of ${issue.multipleOf}`; break; case ZodError_1.ZodIssueCode.not_finite: message = "Number must be finite"; break; default: message = _ctx.defaultError; util_1.util.assertNever(issue); } return { message }; }; exports.default = errorMap; } }); // node_modules/zod/lib/errors.js var require_errors = __commonJS({ "node_modules/zod/lib/errors.js"(exports) { "use strict"; var __importDefault = exports && exports.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.getErrorMap = exports.setErrorMap = exports.defaultErrorMap = void 0; var en_1 = __importDefault(require_en()); exports.defaultErrorMap = en_1.default; var overrideErrorMap = en_1.default; function setErrorMap(map2) { overrideErrorMap = map2; } exports.setErrorMap = setErrorMap; function getErrorMap() { return overrideErrorMap; } exports.getErrorMap = getErrorMap; } }); // node_modules/zod/lib/helpers/parseUtil.js var require_parseUtil = __commonJS({ "node_modules/zod/lib/helpers/parseUtil.js"(exports) { "use strict"; var __importDefault = exports && exports.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.isAsync = exports.isValid = exports.isDirty = exports.isAborted = exports.OK = exports.DIRTY = exports.INVALID = exports.ParseStatus = exports.addIssueToContext = exports.EMPTY_PATH = exports.makeIssue = void 0; var errors_1 = require_errors(); var en_1 = __importDefault(require_en()); var makeIssue = (params) => { const { data, path: path2, errorMaps, issueData } = params; const fullPath = [...path2, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath }; let errorMessage = ""; const maps = errorMaps.filter((m) => !!m).slice().reverse(); for (const map2 of maps) { errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message; } return { ...issueData, path: fullPath, message: issueData.message || errorMessage }; }; exports.makeIssue = makeIssue; exports.EMPTY_PATH = []; function addIssueToContext(ctx, issueData) { const issue = (0, exports.makeIssue)({ issueData, data: ctx.data, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_1.getErrorMap)(), en_1.default ].filter((x) => !!x) }); ctx.common.issues.push(issue); } exports.addIssueToContext = addIssueToContext; var ParseStatus = class { constructor() { this.value = "valid"; } dirty() { if (this.value === "valid") this.value = "dirty"; } abort() { if (this.value !== "aborted") this.value = "aborted"; } static mergeArray(status, results) { const arrayValue = []; for (const s of results) { if (s.status === "aborted") return exports.INVALID; if (s.status === "dirty") status.dirty(); arrayValue.push(s.value); } return { status: status.value, value: arrayValue }; } static async mergeObjectAsync(status, pairs2) { const syncPairs = []; for (const pair of pairs2) { syncPairs.push({ key: await pair.key, value: await pair.value }); } return ParseStatus.mergeObjectSync(status, syncPairs); } static mergeObjectSync(status, pairs2) { const finalObject = {}; for (const pair of pairs2) { const { key, value } = pair; if (key.status === "aborted") return exports.INVALID; if (value.status === "aborted") return exports.INVALID; if (key.status === "dirty") status.dirty(); if (value.status === "dirty") status.dirty(); if (typeof value.value !== "undefined" || pair.alwaysSet) { finalObject[key.value] = value.value; } } return { status: status.value, value: finalObject }; } }; exports.ParseStatus = ParseStatus; exports.INVALID = Object.freeze({ status: "aborted" }); var DIRTY = (value) => ({ status: "dirty", value }); exports.DIRTY = DIRTY; var OK = (value) => ({ status: "valid", value }); exports.OK = OK; var isAborted = (x) => x.status === "aborted"; exports.isAborted = isAborted; var isDirty = (x) => x.status === "dirty"; exports.isDirty = isDirty; var isValid = (x) => x.status === "valid"; exports.isValid = isValid; var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; exports.isAsync = isAsync; } }); // node_modules/zod/lib/helpers/typeAliases.js var require_typeAliases = __commonJS({ "node_modules/zod/lib/helpers/typeAliases.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); } }); // node_modules/zod/lib/helpers/errorUtil.js var require_errorUtil = __commonJS({ "node_modules/zod/lib/helpers/errorUtil.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.errorUtil = void 0; var errorUtil; (function(errorUtil2) { errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {}; errorUtil2.toString = (message) => typeof message === "string" ? message : message === null || message === void 0 ? void 0 : message.message; })(errorUtil = exports.errorUtil || (exports.errorUtil = {})); } }); // node_modules/zod/lib/types.js var require_types = __commonJS({ "node_modules/zod/lib/types.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.discriminatedUnion = exports.date = exports.boolean = exports.bigint = exports.array = exports.any = exports.coerce = exports.ZodFirstPartyTypeKind = exports.late = exports.ZodSchema = exports.Schema = exports.custom = exports.ZodPipeline = exports.ZodBranded = exports.BRAND = exports.ZodNaN = exports.ZodCatch = exports.ZodDefault = exports.ZodNullable = exports.ZodOptional = exports.ZodTransformer = exports.ZodEffects = exports.ZodPromise = exports.ZodNativeEnum = exports.ZodEnum = exports.ZodLiteral = exports.ZodLazy = exports.ZodFunction = exports.ZodSet = exports.ZodMap = exports.ZodRecord = exports.ZodTuple = exports.ZodIntersection = exports.ZodDiscriminatedUnion = exports.ZodUnion = exports.ZodObject = exports.ZodArray = exports.ZodVoid = exports.ZodNever = exports.ZodUnknown = exports.ZodAny = exports.ZodNull = exports.ZodUndefined = exports.ZodSymbol = exports.ZodDate = exports.ZodBoolean = exports.ZodBigInt = exports.ZodNumber = exports.ZodString = exports.ZodType = void 0; exports.NEVER = exports.void = exports.unknown = exports.union = exports.undefined = exports.tuple = exports.transformer = exports.symbol = exports.string = exports.strictObject = exports.set = exports.record = exports.promise = exports.preprocess = exports.pipeline = exports.ostring = exports.optional = exports.onumber = exports.oboolean = exports.object = exports.number = exports.nullable = exports.null = exports.never = exports.nativeEnum = exports.nan = exports.map = exports.literal = exports.lazy = exports.intersection = exports.instanceof = exports.function = exports.enum = exports.effect = void 0; var errors_1 = require_errors(); var errorUtil_1 = require_errorUtil(); var parseUtil_1 = require_parseUtil(); var util_1 = require_util(); var ZodError_1 = require_ZodError(); var ParseInputLazyPath = class { constructor(parent, value, path2, key) { this._cachedPath = []; this.parent = parent; this.data = value; this._path = path2; this._key = key; } get path() { if (!this._cachedPath.length) { if (this._key instanceof Array) { this._cachedPath.push(...this._path, ...this._key); } else { this._cachedPath.push(...this._path, this._key); } } return this._cachedPath; } }; var handleResult = (ctx, result) => { if ((0, parseUtil_1.isValid)(result)) { return { success: true, data: result.value }; } else { if (!ctx.common.issues.length) { throw new Error("Validation failed but no issues detected."); } return { success: false, get error() { if (this._error) return this._error; const error = new ZodError_1.ZodError(ctx.common.issues); this._error = error; return this._error; } }; } }; function processCreateParams(params) { if (!params) return {}; const { errorMap, invalid_type_error, required_error, description } = params; if (errorMap && (invalid_type_error || required_error)) { throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); } if (errorMap) return { errorMap, description }; const customMap = (iss, ctx) => { if (iss.code !== "invalid_type") return { message: ctx.defaultError }; if (typeof ctx.data === "undefined") { return { message: required_error !== null && required_error !== void 0 ? required_error : ctx.defaultError }; } return { message: invalid_type_error !== null && invalid_type_error !== void 0 ? invalid_type_error : ctx.defaultError }; }; return { errorMap: customMap, description }; } var ZodType = class { constructor(def) { this.spa = this.safeParseAsync; this._def = def; this.parse = this.parse.bind(this); this.safeParse = this.safeParse.bind(this); this.parseAsync = this.parseAsync.bind(this); this.safeParseAsync = this.safeParseAsync.bind(this); this.spa = this.spa.bind(this); this.refine = this.refine.bind(this); this.refinement = this.refinement.bind(this); this.superRefine = this.superRefine.bind(this); this.optional = this.optional.bind(this); this.nullable = this.nullable.bind(this); this.nullish = this.nullish.bind(this); this.array = this.array.bind(this); this.promise = this.promise.bind(this); this.or = this.or.bind(this); this.and = this.and.bind(this); this.transform = this.transform.bind(this); this.brand = this.brand.bind(this); this.default = this.default.bind(this); this.catch = this.catch.bind(this); this.describe = this.describe.bind(this); this.pipe = this.pipe.bind(this); this.isNullable = this.isNullable.bind(this); this.isOptional = this.isOptional.bind(this); } get description() { return this._def.description; } _getType(input) { return (0, util_1.getParsedType)(input.data); } _getOrReturnCtx(input, ctx) { return ctx || { common: input.parent.common, data: input.data, parsedType: (0, util_1.getParsedType)(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent }; } _processInputParams(input) { return { status: new parseUtil_1.ParseStatus(), ctx: { common: input.parent.common, data: input.data, parsedType: (0, util_1.getParsedType)(input.data), schemaErrorMap: this._def.errorMap, path: input.path, parent: input.parent } }; } _parseSync(input) { const result = this._parse(input); if ((0, parseUtil_1.isAsync)(result)) { throw new Error("Synchronous parse encountered promise."); } return result; } _parseAsync(input) { const result = this._parse(input); return Promise.resolve(result); } parse(data, params) { const result = this.safeParse(data, params); if (result.success) return result.data; throw result.error; } safeParse(data, params) { var _a; const ctx = { common: { issues: [], async: (_a = params === null || params === void 0 ? void 0 : params.async) !== null && _a !== void 0 ? _a : false, contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: (0, util_1.getParsedType)(data) }; const result = this._parseSync({ data, path: ctx.path, parent: ctx }); return handleResult(ctx, result); } async parseAsync(data, params) { const result = await this.safeParseAsync(data, params); if (result.success) return result.data; throw result.error; } async safeParseAsync(data, params) { const ctx = { common: { issues: [], contextualErrorMap: params === null || params === void 0 ? void 0 : params.errorMap, async: true }, path: (params === null || params === void 0 ? void 0 : params.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data, parsedType: (0, util_1.getParsedType)(data) }; const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); const result = await ((0, parseUtil_1.isAsync)(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); return handleResult(ctx, result); } refine(check, message) { const getIssueProperties = (val) => { if (typeof message === "string" || typeof message === "undefined") { return { message }; } else if (typeof message === "function") { return message(val); } else { return message; } }; return this._refinement((val, ctx) => { const result = check(val); const setError = () => ctx.addIssue({ code: ZodError_1.ZodIssueCode.custom, ...getIssueProperties(val) }); if (typeof Promise !== "undefined" && result instanceof Promise) { return result.then((data) => { if (!data) { setError(); return false; } else { return true; } }); } if (!result) { setError(); return false; } else { return true; } }); } refinement(check, refinementData) { return this._refinement((val, ctx) => { if (!check(val)) { ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); return false; } else { return true; } }); } _refinement(refinement) { return new ZodEffects({ schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "refinement", refinement } }); } superRefine(refinement) { return this._refinement(refinement); } optional() { return ZodOptional.create(this, this._def); } nullable() { return ZodNullable.create(this, this._def); } nullish() { return this.nullable().optional(); } array() { return ZodArray.create(this, this._def); } promise() { return ZodPromise.create(this, this._def); } or(option) { return ZodUnion.create([this, option], this._def); } and(incoming) { return ZodIntersection.create(this, incoming, this._def); } transform(transform) { return new ZodEffects({ ...processCreateParams(this._def), schema: this, typeName: ZodFirstPartyTypeKind.ZodEffects, effect: { type: "transform", transform } }); } default(def) { const defaultValueFunc = typeof def === "function" ? def : () => def; return new ZodDefault({ ...processCreateParams(this._def), innerType: this, defaultValue: defaultValueFunc, typeName: ZodFirstPartyTypeKind.ZodDefault }); } brand() { return new ZodBranded({ typeName: ZodFirstPartyTypeKind.ZodBranded, type: this, ...processCreateParams(this._def) }); } catch(def) { const catchValueFunc = typeof def === "function" ? def : () => def; return new ZodCatch({ ...processCreateParams(this._def), innerType: this, catchValue: catchValueFunc, typeName: ZodFirstPartyTypeKind.ZodCatch }); } describe(description) { const This = this.constructor; return new This({ ...this._def, description }); } pipe(target) { return ZodPipeline.create(this, target); } isOptional() { return this.safeParse(void 0).success; } isNullable() { return this.safeParse(null).success; } }; exports.ZodType = ZodType; exports.Schema = ZodType; exports.ZodSchema = ZodType; var cuidRegex = /^c[^\s-]{8,}$/i; var cuid2Regex = /^[a-z][a-z0-9]*$/; var ulidRegex = /[0-9A-HJKMNP-TV-Z]{26}/; var uuidRegex = /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; var emailRegex = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; var emojiRegex = /^(\p{Extended_Pictographic}|\p{Emoji_Component})+$/u; var ipv4Regex = /^(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))$/; var ipv6Regex = /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; var datetimeRegex = (args) => { if (args.precision) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{${args.precision}}Z$`); } } else if (args.precision === 0) { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}Z$`); } } else { if (args.offset) { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?(([+-]\\d{2}(:?\\d{2})?)|Z)$`); } else { return new RegExp(`^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d+)?Z$`); } } }; function isValidIP(ip, version2) { if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) { return true; } if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) { return true; } return false; } var ZodString = class extends ZodType { constructor() { super(...arguments); this._regex = (regex, validation, message) => this.refinement((data) => regex.test(data), { validation, code: ZodError_1.ZodIssueCode.invalid_string, ...errorUtil_1.errorUtil.errToObj(message) }); this.nonempty = (message) => this.min(1, errorUtil_1.errorUtil.errToObj(message)); this.trim = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] }); this.toLowerCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] }); this.toUpperCase = () => new ZodString({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] }); } _parse(input) { if (this._def.coerce) { input.data = String(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.string) { const ctx2 = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx2, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.string, received: ctx2.parsedType }); return parseUtil_1.INVALID; } const status = new parseUtil_1.ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.length < check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { if (input.data.length > check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "length") { const tooBig = input.data.length > check.value; const tooSmall = input.data.length < check.value; if (tooBig || tooSmall) { ctx = this._getOrReturnCtx(input, ctx); if (tooBig) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } else if (tooSmall) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: check.value, type: "string", inclusive: true, exact: true, message: check.message }); } status.dirty(); } } else if (check.kind === "email") { if (!emailRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "email", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "emoji") { if (!emojiRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "emoji", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "uuid") { if (!uuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "uuid", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid") { if (!cuidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "cuid", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "cuid2") { if (!cuid2Regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "cuid2", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "ulid") { if (!ulidRegex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "ulid", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "url") { try { new URL(input.data); } catch (_a) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "url", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "regex") { check.regex.lastIndex = 0; const testResult = check.regex.test(input.data); if (!testResult) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "regex", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else if (check.kind === "trim") { input.data = input.data.trim(); } else if (check.kind === "includes") { if (!input.data.includes(check.value, check.position)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: { includes: check.value, position: check.position }, message: check.message }); status.dirty(); } } else if (check.kind === "toLowerCase") { input.data = input.data.toLowerCase(); } else if (check.kind === "toUpperCase") { input.data = input.data.toUpperCase(); } else if (check.kind === "startsWith") { if (!input.data.startsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: { startsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "endsWith") { if (!input.data.endsWith(check.value)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: { endsWith: check.value }, message: check.message }); status.dirty(); } } else if (check.kind === "datetime") { const regex = datetimeRegex(check); if (!regex.test(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_string, validation: "datetime", message: check.message }); status.dirty(); } } else if (check.kind === "ip") { if (!isValidIP(input.data, check.version)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { validation: "ip", code: ZodError_1.ZodIssueCode.invalid_string, message: check.message }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: input.data }; } _addCheck(check) { return new ZodString({ ...this._def, checks: [...this._def.checks, check] }); } email(message) { return this._addCheck({ kind: "email", ...errorUtil_1.errorUtil.errToObj(message) }); } url(message) { return this._addCheck({ kind: "url", ...errorUtil_1.errorUtil.errToObj(message) }); } emoji(message) { return this._addCheck({ kind: "emoji", ...errorUtil_1.errorUtil.errToObj(message) }); } uuid(message) { return this._addCheck({ kind: "uuid", ...errorUtil_1.errorUtil.errToObj(message) }); } cuid(message) { return this._addCheck({ kind: "cuid", ...errorUtil_1.errorUtil.errToObj(message) }); } cuid2(message) { return this._addCheck({ kind: "cuid2", ...errorUtil_1.errorUtil.errToObj(message) }); } ulid(message) { return this._addCheck({ kind: "ulid", ...errorUtil_1.errorUtil.errToObj(message) }); } ip(options) { return this._addCheck({ kind: "ip", ...errorUtil_1.errorUtil.errToObj(options) }); } datetime(options) { var _a; if (typeof options === "string") { return this._addCheck({ kind: "datetime", precision: null, offset: false, message: options }); } return this._addCheck({ kind: "datetime", precision: typeof (options === null || options === void 0 ? void 0 : options.precision) === "undefined" ? null : options === null || options === void 0 ? void 0 : options.precision, offset: (_a = options === null || options === void 0 ? void 0 : options.offset) !== null && _a !== void 0 ? _a : false, ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } regex(regex, message) { return this._addCheck({ kind: "regex", regex, ...errorUtil_1.errorUtil.errToObj(message) }); } includes(value, options) { return this._addCheck({ kind: "includes", value, position: options === null || options === void 0 ? void 0 : options.position, ...errorUtil_1.errorUtil.errToObj(options === null || options === void 0 ? void 0 : options.message) }); } startsWith(value, message) { return this._addCheck({ kind: "startsWith", value, ...errorUtil_1.errorUtil.errToObj(message) }); } endsWith(value, message) { return this._addCheck({ kind: "endsWith", value, ...errorUtil_1.errorUtil.errToObj(message) }); } min(minLength, message) { return this._addCheck({ kind: "min", value: minLength, ...errorUtil_1.errorUtil.errToObj(message) }); } max(maxLength, message) { return this._addCheck({ kind: "max", value: maxLength, ...errorUtil_1.errorUtil.errToObj(message) }); } length(len, message) { return this._addCheck({ kind: "length", value: len, ...errorUtil_1.errorUtil.errToObj(message) }); } get isDatetime() { return !!this._def.checks.find((ch) => ch.kind === "datetime"); } get isEmail() { return !!this._def.checks.find((ch) => ch.kind === "email"); } get isURL() { return !!this._def.checks.find((ch) => ch.kind === "url"); } get isEmoji() { return !!this._def.checks.find((ch) => ch.kind === "emoji"); } get isUUID() { return !!this._def.checks.find((ch) => ch.kind === "uuid"); } get isCUID() { return !!this._def.checks.find((ch) => ch.kind === "cuid"); } get isCUID2() { return !!this._def.checks.find((ch) => ch.kind === "cuid2"); } get isULID() { return !!this._def.checks.find((ch) => ch.kind === "ulid"); } get isIP() { return !!this._def.checks.find((ch) => ch.kind === "ip"); } get minLength() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxLength() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; exports.ZodString = ZodString; ZodString.create = (params) => { var _a; return new ZodString({ checks: [], typeName: ZodFirstPartyTypeKind.ZodString, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params) }); }; function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepDecCount = (step.toString().split(".")[1] || "").length; const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = parseInt(step.toFixed(decCount).replace(".", "")); return valInt % stepInt / Math.pow(10, decCount); } var ZodNumber = class extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; this.step = this.multipleOf; } _parse(input) { if (this._def.coerce) { input.data = Number(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.number) { const ctx2 = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx2, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.number, received: ctx2.parsedType }); return parseUtil_1.INVALID; } let ctx = void 0; const status = new parseUtil_1.ParseStatus(); for (const check of this._def.checks) { if (check.kind === "int") { if (!util_1.util.isInteger(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: "integer", received: "float", message: check.message }); status.dirty(); } } else if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: check.value, type: "number", inclusive: check.inclusive, exact: false, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (floatSafeRemainder(input.data, check.value) !== 0) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else if (check.kind === "finite") { if (!Number.isFinite(input.data)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.not_finite, message: check.message }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodNumber({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil_1.errorUtil.toString(message) } ] }); } _addCheck(check) { return new ZodNumber({ ...this._def, checks: [...this._def.checks, check] }); } int(message) { return this._addCheck({ kind: "int", message: errorUtil_1.errorUtil.toString(message) }); } positive(message) { return this._addCheck({ kind: "min", value: 0, inclusive: false, message: errorUtil_1.errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: 0, inclusive: false, message: errorUtil_1.errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: 0, inclusive: true, message: errorUtil_1.errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: 0, inclusive: true, message: errorUtil_1.errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil_1.errorUtil.toString(message) }); } finite(message) { return this._addCheck({ kind: "finite", message: errorUtil_1.errorUtil.toString(message) }); } safe(message) { return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: errorUtil_1.errorUtil.toString(message) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: errorUtil_1.errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } get isInt() { return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util_1.util.isInteger(ch.value)); } get isFinite() { let max = null, min = null; for (const ch of this._def.checks) { if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { return true; } else if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } else if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return Number.isFinite(min) && Number.isFinite(max); } }; exports.ZodNumber = ZodNumber; ZodNumber.create = (params) => { return new ZodNumber({ checks: [], typeName: ZodFirstPartyTypeKind.ZodNumber, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; var ZodBigInt = class extends ZodType { constructor() { super(...arguments); this.min = this.gte; this.max = this.lte; } _parse(input) { if (this._def.coerce) { input.data = BigInt(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.bigint) { const ctx2 = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx2, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.bigint, received: ctx2.parsedType }); return parseUtil_1.INVALID; } let ctx = void 0; const status = new parseUtil_1.ParseStatus(); for (const check of this._def.checks) { if (check.kind === "min") { const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; if (tooSmall) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, type: "bigint", minimum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "max") { const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; if (tooBig) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, type: "bigint", maximum: check.value, inclusive: check.inclusive, message: check.message }); status.dirty(); } } else if (check.kind === "multipleOf") { if (input.data % check.value !== BigInt(0)) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.not_multiple_of, multipleOf: check.value, message: check.message }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: input.data }; } gte(value, message) { return this.setLimit("min", value, true, errorUtil_1.errorUtil.toString(message)); } gt(value, message) { return this.setLimit("min", value, false, errorUtil_1.errorUtil.toString(message)); } lte(value, message) { return this.setLimit("max", value, true, errorUtil_1.errorUtil.toString(message)); } lt(value, message) { return this.setLimit("max", value, false, errorUtil_1.errorUtil.toString(message)); } setLimit(kind, value, inclusive, message) { return new ZodBigInt({ ...this._def, checks: [ ...this._def.checks, { kind, value, inclusive, message: errorUtil_1.errorUtil.toString(message) } ] }); } _addCheck(check) { return new ZodBigInt({ ...this._def, checks: [...this._def.checks, check] }); } positive(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: errorUtil_1.errorUtil.toString(message) }); } negative(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: errorUtil_1.errorUtil.toString(message) }); } nonpositive(message) { return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: errorUtil_1.errorUtil.toString(message) }); } nonnegative(message) { return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: errorUtil_1.errorUtil.toString(message) }); } multipleOf(value, message) { return this._addCheck({ kind: "multipleOf", value, message: errorUtil_1.errorUtil.toString(message) }); } get minValue() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min; } get maxValue() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max; } }; exports.ZodBigInt = ZodBigInt; ZodBigInt.create = (params) => { var _a; return new ZodBigInt({ checks: [], typeName: ZodFirstPartyTypeKind.ZodBigInt, coerce: (_a = params === null || params === void 0 ? void 0 : params.coerce) !== null && _a !== void 0 ? _a : false, ...processCreateParams(params) }); }; var ZodBoolean = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = Boolean(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.boolean) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.boolean, received: ctx.parsedType }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } }; exports.ZodBoolean = ZodBoolean; ZodBoolean.create = (params) => { return new ZodBoolean({ typeName: ZodFirstPartyTypeKind.ZodBoolean, coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, ...processCreateParams(params) }); }; var ZodDate = class extends ZodType { _parse(input) { if (this._def.coerce) { input.data = new Date(input.data); } const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.date) { const ctx2 = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx2, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.date, received: ctx2.parsedType }); return parseUtil_1.INVALID; } if (isNaN(input.data.getTime())) { const ctx2 = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx2, { code: ZodError_1.ZodIssueCode.invalid_date }); return parseUtil_1.INVALID; } const status = new parseUtil_1.ParseStatus(); let ctx = void 0; for (const check of this._def.checks) { if (check.kind === "min") { if (input.data.getTime() < check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, message: check.message, inclusive: true, exact: false, minimum: check.value, type: "date" }); status.dirty(); } } else if (check.kind === "max") { if (input.data.getTime() > check.value) { ctx = this._getOrReturnCtx(input, ctx); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, message: check.message, inclusive: true, exact: false, maximum: check.value, type: "date" }); status.dirty(); } } else { util_1.util.assertNever(check); } } return { status: status.value, value: new Date(input.data.getTime()) }; } _addCheck(check) { return new ZodDate({ ...this._def, checks: [...this._def.checks, check] }); } min(minDate, message) { return this._addCheck({ kind: "min", value: minDate.getTime(), message: errorUtil_1.errorUtil.toString(message) }); } max(maxDate, message) { return this._addCheck({ kind: "max", value: maxDate.getTime(), message: errorUtil_1.errorUtil.toString(message) }); } get minDate() { let min = null; for (const ch of this._def.checks) { if (ch.kind === "min") { if (min === null || ch.value > min) min = ch.value; } } return min != null ? new Date(min) : null; } get maxDate() { let max = null; for (const ch of this._def.checks) { if (ch.kind === "max") { if (max === null || ch.value < max) max = ch.value; } } return max != null ? new Date(max) : null; } }; exports.ZodDate = ZodDate; ZodDate.create = (params) => { return new ZodDate({ checks: [], coerce: (params === null || params === void 0 ? void 0 : params.coerce) || false, typeName: ZodFirstPartyTypeKind.ZodDate, ...processCreateParams(params) }); }; var ZodSymbol = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.symbol) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.symbol, received: ctx.parsedType }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } }; exports.ZodSymbol = ZodSymbol; ZodSymbol.create = (params) => { return new ZodSymbol({ typeName: ZodFirstPartyTypeKind.ZodSymbol, ...processCreateParams(params) }); }; var ZodUndefined = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.undefined, received: ctx.parsedType }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } }; exports.ZodUndefined = ZodUndefined; ZodUndefined.create = (params) => { return new ZodUndefined({ typeName: ZodFirstPartyTypeKind.ZodUndefined, ...processCreateParams(params) }); }; var ZodNull = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.null) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.null, received: ctx.parsedType }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } }; exports.ZodNull = ZodNull; ZodNull.create = (params) => { return new ZodNull({ typeName: ZodFirstPartyTypeKind.ZodNull, ...processCreateParams(params) }); }; var ZodAny = class extends ZodType { constructor() { super(...arguments); this._any = true; } _parse(input) { return (0, parseUtil_1.OK)(input.data); } }; exports.ZodAny = ZodAny; ZodAny.create = (params) => { return new ZodAny({ typeName: ZodFirstPartyTypeKind.ZodAny, ...processCreateParams(params) }); }; var ZodUnknown = class extends ZodType { constructor() { super(...arguments); this._unknown = true; } _parse(input) { return (0, parseUtil_1.OK)(input.data); } }; exports.ZodUnknown = ZodUnknown; ZodUnknown.create = (params) => { return new ZodUnknown({ typeName: ZodFirstPartyTypeKind.ZodUnknown, ...processCreateParams(params) }); }; var ZodNever = class extends ZodType { _parse(input) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.never, received: ctx.parsedType }); return parseUtil_1.INVALID; } }; exports.ZodNever = ZodNever; ZodNever.create = (params) => { return new ZodNever({ typeName: ZodFirstPartyTypeKind.ZodNever, ...processCreateParams(params) }); }; var ZodVoid = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.undefined) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.void, received: ctx.parsedType }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } }; exports.ZodVoid = ZodVoid; ZodVoid.create = (params) => { return new ZodVoid({ typeName: ZodFirstPartyTypeKind.ZodVoid, ...processCreateParams(params) }); }; var ZodArray = class extends ZodType { _parse(input) { const { ctx, status } = this._processInputParams(input); const def = this._def; if (ctx.parsedType !== util_1.ZodParsedType.array) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.array, received: ctx.parsedType }); return parseUtil_1.INVALID; } if (def.exactLength !== null) { const tooBig = ctx.data.length > def.exactLength.value; const tooSmall = ctx.data.length < def.exactLength.value; if (tooBig || tooSmall) { (0, parseUtil_1.addIssueToContext)(ctx, { code: tooBig ? ZodError_1.ZodIssueCode.too_big : ZodError_1.ZodIssueCode.too_small, minimum: tooSmall ? def.exactLength.value : void 0, maximum: tooBig ? def.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: def.exactLength.message }); status.dirty(); } } if (def.minLength !== null) { if (ctx.data.length < def.minLength.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: def.minLength.value, type: "array", inclusive: true, exact: false, message: def.minLength.message }); status.dirty(); } } if (def.maxLength !== null) { if (ctx.data.length > def.maxLength.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: def.maxLength.value, type: "array", inclusive: true, exact: false, message: def.maxLength.message }); status.dirty(); } } if (ctx.common.async) { return Promise.all([...ctx.data].map((item, i) => { return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); })).then((result2) => { return parseUtil_1.ParseStatus.mergeArray(status, result2); }); } const result = [...ctx.data].map((item, i) => { return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); }); return parseUtil_1.ParseStatus.mergeArray(status, result); } get element() { return this._def.type; } min(minLength, message) { return new ZodArray({ ...this._def, minLength: { value: minLength, message: errorUtil_1.errorUtil.toString(message) } }); } max(maxLength, message) { return new ZodArray({ ...this._def, maxLength: { value: maxLength, message: errorUtil_1.errorUtil.toString(message) } }); } length(len, message) { return new ZodArray({ ...this._def, exactLength: { value: len, message: errorUtil_1.errorUtil.toString(message) } }); } nonempty(message) { return this.min(1, message); } }; exports.ZodArray = ZodArray; ZodArray.create = (schema2, params) => { return new ZodArray({ type: schema2, minLength: null, maxLength: null, exactLength: null, typeName: ZodFirstPartyTypeKind.ZodArray, ...processCreateParams(params) }); }; function deepPartialify(schema2) { if (schema2 instanceof ZodObject) { const newShape = {}; for (const key in schema2.shape) { const fieldSchema = schema2.shape[key]; newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); } return new ZodObject({ ...schema2._def, shape: () => newShape }); } else if (schema2 instanceof ZodArray) { return new ZodArray({ ...schema2._def, type: deepPartialify(schema2.element) }); } else if (schema2 instanceof ZodOptional) { return ZodOptional.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodNullable) { return ZodNullable.create(deepPartialify(schema2.unwrap())); } else if (schema2 instanceof ZodTuple) { return ZodTuple.create(schema2.items.map((item) => deepPartialify(item))); } else { return schema2; } } var ZodObject = class extends ZodType { constructor() { super(...arguments); this._cached = null; this.nonstrict = this.passthrough; this.augment = this.extend; } _getCached() { if (this._cached !== null) return this._cached; const shape = this._def.shape(); const keys3 = util_1.util.objectKeys(shape); return this._cached = { shape, keys: keys3 }; } _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.object) { const ctx2 = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx2, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.object, received: ctx2.parsedType }); return parseUtil_1.INVALID; } const { status, ctx } = this._processInputParams(input); const { shape, keys: shapeKeys } = this._getCached(); const extraKeys = []; if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { for (const key in ctx.data) { if (!shapeKeys.includes(key)) { extraKeys.push(key); } } } const pairs2 = []; for (const key of shapeKeys) { const keyValidator = shape[key]; const value = ctx.data[key]; pairs2.push({ key: { status: "valid", value: key }, value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } if (this._def.catchall instanceof ZodNever) { const unknownKeys = this._def.unknownKeys; if (unknownKeys === "passthrough") { for (const key of extraKeys) { pairs2.push({ key: { status: "valid", value: key }, value: { status: "valid", value: ctx.data[key] } }); } } else if (unknownKeys === "strict") { if (extraKeys.length > 0) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.unrecognized_keys, keys: extraKeys }); status.dirty(); } } else if (unknownKeys === "strip") { } else { throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); } } else { const catchall = this._def.catchall; for (const key of extraKeys) { const value = ctx.data[key]; pairs2.push({ key: { status: "valid", value: key }, value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), alwaysSet: key in ctx.data }); } } if (ctx.common.async) { return Promise.resolve().then(async () => { const syncPairs = []; for (const pair of pairs2) { const key = await pair.key; syncPairs.push({ key, value: await pair.value, alwaysSet: pair.alwaysSet }); } return syncPairs; }).then((syncPairs) => { return parseUtil_1.ParseStatus.mergeObjectSync(status, syncPairs); }); } else { return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs2); } } get shape() { return this._def.shape(); } strict(message) { errorUtil_1.errorUtil.errToObj; return new ZodObject({ ...this._def, unknownKeys: "strict", ...message !== void 0 ? { errorMap: (issue, ctx) => { var _a, _b, _c, _d; const defaultError = (_c = (_b = (_a = this._def).errorMap) === null || _b === void 0 ? void 0 : _b.call(_a, issue, ctx).message) !== null && _c !== void 0 ? _c : ctx.defaultError; if (issue.code === "unrecognized_keys") return { message: (_d = errorUtil_1.errorUtil.errToObj(message).message) !== null && _d !== void 0 ? _d : defaultError }; return { message: defaultError }; } } : {} }); } strip() { return new ZodObject({ ...this._def, unknownKeys: "strip" }); } passthrough() { return new ZodObject({ ...this._def, unknownKeys: "passthrough" }); } extend(augmentation) { return new ZodObject({ ...this._def, shape: () => ({ ...this._def.shape(), ...augmentation }) }); } merge(merging) { const merged = new ZodObject({ unknownKeys: merging._def.unknownKeys, catchall: merging._def.catchall, shape: () => ({ ...this._def.shape(), ...merging._def.shape() }), typeName: ZodFirstPartyTypeKind.ZodObject }); return merged; } setKey(key, schema2) { return this.augment({ [key]: schema2 }); } catchall(index2) { return new ZodObject({ ...this._def, catchall: index2 }); } pick(mask) { const shape = {}; util_1.util.objectKeys(mask).forEach((key) => { if (mask[key] && this.shape[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } omit(mask) { const shape = {}; util_1.util.objectKeys(this.shape).forEach((key) => { if (!mask[key]) { shape[key] = this.shape[key]; } }); return new ZodObject({ ...this._def, shape: () => shape }); } deepPartial() { return deepPartialify(this); } partial(mask) { const newShape = {}; util_1.util.objectKeys(this.shape).forEach((key) => { const fieldSchema = this.shape[key]; if (mask && !mask[key]) { newShape[key] = fieldSchema; } else { newShape[key] = fieldSchema.optional(); } }); return new ZodObject({ ...this._def, shape: () => newShape }); } required(mask) { const newShape = {}; util_1.util.objectKeys(this.shape).forEach((key) => { if (mask && !mask[key]) { newShape[key] = this.shape[key]; } else { const fieldSchema = this.shape[key]; let newField = fieldSchema; while (newField instanceof ZodOptional) { newField = newField._def.innerType; } newShape[key] = newField; } }); return new ZodObject({ ...this._def, shape: () => newShape }); } keyof() { return createZodEnum(util_1.util.objectKeys(this.shape)); } }; exports.ZodObject = ZodObject; ZodObject.create = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.strictCreate = (shape, params) => { return new ZodObject({ shape: () => shape, unknownKeys: "strict", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; ZodObject.lazycreate = (shape, params) => { return new ZodObject({ shape, unknownKeys: "strip", catchall: ZodNever.create(), typeName: ZodFirstPartyTypeKind.ZodObject, ...processCreateParams(params) }); }; var ZodUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const options = this._def.options; function handleResults(results) { for (const result of results) { if (result.result.status === "valid") { return result.result; } } for (const result of results) { if (result.result.status === "dirty") { ctx.common.issues.push(...result.ctx.common.issues); return result.result; } } const unionErrors = results.map((result) => new ZodError_1.ZodError(result.ctx.common.issues)); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_union, unionErrors }); return parseUtil_1.INVALID; } if (ctx.common.async) { return Promise.all(options.map(async (option) => { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; return { result: await option._parseAsync({ data: ctx.data, path: ctx.path, parent: childCtx }), ctx: childCtx }; })).then(handleResults); } else { let dirty = void 0; const issues = []; for (const option of options) { const childCtx = { ...ctx, common: { ...ctx.common, issues: [] }, parent: null }; const result = option._parseSync({ data: ctx.data, path: ctx.path, parent: childCtx }); if (result.status === "valid") { return result; } else if (result.status === "dirty" && !dirty) { dirty = { result, ctx: childCtx }; } if (childCtx.common.issues.length) { issues.push(childCtx.common.issues); } } if (dirty) { ctx.common.issues.push(...dirty.ctx.common.issues); return dirty.result; } const unionErrors = issues.map((issues2) => new ZodError_1.ZodError(issues2)); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_union, unionErrors }); return parseUtil_1.INVALID; } } get options() { return this._def.options; } }; exports.ZodUnion = ZodUnion; ZodUnion.create = (types, params) => { return new ZodUnion({ options: types, typeName: ZodFirstPartyTypeKind.ZodUnion, ...processCreateParams(params) }); }; var getDiscriminator = (type2) => { if (type2 instanceof ZodLazy) { return getDiscriminator(type2.schema); } else if (type2 instanceof ZodEffects) { return getDiscriminator(type2.innerType()); } else if (type2 instanceof ZodLiteral) { return [type2.value]; } else if (type2 instanceof ZodEnum) { return type2.options; } else if (type2 instanceof ZodNativeEnum) { return Object.keys(type2.enum); } else if (type2 instanceof ZodDefault) { return getDiscriminator(type2._def.innerType); } else if (type2 instanceof ZodUndefined) { return [void 0]; } else if (type2 instanceof ZodNull) { return [null]; } else { return null; } }; var ZodDiscriminatedUnion = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.object) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.object, received: ctx.parsedType }); return parseUtil_1.INVALID; } const discriminator = this.discriminator; const discriminatorValue = ctx.data[discriminator]; const option = this.optionsMap.get(discriminatorValue); if (!option) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [discriminator] }); return parseUtil_1.INVALID; } if (ctx.common.async) { return option._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); } else { return option._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); } } get discriminator() { return this._def.discriminator; } get options() { return this._def.options; } get optionsMap() { return this._def.optionsMap; } static create(discriminator, options, params) { const optionsMap = /* @__PURE__ */ new Map(); for (const type2 of options) { const discriminatorValues = getDiscriminator(type2.shape[discriminator]); if (!discriminatorValues) { throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); } for (const value of discriminatorValues) { if (optionsMap.has(value)) { throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); } optionsMap.set(value, type2); } } return new ZodDiscriminatedUnion({ typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, discriminator, options, optionsMap, ...processCreateParams(params) }); } }; exports.ZodDiscriminatedUnion = ZodDiscriminatedUnion; function mergeValues(a2, b) { const aType = (0, util_1.getParsedType)(a2); const bType = (0, util_1.getParsedType)(b); if (a2 === b) { return { valid: true, data: a2 }; } else if (aType === util_1.ZodParsedType.object && bType === util_1.ZodParsedType.object) { const bKeys = util_1.util.objectKeys(b); const sharedKeys = util_1.util.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1); const newObj = { ...a2, ...b }; for (const key of sharedKeys) { const sharedValue = mergeValues(a2[key], b[key]); if (!sharedValue.valid) { return { valid: false }; } newObj[key] = sharedValue.data; } return { valid: true, data: newObj }; } else if (aType === util_1.ZodParsedType.array && bType === util_1.ZodParsedType.array) { if (a2.length !== b.length) { return { valid: false }; } const newArray = []; for (let index2 = 0; index2 < a2.length; index2++) { const itemA = a2[index2]; const itemB = b[index2]; const sharedValue = mergeValues(itemA, itemB); if (!sharedValue.valid) { return { valid: false }; } newArray.push(sharedValue.data); } return { valid: true, data: newArray }; } else if (aType === util_1.ZodParsedType.date && bType === util_1.ZodParsedType.date && +a2 === +b) { return { valid: true, data: a2 }; } else { return { valid: false }; } } var ZodIntersection = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); const handleParsed = (parsedLeft, parsedRight) => { if ((0, parseUtil_1.isAborted)(parsedLeft) || (0, parseUtil_1.isAborted)(parsedRight)) { return parseUtil_1.INVALID; } const merged = mergeValues(parsedLeft.value, parsedRight.value); if (!merged.valid) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_intersection_types }); return parseUtil_1.INVALID; } if ((0, parseUtil_1.isDirty)(parsedLeft) || (0, parseUtil_1.isDirty)(parsedRight)) { status.dirty(); } return { status: status.value, value: merged.data }; }; if (ctx.common.async) { return Promise.all([ this._def.left._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }) ]).then(([left, right]) => handleParsed(left, right)); } else { return handleParsed(this._def.left._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }), this._def.right._parseSync({ data: ctx.data, path: ctx.path, parent: ctx })); } } }; exports.ZodIntersection = ZodIntersection; ZodIntersection.create = (left, right, params) => { return new ZodIntersection({ left, right, typeName: ZodFirstPartyTypeKind.ZodIntersection, ...processCreateParams(params) }); }; var ZodTuple = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.array) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.array, received: ctx.parsedType }); return parseUtil_1.INVALID; } if (ctx.data.length < this._def.items.length) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }); return parseUtil_1.INVALID; } const rest = this._def.rest; if (!rest && ctx.data.length > this._def.items.length) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }); status.dirty(); } const items = [...ctx.data].map((item, itemIndex) => { const schema2 = this._def.items[itemIndex] || this._def.rest; if (!schema2) return null; return schema2._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); }).filter((x) => !!x); if (ctx.common.async) { return Promise.all(items).then((results) => { return parseUtil_1.ParseStatus.mergeArray(status, results); }); } else { return parseUtil_1.ParseStatus.mergeArray(status, items); } } get items() { return this._def.items; } rest(rest) { return new ZodTuple({ ...this._def, rest }); } }; exports.ZodTuple = ZodTuple; ZodTuple.create = (schemas, params) => { if (!Array.isArray(schemas)) { throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); } return new ZodTuple({ items: schemas, typeName: ZodFirstPartyTypeKind.ZodTuple, rest: null, ...processCreateParams(params) }); }; var ZodRecord = class extends ZodType { get keySchema() { return this._def.keyType; } get valueSchema() { return this._def.valueType; } _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.object) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.object, received: ctx.parsedType }); return parseUtil_1.INVALID; } const pairs2 = []; const keyType = this._def.keyType; const valueType = this._def.valueType; for (const key in ctx.data) { pairs2.push({ key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)) }); } if (ctx.common.async) { return parseUtil_1.ParseStatus.mergeObjectAsync(status, pairs2); } else { return parseUtil_1.ParseStatus.mergeObjectSync(status, pairs2); } } get element() { return this._def.valueType; } static create(first, second, third) { if (second instanceof ZodType) { return new ZodRecord({ keyType: first, valueType: second, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(third) }); } return new ZodRecord({ keyType: ZodString.create(), valueType: first, typeName: ZodFirstPartyTypeKind.ZodRecord, ...processCreateParams(second) }); } }; exports.ZodRecord = ZodRecord; var ZodMap = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.map) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.map, received: ctx.parsedType }); return parseUtil_1.INVALID; } const keyType = this._def.keyType; const valueType = this._def.valueType; const pairs2 = [...ctx.data.entries()].map(([key, value], index2) => { return { key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index2, "key"])), value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index2, "value"])) }; }); if (ctx.common.async) { const finalMap = /* @__PURE__ */ new Map(); return Promise.resolve().then(async () => { for (const pair of pairs2) { const key = await pair.key; const value = await pair.value; if (key.status === "aborted" || value.status === "aborted") { return parseUtil_1.INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; }); } else { const finalMap = /* @__PURE__ */ new Map(); for (const pair of pairs2) { const key = pair.key; const value = pair.value; if (key.status === "aborted" || value.status === "aborted") { return parseUtil_1.INVALID; } if (key.status === "dirty" || value.status === "dirty") { status.dirty(); } finalMap.set(key.value, value.value); } return { status: status.value, value: finalMap }; } } }; exports.ZodMap = ZodMap; ZodMap.create = (keyType, valueType, params) => { return new ZodMap({ valueType, keyType, typeName: ZodFirstPartyTypeKind.ZodMap, ...processCreateParams(params) }); }; var ZodSet = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.set) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.set, received: ctx.parsedType }); return parseUtil_1.INVALID; } const def = this._def; if (def.minSize !== null) { if (ctx.data.size < def.minSize.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_small, minimum: def.minSize.value, type: "set", inclusive: true, exact: false, message: def.minSize.message }); status.dirty(); } } if (def.maxSize !== null) { if (ctx.data.size > def.maxSize.value) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.too_big, maximum: def.maxSize.value, type: "set", inclusive: true, exact: false, message: def.maxSize.message }); status.dirty(); } } const valueType = this._def.valueType; function finalizeSet(elements2) { const parsedSet = /* @__PURE__ */ new Set(); for (const element2 of elements2) { if (element2.status === "aborted") return parseUtil_1.INVALID; if (element2.status === "dirty") status.dirty(); parsedSet.add(element2.value); } return { status: status.value, value: parsedSet }; } const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); if (ctx.common.async) { return Promise.all(elements).then((elements2) => finalizeSet(elements2)); } else { return finalizeSet(elements); } } min(minSize, message) { return new ZodSet({ ...this._def, minSize: { value: minSize, message: errorUtil_1.errorUtil.toString(message) } }); } max(maxSize, message) { return new ZodSet({ ...this._def, maxSize: { value: maxSize, message: errorUtil_1.errorUtil.toString(message) } }); } size(size, message) { return this.min(size, message).max(size, message); } nonempty(message) { return this.min(1, message); } }; exports.ZodSet = ZodSet; ZodSet.create = (valueType, params) => { return new ZodSet({ valueType, minSize: null, maxSize: null, typeName: ZodFirstPartyTypeKind.ZodSet, ...processCreateParams(params) }); }; var ZodFunction = class extends ZodType { constructor() { super(...arguments); this.validate = this.implement; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.function) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.function, received: ctx.parsedType }); return parseUtil_1.INVALID; } function makeArgsIssue(args, error) { return (0, parseUtil_1.makeIssue)({ data: args, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_1.getErrorMap)(), errors_1.defaultErrorMap ].filter((x) => !!x), issueData: { code: ZodError_1.ZodIssueCode.invalid_arguments, argumentsError: error } }); } function makeReturnsIssue(returns, error) { return (0, parseUtil_1.makeIssue)({ data: returns, path: ctx.path, errorMaps: [ ctx.common.contextualErrorMap, ctx.schemaErrorMap, (0, errors_1.getErrorMap)(), errors_1.defaultErrorMap ].filter((x) => !!x), issueData: { code: ZodError_1.ZodIssueCode.invalid_return_type, returnTypeError: error } }); } const params = { errorMap: ctx.common.contextualErrorMap }; const fn = ctx.data; if (this._def.returns instanceof ZodPromise) { return (0, parseUtil_1.OK)(async (...args) => { const error = new ZodError_1.ZodError([]); const parsedArgs = await this._def.args.parseAsync(args, params).catch((e) => { error.addIssue(makeArgsIssue(args, e)); throw error; }); const result = await fn(...parsedArgs); const parsedReturns = await this._def.returns._def.type.parseAsync(result, params).catch((e) => { error.addIssue(makeReturnsIssue(result, e)); throw error; }); return parsedReturns; }); } else { return (0, parseUtil_1.OK)((...args) => { const parsedArgs = this._def.args.safeParse(args, params); if (!parsedArgs.success) { throw new ZodError_1.ZodError([makeArgsIssue(args, parsedArgs.error)]); } const result = fn(...parsedArgs.data); const parsedReturns = this._def.returns.safeParse(result, params); if (!parsedReturns.success) { throw new ZodError_1.ZodError([makeReturnsIssue(result, parsedReturns.error)]); } return parsedReturns.data; }); } } parameters() { return this._def.args; } returnType() { return this._def.returns; } args(...items) { return new ZodFunction({ ...this._def, args: ZodTuple.create(items).rest(ZodUnknown.create()) }); } returns(returnType) { return new ZodFunction({ ...this._def, returns: returnType }); } implement(func) { const validatedFunc = this.parse(func); return validatedFunc; } strictImplement(func) { const validatedFunc = this.parse(func); return validatedFunc; } static create(args, returns, params) { return new ZodFunction({ args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()), returns: returns || ZodUnknown.create(), typeName: ZodFirstPartyTypeKind.ZodFunction, ...processCreateParams(params) }); } }; exports.ZodFunction = ZodFunction; var ZodLazy = class extends ZodType { get schema() { return this._def.getter(); } _parse(input) { const { ctx } = this._processInputParams(input); const lazySchema = this._def.getter(); return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); } }; exports.ZodLazy = ZodLazy; ZodLazy.create = (getter, params) => { return new ZodLazy({ getter, typeName: ZodFirstPartyTypeKind.ZodLazy, ...processCreateParams(params) }); }; var ZodLiteral = class extends ZodType { _parse(input) { if (input.data !== this._def.value) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { received: ctx.data, code: ZodError_1.ZodIssueCode.invalid_literal, expected: this._def.value }); return parseUtil_1.INVALID; } return { status: "valid", value: input.data }; } get value() { return this._def.value; } }; exports.ZodLiteral = ZodLiteral; ZodLiteral.create = (value, params) => { return new ZodLiteral({ value, typeName: ZodFirstPartyTypeKind.ZodLiteral, ...processCreateParams(params) }); }; function createZodEnum(values, params) { return new ZodEnum({ values, typeName: ZodFirstPartyTypeKind.ZodEnum, ...processCreateParams(params) }); } var ZodEnum = class extends ZodType { _parse(input) { if (typeof input.data !== "string") { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; (0, parseUtil_1.addIssueToContext)(ctx, { expected: util_1.util.joinValues(expectedValues), received: ctx.parsedType, code: ZodError_1.ZodIssueCode.invalid_type }); return parseUtil_1.INVALID; } if (this._def.values.indexOf(input.data) === -1) { const ctx = this._getOrReturnCtx(input); const expectedValues = this._def.values; (0, parseUtil_1.addIssueToContext)(ctx, { received: ctx.data, code: ZodError_1.ZodIssueCode.invalid_enum_value, options: expectedValues }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } get options() { return this._def.values; } get enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Values() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } get Enum() { const enumValues = {}; for (const val of this._def.values) { enumValues[val] = val; } return enumValues; } extract(values) { return ZodEnum.create(values); } exclude(values) { return ZodEnum.create(this.options.filter((opt) => !values.includes(opt))); } }; exports.ZodEnum = ZodEnum; ZodEnum.create = createZodEnum; var ZodNativeEnum = class extends ZodType { _parse(input) { const nativeEnumValues = util_1.util.getValidEnumValues(this._def.values); const ctx = this._getOrReturnCtx(input); if (ctx.parsedType !== util_1.ZodParsedType.string && ctx.parsedType !== util_1.ZodParsedType.number) { const expectedValues = util_1.util.objectValues(nativeEnumValues); (0, parseUtil_1.addIssueToContext)(ctx, { expected: util_1.util.joinValues(expectedValues), received: ctx.parsedType, code: ZodError_1.ZodIssueCode.invalid_type }); return parseUtil_1.INVALID; } if (nativeEnumValues.indexOf(input.data) === -1) { const expectedValues = util_1.util.objectValues(nativeEnumValues); (0, parseUtil_1.addIssueToContext)(ctx, { received: ctx.data, code: ZodError_1.ZodIssueCode.invalid_enum_value, options: expectedValues }); return parseUtil_1.INVALID; } return (0, parseUtil_1.OK)(input.data); } get enum() { return this._def.values; } }; exports.ZodNativeEnum = ZodNativeEnum; ZodNativeEnum.create = (values, params) => { return new ZodNativeEnum({ values, typeName: ZodFirstPartyTypeKind.ZodNativeEnum, ...processCreateParams(params) }); }; var ZodPromise = class extends ZodType { unwrap() { return this._def.type; } _parse(input) { const { ctx } = this._processInputParams(input); if (ctx.parsedType !== util_1.ZodParsedType.promise && ctx.common.async === false) { (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.promise, received: ctx.parsedType }); return parseUtil_1.INVALID; } const promisified = ctx.parsedType === util_1.ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); return (0, parseUtil_1.OK)(promisified.then((data) => { return this._def.type.parseAsync(data, { path: ctx.path, errorMap: ctx.common.contextualErrorMap }); })); } }; exports.ZodPromise = ZodPromise; ZodPromise.create = (schema2, params) => { return new ZodPromise({ type: schema2, typeName: ZodFirstPartyTypeKind.ZodPromise, ...processCreateParams(params) }); }; var ZodEffects = class extends ZodType { innerType() { return this._def.schema; } sourceType() { return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema; } _parse(input) { const { status, ctx } = this._processInputParams(input); const effect = this._def.effect || null; if (effect.type === "preprocess") { const processed = effect.transform(ctx.data); if (ctx.common.async) { return Promise.resolve(processed).then((processed2) => { return this._def.schema._parseAsync({ data: processed2, path: ctx.path, parent: ctx }); }); } else { return this._def.schema._parseSync({ data: processed, path: ctx.path, parent: ctx }); } } const checkCtx = { addIssue: (arg) => { (0, parseUtil_1.addIssueToContext)(ctx, arg); if (arg.fatal) { status.abort(); } else { status.dirty(); } }, get path() { return ctx.path; } }; checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); if (effect.type === "refinement") { const executeRefinement = (acc) => { const result = effect.refinement(acc, checkCtx); if (ctx.common.async) { return Promise.resolve(result); } if (result instanceof Promise) { throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); } return acc; }; if (ctx.common.async === false) { const inner = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inner.status === "aborted") return parseUtil_1.INVALID; if (inner.status === "dirty") status.dirty(); executeRefinement(inner.value); return { status: status.value, value: inner.value }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { if (inner.status === "aborted") return parseUtil_1.INVALID; if (inner.status === "dirty") status.dirty(); return executeRefinement(inner.value).then(() => { return { status: status.value, value: inner.value }; }); }); } } if (effect.type === "transform") { if (ctx.common.async === false) { const base2 = this._def.schema._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (!(0, parseUtil_1.isValid)(base2)) return base2; const result = effect.transform(base2.value, checkCtx); if (result instanceof Promise) { throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); } return { status: status.value, value: result }; } else { return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base2) => { if (!(0, parseUtil_1.isValid)(base2)) return base2; return Promise.resolve(effect.transform(base2.value, checkCtx)).then((result) => ({ status: status.value, value: result })); }); } } util_1.util.assertNever(effect); } }; exports.ZodEffects = ZodEffects; exports.ZodTransformer = ZodEffects; ZodEffects.create = (schema2, effect, params) => { return new ZodEffects({ schema: schema2, typeName: ZodFirstPartyTypeKind.ZodEffects, effect, ...processCreateParams(params) }); }; ZodEffects.createWithPreprocess = (preprocess2, schema2, params) => { return new ZodEffects({ schema: schema2, effect: { type: "preprocess", transform: preprocess2 }, typeName: ZodFirstPartyTypeKind.ZodEffects, ...processCreateParams(params) }); }; var ZodOptional = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === util_1.ZodParsedType.undefined) { return (0, parseUtil_1.OK)(void 0); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; exports.ZodOptional = ZodOptional; ZodOptional.create = (type2, params) => { return new ZodOptional({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodOptional, ...processCreateParams(params) }); }; var ZodNullable = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType === util_1.ZodParsedType.null) { return (0, parseUtil_1.OK)(null); } return this._def.innerType._parse(input); } unwrap() { return this._def.innerType; } }; exports.ZodNullable = ZodNullable; ZodNullable.create = (type2, params) => { return new ZodNullable({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodNullable, ...processCreateParams(params) }); }; var ZodDefault = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); let data = ctx.data; if (ctx.parsedType === util_1.ZodParsedType.undefined) { data = this._def.defaultValue(); } return this._def.innerType._parse({ data, path: ctx.path, parent: ctx }); } removeDefault() { return this._def.innerType; } }; exports.ZodDefault = ZodDefault; ZodDefault.create = (type2, params) => { return new ZodDefault({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodDefault, defaultValue: typeof params.default === "function" ? params.default : () => params.default, ...processCreateParams(params) }); }; var ZodCatch = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const newCtx = { ...ctx, common: { ...ctx.common, issues: [] } }; const result = this._def.innerType._parse({ data: newCtx.data, path: newCtx.path, parent: { ...newCtx } }); if ((0, parseUtil_1.isAsync)(result)) { return result.then((result2) => { return { status: "valid", value: result2.status === "valid" ? result2.value : this._def.catchValue({ get error() { return new ZodError_1.ZodError(newCtx.common.issues); }, input: newCtx.data }) }; }); } else { return { status: "valid", value: result.status === "valid" ? result.value : this._def.catchValue({ get error() { return new ZodError_1.ZodError(newCtx.common.issues); }, input: newCtx.data }) }; } } removeCatch() { return this._def.innerType; } }; exports.ZodCatch = ZodCatch; ZodCatch.create = (type2, params) => { return new ZodCatch({ innerType: type2, typeName: ZodFirstPartyTypeKind.ZodCatch, catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, ...processCreateParams(params) }); }; var ZodNaN = class extends ZodType { _parse(input) { const parsedType = this._getType(input); if (parsedType !== util_1.ZodParsedType.nan) { const ctx = this._getOrReturnCtx(input); (0, parseUtil_1.addIssueToContext)(ctx, { code: ZodError_1.ZodIssueCode.invalid_type, expected: util_1.ZodParsedType.nan, received: ctx.parsedType }); return parseUtil_1.INVALID; } return { status: "valid", value: input.data }; } }; exports.ZodNaN = ZodNaN; ZodNaN.create = (params) => { return new ZodNaN({ typeName: ZodFirstPartyTypeKind.ZodNaN, ...processCreateParams(params) }); }; exports.BRAND = Symbol("zod_brand"); var ZodBranded = class extends ZodType { _parse(input) { const { ctx } = this._processInputParams(input); const data = ctx.data; return this._def.type._parse({ data, path: ctx.path, parent: ctx }); } unwrap() { return this._def.type; } }; exports.ZodBranded = ZodBranded; var ZodPipeline = class extends ZodType { _parse(input) { const { status, ctx } = this._processInputParams(input); if (ctx.common.async) { const handleAsync = async () => { const inResult = await this._def.in._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return parseUtil_1.INVALID; if (inResult.status === "dirty") { status.dirty(); return (0, parseUtil_1.DIRTY)(inResult.value); } else { return this._def.out._parseAsync({ data: inResult.value, path: ctx.path, parent: ctx }); } }; return handleAsync(); } else { const inResult = this._def.in._parseSync({ data: ctx.data, path: ctx.path, parent: ctx }); if (inResult.status === "aborted") return parseUtil_1.INVALID; if (inResult.status === "dirty") { status.dirty(); return { status: "dirty", value: inResult.value }; } else { return this._def.out._parseSync({ data: inResult.value, path: ctx.path, parent: ctx }); } } } static create(a2, b) { return new ZodPipeline({ in: a2, out: b, typeName: ZodFirstPartyTypeKind.ZodPipeline }); } }; exports.ZodPipeline = ZodPipeline; var custom = (check, params = {}, fatal) => { if (check) return ZodAny.create().superRefine((data, ctx) => { var _a, _b; if (!check(data)) { const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; const _fatal = (_b = (_a = p.fatal) !== null && _a !== void 0 ? _a : fatal) !== null && _b !== void 0 ? _b : true; const p2 = typeof p === "string" ? { message: p } : p; ctx.addIssue({ code: "custom", ...p2, fatal: _fatal }); } }); return ZodAny.create(); }; exports.custom = custom; exports.late = { object: ZodObject.lazycreate }; var ZodFirstPartyTypeKind; (function(ZodFirstPartyTypeKind2) { ZodFirstPartyTypeKind2["ZodString"] = "ZodString"; ZodFirstPartyTypeKind2["ZodNumber"] = "ZodNumber"; ZodFirstPartyTypeKind2["ZodNaN"] = "ZodNaN"; ZodFirstPartyTypeKind2["ZodBigInt"] = "ZodBigInt"; ZodFirstPartyTypeKind2["ZodBoolean"] = "ZodBoolean"; ZodFirstPartyTypeKind2["ZodDate"] = "ZodDate"; ZodFirstPartyTypeKind2["ZodSymbol"] = "ZodSymbol"; ZodFirstPartyTypeKind2["ZodUndefined"] = "ZodUndefined"; ZodFirstPartyTypeKind2["ZodNull"] = "ZodNull"; ZodFirstPartyTypeKind2["ZodAny"] = "ZodAny"; ZodFirstPartyTypeKind2["ZodUnknown"] = "ZodUnknown"; ZodFirstPartyTypeKind2["ZodNever"] = "ZodNever"; ZodFirstPartyTypeKind2["ZodVoid"] = "ZodVoid"; ZodFirstPartyTypeKind2["ZodArray"] = "ZodArray"; ZodFirstPartyTypeKind2["ZodObject"] = "ZodObject"; ZodFirstPartyTypeKind2["ZodUnion"] = "ZodUnion"; ZodFirstPartyTypeKind2["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; ZodFirstPartyTypeKind2["ZodIntersection"] = "ZodIntersection"; ZodFirstPartyTypeKind2["ZodTuple"] = "ZodTuple"; ZodFirstPartyTypeKind2["ZodRecord"] = "ZodRecord"; ZodFirstPartyTypeKind2["ZodMap"] = "ZodMap"; ZodFirstPartyTypeKind2["ZodSet"] = "ZodSet"; ZodFirstPartyTypeKind2["ZodFunction"] = "ZodFunction"; ZodFirstPartyTypeKind2["ZodLazy"] = "ZodLazy"; ZodFirstPartyTypeKind2["ZodLiteral"] = "ZodLiteral"; ZodFirstPartyTypeKind2["ZodEnum"] = "ZodEnum"; ZodFirstPartyTypeKind2["ZodEffects"] = "ZodEffects"; ZodFirstPartyTypeKind2["ZodNativeEnum"] = "ZodNativeEnum"; ZodFirstPartyTypeKind2["ZodOptional"] = "ZodOptional"; ZodFirstPartyTypeKind2["ZodNullable"] = "ZodNullable"; ZodFirstPartyTypeKind2["ZodDefault"] = "ZodDefault"; ZodFirstPartyTypeKind2["ZodCatch"] = "ZodCatch"; ZodFirstPartyTypeKind2["ZodPromise"] = "ZodPromise"; ZodFirstPartyTypeKind2["ZodBranded"] = "ZodBranded"; ZodFirstPartyTypeKind2["ZodPipeline"] = "ZodPipeline"; })(ZodFirstPartyTypeKind = exports.ZodFirstPartyTypeKind || (exports.ZodFirstPartyTypeKind = {})); var instanceOfType = (cls, params = { message: `Input not instance of ${cls.name}` }) => (0, exports.custom)((data) => data instanceof cls, params); exports.instanceof = instanceOfType; var stringType = ZodString.create; exports.string = stringType; var numberType = ZodNumber.create; exports.number = numberType; var nanType = ZodNaN.create; exports.nan = nanType; var bigIntType = ZodBigInt.create; exports.bigint = bigIntType; var booleanType = ZodBoolean.create; exports.boolean = booleanType; var dateType = ZodDate.create; exports.date = dateType; var symbolType = ZodSymbol.create; exports.symbol = symbolType; var undefinedType = ZodUndefined.create; exports.undefined = undefinedType; var nullType = ZodNull.create; exports.null = nullType; var anyType = ZodAny.create; exports.any = anyType; var unknownType = ZodUnknown.create; exports.unknown = unknownType; var neverType = ZodNever.create; exports.never = neverType; var voidType = ZodVoid.create; exports.void = voidType; var arrayType = ZodArray.create; exports.array = arrayType; var objectType = ZodObject.create; exports.object = objectType; var strictObjectType = ZodObject.strictCreate; exports.strictObject = strictObjectType; var unionType = ZodUnion.create; exports.union = unionType; var discriminatedUnionType = ZodDiscriminatedUnion.create; exports.discriminatedUnion = discriminatedUnionType; var intersectionType = ZodIntersection.create; exports.intersection = intersectionType; var tupleType = ZodTuple.create; exports.tuple = tupleType; var recordType = ZodRecord.create; exports.record = recordType; var mapType = ZodMap.create; exports.map = mapType; var setType = ZodSet.create; exports.set = setType; var functionType = ZodFunction.create; exports.function = functionType; var lazyType = ZodLazy.create; exports.lazy = lazyType; var literalType = ZodLiteral.create; exports.literal = literalType; var enumType = ZodEnum.create; exports.enum = enumType; var nativeEnumType = ZodNativeEnum.create; exports.nativeEnum = nativeEnumType; var promiseType = ZodPromise.create; exports.promise = promiseType; var effectsType = ZodEffects.create; exports.effect = effectsType; exports.transformer = effectsType; var optionalType = ZodOptional.create; exports.optional = optionalType; var nullableType = ZodNullable.create; exports.nullable = nullableType; var preprocessType = ZodEffects.createWithPreprocess; exports.preprocess = preprocessType; var pipelineType = ZodPipeline.create; exports.pipeline = pipelineType; var ostring = () => stringType().optional(); exports.ostring = ostring; var onumber = () => numberType().optional(); exports.onumber = onumber; var oboolean = () => booleanType().optional(); exports.oboolean = oboolean; exports.coerce = { string: (arg) => ZodString.create({ ...arg, coerce: true }), number: (arg) => ZodNumber.create({ ...arg, coerce: true }), boolean: (arg) => ZodBoolean.create({ ...arg, coerce: true }), bigint: (arg) => ZodBigInt.create({ ...arg, coerce: true }), date: (arg) => ZodDate.create({ ...arg, coerce: true }) }; exports.NEVER = parseUtil_1.INVALID; } }); // node_modules/zod/lib/external.js var require_external = __commonJS({ "node_modules/zod/lib/external.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); __exportStar(require_errors(), exports); __exportStar(require_parseUtil(), exports); __exportStar(require_typeAliases(), exports); __exportStar(require_util(), exports); __exportStar(require_types(), exports); __exportStar(require_ZodError(), exports); } }); // node_modules/zod/lib/index.js var require_lib = __commonJS({ "node_modules/zod/lib/index.js"(exports) { "use strict"; var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) { if (k2 === void 0) k2 = k; Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); } : function(o, m, k, k2) { if (k2 === void 0) k2 = k; o[k2] = m[k]; }); var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); } : function(o, v) { o["default"] = v; }); var __importStar = exports && exports.__importStar || function(mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) { for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); } __setModuleDefault(result, mod); return result; }; var __exportStar = exports && exports.__exportStar || function(m, exports2) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.z = void 0; var z = __importStar(require_external()); exports.z = z; __exportStar(require_external(), exports); exports.default = z; } }); // node_modules/zod-to-json-schema/src/parsers/any.js var require_any = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/any.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseAnyDef = void 0; function parseAnyDef() { return {}; } exports.parseAnyDef = parseAnyDef; } }); // node_modules/zod-to-json-schema/src/errorMessages.js var require_errorMessages = __commonJS({ "node_modules/zod-to-json-schema/src/errorMessages.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setResponseValueAndErrors = exports.addErrorMessage = void 0; function addErrorMessage(res, key, errorMessage, refs) { if (!(refs === null || refs === void 0 ? void 0 : refs.errorMessages)) return; if (errorMessage) { res.errorMessage = Object.assign(Object.assign({}, res.errorMessage), { [key]: errorMessage }); } } exports.addErrorMessage = addErrorMessage; function setResponseValueAndErrors(res, key, value, errorMessage, refs) { res[key] = value; addErrorMessage(res, key, errorMessage, refs); } exports.setResponseValueAndErrors = setResponseValueAndErrors; } }); // node_modules/zod-to-json-schema/src/parsers/array.js var require_array = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/array.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseArrayDef = void 0; var zod_1 = require_lib(); var errorMessages_1 = require_errorMessages(); var parseDef_1 = require_parseDef(); function parseArrayDef(def, refs) { var _a, _b; const res = { type: "array" }; if (((_b = (_a = def.type) === null || _a === void 0 ? void 0 : _a._def) === null || _b === void 0 ? void 0 : _b.typeName) !== zod_1.ZodFirstPartyTypeKind.ZodAny) { res.items = (0, parseDef_1.parseDef)(def.type._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items"] })); } if (def.minLength) { (0, errorMessages_1.setResponseValueAndErrors)(res, "minItems", def.minLength.value, def.minLength.message, refs); } if (def.maxLength) { (0, errorMessages_1.setResponseValueAndErrors)(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); } return res; } exports.parseArrayDef = parseArrayDef; } }); // node_modules/zod-to-json-schema/src/parsers/bigint.js var require_bigint = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/bigint.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseBigintDef = void 0; var errorMessages_1 = require_errorMessages(); function parseBigintDef(def, refs) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); } else { (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMinimum = true; } (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check.inclusive) { (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); } else { (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMaximum = true; } (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); } break; case "multipleOf": (0, errorMessages_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); break; } } return res; } exports.parseBigintDef = parseBigintDef; } }); // node_modules/zod-to-json-schema/src/parsers/boolean.js var require_boolean = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/boolean.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseBooleanDef = void 0; function parseBooleanDef() { return { type: "boolean" }; } exports.parseBooleanDef = parseBooleanDef; } }); // node_modules/zod-to-json-schema/src/parsers/branded.js var require_branded = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/branded.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseBrandedDef = void 0; var parseDef_1 = require_parseDef(); function parseBrandedDef(_def, refs) { return (0, parseDef_1.parseDef)(_def.type._def, refs); } exports.parseBrandedDef = parseBrandedDef; } }); // node_modules/zod-to-json-schema/src/parsers/catch.js var require_catch = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/catch.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseCatchDef = void 0; var parseDef_1 = require_parseDef(); var parseCatchDef = (def, refs) => { return (0, parseDef_1.parseDef)(def.innerType._def, refs); }; exports.parseCatchDef = parseCatchDef; } }); // node_modules/zod-to-json-schema/src/parsers/date.js var require_date = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/date.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseDateDef = void 0; function parseDateDef() { return { type: "string", format: "date-time" }; } exports.parseDateDef = parseDateDef; } }); // node_modules/zod-to-json-schema/src/parsers/default.js var require_default = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/default.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseDefaultDef = void 0; var parseDef_1 = require_parseDef(); function parseDefaultDef(_def, refs) { return Object.assign(Object.assign({}, (0, parseDef_1.parseDef)(_def.innerType._def, refs)), { default: _def.defaultValue() }); } exports.parseDefaultDef = parseDefaultDef; } }); // node_modules/zod-to-json-schema/src/parsers/effects.js var require_effects = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/effects.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseEffectsDef = void 0; var parseDef_1 = require_parseDef(); function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? (0, parseDef_1.parseDef)(_def.schema._def, refs) : {}; } exports.parseEffectsDef = parseEffectsDef; } }); // node_modules/zod-to-json-schema/src/parsers/enum.js var require_enum = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/enum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseEnumDef = void 0; function parseEnumDef(def) { return { type: "string", enum: def.values }; } exports.parseEnumDef = parseEnumDef; } }); // node_modules/zod-to-json-schema/src/parsers/intersection.js var require_intersection = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/intersection.js"(exports) { "use strict"; var __rest = exports && exports.__rest || function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseIntersectionDef = void 0; var parseDef_1 = require_parseDef(); var isJsonSchema7AllOfType = (type2) => { if ("type" in type2 && type2.type === "string") return false; return "allOf" in type2; }; function parseIntersectionDef(def, refs) { const allOf = [ (0, parseDef_1.parseDef)(def.left._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })), (0, parseDef_1.parseDef)(def.right._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "1"] })) ].filter((x) => !!x); let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; const mergedAllOf = []; allOf.forEach((schema2) => { if (isJsonSchema7AllOfType(schema2)) { mergedAllOf.push(...schema2.allOf); if (schema2.unevaluatedProperties === void 0) { unevaluatedProperties = void 0; } } else { let nestedSchema = schema2; if ("additionalProperties" in schema2 && schema2.additionalProperties === false) { const { additionalProperties } = schema2, rest = __rest(schema2, ["additionalProperties"]); nestedSchema = rest; } else { unevaluatedProperties = void 0; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? Object.assign({ allOf: mergedAllOf }, unevaluatedProperties) : void 0; } exports.parseIntersectionDef = parseIntersectionDef; } }); // node_modules/zod-to-json-schema/src/parsers/literal.js var require_literal = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/literal.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseLiteralDef = void 0; function parseLiteralDef(def, refs) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") { return { type: Array.isArray(def.value) ? "array" : "object" }; } if (refs.target === "openApi3") { return { type: parsedType === "bigint" ? "integer" : parsedType, enum: [def.value] }; } return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value }; } exports.parseLiteralDef = parseLiteralDef; } }); // node_modules/zod-to-json-schema/src/parsers/map.js var require_map = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/map.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseMapDef = void 0; var parseDef_1 = require_parseDef(); function parseMapDef(def, refs) { const keys3 = (0, parseDef_1.parseDef)(def.keyType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", "items", "0"] })) || {}; const values = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", "items", "1"] })) || {}; return { type: "array", maxItems: 125, items: { type: "array", items: [keys3, values], minItems: 2, maxItems: 2 } }; } exports.parseMapDef = parseMapDef; } }); // node_modules/zod-to-json-schema/src/parsers/nativeEnum.js var require_nativeEnum = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/nativeEnum.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseNativeEnumDef = void 0; function parseNativeEnumDef(def) { const object = def.values; const actualKeys = Object.keys(def.values).filter((key) => { return typeof object[object[key]] !== "number"; }); const actualValues = actualKeys.map((key) => object[key]); const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); return { type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], enum: actualValues }; } exports.parseNativeEnumDef = parseNativeEnumDef; } }); // node_modules/zod-to-json-schema/src/parsers/never.js var require_never = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/never.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseNeverDef = void 0; function parseNeverDef() { return { not: {} }; } exports.parseNeverDef = parseNeverDef; } }); // node_modules/zod-to-json-schema/src/parsers/null.js var require_null = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/null.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseNullDef = void 0; function parseNullDef(refs) { return refs.target === "openApi3" ? { enum: ["null"], nullable: true } : { type: "null" }; } exports.parseNullDef = parseNullDef; } }); // node_modules/zod-to-json-schema/src/parsers/union.js var require_union = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/union.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseUnionDef = exports.primitiveMappings = void 0; var parseDef_1 = require_parseDef(); exports.primitiveMappings = { ZodString: "string", ZodNumber: "number", ZodBigInt: "integer", ZodBoolean: "boolean", ZodNull: "null" }; function parseUnionDef(def, refs) { if (refs.target === "openApi3") return asAnyOf(def, refs); const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; if (options.every((x) => x._def.typeName in exports.primitiveMappings && (!x._def.checks || !x._def.checks.length))) { const types = options.reduce((types2, x) => { const type2 = exports.primitiveMappings[x._def.typeName]; return type2 && !types2.includes(type2) ? [...types2, type2] : types2; }, []); return { type: types.length > 1 ? types : types[0] }; } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { const types = options.reduce((acc, x) => { const type2 = typeof x._def.value; switch (type2) { case "string": case "number": case "boolean": return [...acc, type2]; case "bigint": return [...acc, "integer"]; case "object": if (x._def.value === null) return [...acc, "null"]; case "symbol": case "undefined": case "function": default: return acc; } }, []); if (types.length === options.length) { const uniqueTypes = types.filter((x, i, a2) => a2.indexOf(x) === i); return { type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], enum: options.reduce((acc, x) => { return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; }, []) }; } } else if (options.every((x) => x._def.typeName === "ZodEnum")) { return { type: "string", enum: options.reduce((acc, x) => [ ...acc, ...x._def.values.filter((x2) => !acc.includes(x2)) ], []) }; } return asAnyOf(def, refs); } exports.parseUnionDef = parseUnionDef; var asAnyOf = (def, refs) => { const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", `${i}`] }))).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); return anyOf.length ? { anyOf } : void 0; }; } }); // node_modules/zod-to-json-schema/src/parsers/nullable.js var require_nullable = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/nullable.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseNullableDef = void 0; var parseDef_1 = require_parseDef(); var union_1 = require_union(); function parseNullableDef(def, refs) { if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { if (refs.target === "openApi3") { return { type: union_1.primitiveMappings[def.innerType._def.typeName], nullable: true }; } return { type: [ union_1.primitiveMappings[def.innerType._def.typeName], "null" ] }; } const type2 = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", "0"] })); return type2 ? refs.target === "openApi3" ? Object.assign(Object.assign({}, type2), { nullable: true }) : { anyOf: [ type2, { type: "null" } ] } : void 0; } exports.parseNullableDef = parseNullableDef; } }); // node_modules/zod-to-json-schema/src/parsers/number.js var require_number = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/number.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseNumberDef = void 0; var errorMessages_1 = require_errorMessages(); function parseNumberDef(def, refs) { const res = { type: "number" }; if (!def.checks) return res; for (const check of def.checks) { switch (check.kind) { case "int": res.type = "integer"; (0, errorMessages_1.addErrorMessage)(res, "type", check.message, refs); break; case "min": if (refs.target === "jsonSchema7") { if (check.inclusive) { (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); } else { (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMinimum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMinimum = true; } (0, errorMessages_1.setResponseValueAndErrors)(res, "minimum", check.value, check.message, refs); } break; case "max": if (refs.target === "jsonSchema7") { if (check.inclusive) { (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); } else { (0, errorMessages_1.setResponseValueAndErrors)(res, "exclusiveMaximum", check.value, check.message, refs); } } else { if (!check.inclusive) { res.exclusiveMaximum = true; } (0, errorMessages_1.setResponseValueAndErrors)(res, "maximum", check.value, check.message, refs); } break; case "multipleOf": (0, errorMessages_1.setResponseValueAndErrors)(res, "multipleOf", check.value, check.message, refs); break; } } return res; } exports.parseNumberDef = parseNumberDef; } }); // node_modules/zod-to-json-schema/src/parsers/object.js var require_object = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/object.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseObjectDef = void 0; var parseDef_1 = require_parseDef(); function parseObjectDef(def, refs) { var _a; const result = Object.assign(Object.assign({ type: "object" }, Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { if (propDef === void 0 || propDef._def === void 0) return acc; const parsedDef = (0, parseDef_1.parseDef)(propDef._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", propName], propertyPath: [...refs.currentPath, "properties", propName] })); if (parsedDef === void 0) return acc; return { properties: Object.assign(Object.assign({}, acc.properties), { [propName]: parsedDef }), required: propDef.isOptional() ? acc.required : [...acc.required, propName] }; }, { properties: {}, required: [] })), { additionalProperties: def.catchall._def.typeName === "ZodNever" ? def.unknownKeys === "passthrough" : (_a = (0, parseDef_1.parseDef)(def.catchall._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _a !== void 0 ? _a : true }); if (!result.required.length) delete result.required; return result; } exports.parseObjectDef = parseObjectDef; } }); // node_modules/zod-to-json-schema/src/parsers/optional.js var require_optional = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/optional.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseOptionalDef = void 0; var parseDef_1 = require_parseDef(); var parseOptionalDef = (def, refs) => { var _a; if (refs.currentPath.toString() === ((_a = refs.propertyPath) === null || _a === void 0 ? void 0 : _a.toString())) { return (0, parseDef_1.parseDef)(def.innerType._def, refs); } const innerSchema = (0, parseDef_1.parseDef)(def.innerType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "anyOf", "1"] })); return innerSchema ? { anyOf: [ { not: {} }, innerSchema ] } : {}; }; exports.parseOptionalDef = parseOptionalDef; } }); // node_modules/zod-to-json-schema/src/parsers/pipeline.js var require_pipeline = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/pipeline.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parsePipelineDef = void 0; var parseDef_1 = require_parseDef(); var parsePipelineDef = (def, refs) => { if (refs.pipeStrategy === "input") { return (0, parseDef_1.parseDef)(def.in._def, refs); } const a2 = (0, parseDef_1.parseDef)(def.in._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", "0"] })); const b = (0, parseDef_1.parseDef)(def.out._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "allOf", a2 ? "1" : "0"] })); return { allOf: [a2, b].filter((x) => x !== void 0) }; }; exports.parsePipelineDef = parsePipelineDef; } }); // node_modules/zod-to-json-schema/src/parsers/promise.js var require_promise = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/promise.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parsePromiseDef = void 0; var parseDef_1 = require_parseDef(); function parsePromiseDef(def, refs) { return (0, parseDef_1.parseDef)(def.type._def, refs); } exports.parsePromiseDef = parsePromiseDef; } }); // node_modules/zod-to-json-schema/src/parsers/string.js var require_string = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/string.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseStringDef = void 0; var errorMessages_1 = require_errorMessages(); function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) { for (const check of def.checks) { switch (check.kind) { case "min": (0, errorMessages_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); break; case "max": (0, errorMessages_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); break; case "email": addFormat(res, "email", check.message, refs); break; case "url": addFormat(res, "uri", check.message, refs); break; case "uuid": addFormat(res, "uuid", check.message, refs); break; case "regex": addPattern(res, check.regex.source, check.message, refs); break; case "cuid": addPattern(res, "^c[^\\s-]{8,}$", check.message, refs); break; case "cuid2": addPattern(res, "^[a-z][a-z0-9]*$", check.message, refs); break; case "startsWith": addPattern(res, "^" + escapeNonAlphaNumeric(check.value), check.message, refs); break; case "endsWith": addPattern(res, escapeNonAlphaNumeric(check.value) + "$", check.message, refs); break; case "datetime": addFormat(res, "date-time", check.message, refs); break; case "length": (0, errorMessages_1.setResponseValueAndErrors)(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); (0, errorMessages_1.setResponseValueAndErrors)(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); break; case "includes": { addPattern(res, escapeNonAlphaNumeric(check.value), check.message, refs); break; } case "ip": { if (check.version !== "v6") { addFormat(res, "ipv4", check.message, refs); } if (check.version !== "v4") { addFormat(res, "ipv6", check.message, refs); } break; } case "emoji": addPattern(res, "/^(p{Extended_Pictographic}|p{Emoji_Component})+$/u", check.message, refs); break; case "ulid": { addPattern(res, "/[0-9A-HJKMNP-TV-Z]{26}/", check.message, refs); break; } case "toLowerCase": case "toUpperCase": case "trim": break; default: ((_) => { })(check); } } } return res; } exports.parseStringDef = parseStringDef; var escapeNonAlphaNumeric = (value) => Array.from(value).map((c) => /[a-zA-Z0-9]/.test(c) ? c : `\\${c}`).join(""); var addFormat = (schema2, value, message, refs) => { var _a; if (schema2.format || ((_a = schema2.anyOf) === null || _a === void 0 ? void 0 : _a.some((x) => x.format))) { if (!schema2.anyOf) { schema2.anyOf = []; } if (schema2.format) { schema2.anyOf.push(Object.assign({ format: schema2.format }, schema2.errorMessage && refs.errorMessages && { errorMessage: { format: schema2.errorMessage.format } })); delete schema2.format; if (schema2.errorMessage) { delete schema2.errorMessage.format; if (Object.keys(schema2.errorMessage).length === 0) { delete schema2.errorMessage; } } } schema2.anyOf.push(Object.assign({ format: value }, message && refs.errorMessages && { errorMessage: { format: message } })); } else { (0, errorMessages_1.setResponseValueAndErrors)(schema2, "format", value, message, refs); } }; var addPattern = (schema2, value, message, refs) => { var _a; if (schema2.pattern || ((_a = schema2.allOf) === null || _a === void 0 ? void 0 : _a.some((x) => x.pattern))) { if (!schema2.allOf) { schema2.allOf = []; } if (schema2.pattern) { schema2.allOf.push(Object.assign({ pattern: schema2.pattern }, schema2.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema2.errorMessage.pattern } })); delete schema2.pattern; if (schema2.errorMessage) { delete schema2.errorMessage.pattern; if (Object.keys(schema2.errorMessage).length === 0) { delete schema2.errorMessage; } } } schema2.allOf.push(Object.assign({ pattern: value }, message && refs.errorMessages && { errorMessage: { pattern: message } })); } else { (0, errorMessages_1.setResponseValueAndErrors)(schema2, "pattern", value, message, refs); } }; } }); // node_modules/zod-to-json-schema/src/parsers/record.js var require_record = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/record.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseRecordDef = void 0; var zod_1 = require_lib(); var parseDef_1 = require_parseDef(); var string_1 = require_string(); function parseRecordDef(def, refs) { var _a, _b, _c, _d, _e; if (refs.target === "openApi3" && ((_a = def.keyType) === null || _a === void 0 ? void 0 : _a._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodEnum) { return { type: "object", required: def.keyType._def.values, properties: def.keyType._def.values.reduce((acc, key) => { var _a2; return Object.assign(Object.assign({}, acc), { [key]: (_a2 = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "properties", key] }))) !== null && _a2 !== void 0 ? _a2 : {} }); }, {}), additionalProperties: false }; } const schema2 = { type: "object", additionalProperties: (_b = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalProperties"] }))) !== null && _b !== void 0 ? _b : {} }; if (refs.target === "openApi3") { return schema2; } if (((_c = def.keyType) === null || _c === void 0 ? void 0 : _c._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodString && ((_d = def.keyType._def.checks) === null || _d === void 0 ? void 0 : _d.length)) { const keyType = Object.entries((0, string_1.parseStringDef)(def.keyType._def, refs)).reduce((acc, [key, value]) => key === "type" ? acc : Object.assign(Object.assign({}, acc), { [key]: value }), {}); return Object.assign(Object.assign({}, schema2), { propertyNames: keyType }); } else if (((_e = def.keyType) === null || _e === void 0 ? void 0 : _e._def.typeName) === zod_1.ZodFirstPartyTypeKind.ZodEnum) { return Object.assign(Object.assign({}, schema2), { propertyNames: { enum: def.keyType._def.values } }); } return schema2; } exports.parseRecordDef = parseRecordDef; } }); // node_modules/zod-to-json-schema/src/parsers/set.js var require_set = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/set.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseSetDef = void 0; var errorMessages_1 = require_errorMessages(); var parseDef_1 = require_parseDef(); function parseSetDef(def, refs) { const items = (0, parseDef_1.parseDef)(def.valueType._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items"] })); const schema2 = { type: "array", uniqueItems: true, items }; if (def.minSize) { (0, errorMessages_1.setResponseValueAndErrors)(schema2, "minItems", def.minSize.value, def.minSize.message, refs); } if (def.maxSize) { (0, errorMessages_1.setResponseValueAndErrors)(schema2, "maxItems", def.maxSize.value, def.maxSize.message, refs); } return schema2; } exports.parseSetDef = parseSetDef; } }); // node_modules/zod-to-json-schema/src/parsers/tuple.js var require_tuple = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/tuple.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseTupleDef = void 0; var parseDef_1 = require_parseDef(); function parseTupleDef(def, refs) { if (def.rest) { return { type: "array", minItems: def.items.length, items: def.items.map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", `${i}`] }))).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), additionalItems: (0, parseDef_1.parseDef)(def.rest._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "additionalItems"] })) }; } else { return { type: "array", minItems: def.items.length, maxItems: def.items.length, items: def.items.map((x, i) => (0, parseDef_1.parseDef)(x._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.currentPath, "items", `${i}`] }))).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) }; } } exports.parseTupleDef = parseTupleDef; } }); // node_modules/zod-to-json-schema/src/parsers/undefined.js var require_undefined = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/undefined.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseUndefinedDef = void 0; function parseUndefinedDef() { return { not: {} }; } exports.parseUndefinedDef = parseUndefinedDef; } }); // node_modules/zod-to-json-schema/src/parsers/unknown.js var require_unknown = __commonJS({ "node_modules/zod-to-json-schema/src/parsers/unknown.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseUnknownDef = void 0; function parseUnknownDef() { return {}; } exports.parseUnknownDef = parseUnknownDef; } }); // node_modules/zod-to-json-schema/src/parseDef.js var require_parseDef = __commonJS({ "node_modules/zod-to-json-schema/src/parseDef.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.parseDef = void 0; var zod_1 = require_lib(); var any_1 = require_any(); var array_1 = require_array(); var bigint_1 = require_bigint(); var boolean_1 = require_boolean(); var branded_1 = require_branded(); var catch_1 = require_catch(); var date_1 = require_date(); var default_1 = require_default(); var effects_1 = require_effects(); var enum_1 = require_enum(); var intersection_1 = require_intersection(); var literal_1 = require_literal(); var map_1 = require_map(); var nativeEnum_1 = require_nativeEnum(); var never_1 = require_never(); var null_1 = require_null(); var nullable_1 = require_nullable(); var number_1 = require_number(); var object_1 = require_object(); var optional_1 = require_optional(); var pipeline_1 = require_pipeline(); var promise_1 = require_promise(); var record_1 = require_record(); var set_1 = require_set(); var string_1 = require_string(); var tuple_1 = require_tuple(); var undefined_1 = require_undefined(); var union_1 = require_union(); var unknown_1 = require_unknown(); function parseDef(def, refs, forceResolution = false) { const seenItem = refs.seen.get(def); if (seenItem && !forceResolution) { return get$ref(seenItem, refs); } const newItem = { def, path: refs.currentPath, jsonSchema: void 0 }; refs.seen.set(def, newItem); const jsonSchema = selectParser(def, def.typeName, refs); if (jsonSchema) { addMeta(def, jsonSchema); } newItem.jsonSchema = jsonSchema; return jsonSchema; } exports.parseDef = parseDef; var get$ref = (item, refs) => { switch (refs.$refStrategy) { case "root": return { $ref: item.path.length === 0 ? "" : item.path.length === 1 ? `${item.path[0]}/` : item.path.join("/") }; case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; case "none": { if (item.path.length < refs.currentPath.length && item.path.every((value, index2) => refs.currentPath[index2] === value)) { console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); return {}; } else { return item.jsonSchema; } } } }; var getRelativePath = (pathA, pathB) => { let i = 0; for (; i < pathA.length && i < pathB.length; i++) { if (pathA[i] !== pathB[i]) break; } return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); }; var selectParser = (def, typeName, refs) => { switch (typeName) { case zod_1.ZodFirstPartyTypeKind.ZodString: return (0, string_1.parseStringDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodNumber: return (0, number_1.parseNumberDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodObject: return (0, object_1.parseObjectDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodBigInt: return (0, bigint_1.parseBigintDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodBoolean: return (0, boolean_1.parseBooleanDef)(); case zod_1.ZodFirstPartyTypeKind.ZodDate: return (0, date_1.parseDateDef)(); case zod_1.ZodFirstPartyTypeKind.ZodUndefined: return (0, undefined_1.parseUndefinedDef)(); case zod_1.ZodFirstPartyTypeKind.ZodNull: return (0, null_1.parseNullDef)(refs); case zod_1.ZodFirstPartyTypeKind.ZodArray: return (0, array_1.parseArrayDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodUnion: case zod_1.ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return (0, union_1.parseUnionDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodIntersection: return (0, intersection_1.parseIntersectionDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodTuple: return (0, tuple_1.parseTupleDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodRecord: return (0, record_1.parseRecordDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodLiteral: return (0, literal_1.parseLiteralDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodEnum: return (0, enum_1.parseEnumDef)(def); case zod_1.ZodFirstPartyTypeKind.ZodNativeEnum: return (0, nativeEnum_1.parseNativeEnumDef)(def); case zod_1.ZodFirstPartyTypeKind.ZodNullable: return (0, nullable_1.parseNullableDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodOptional: return (0, optional_1.parseOptionalDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodMap: return (0, map_1.parseMapDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodSet: return (0, set_1.parseSetDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodLazy: return parseDef(def.getter()._def, refs); case zod_1.ZodFirstPartyTypeKind.ZodPromise: return (0, promise_1.parsePromiseDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodNaN: case zod_1.ZodFirstPartyTypeKind.ZodNever: return (0, never_1.parseNeverDef)(); case zod_1.ZodFirstPartyTypeKind.ZodEffects: return (0, effects_1.parseEffectsDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodAny: return (0, any_1.parseAnyDef)(); case zod_1.ZodFirstPartyTypeKind.ZodUnknown: return (0, unknown_1.parseUnknownDef)(); case zod_1.ZodFirstPartyTypeKind.ZodDefault: return (0, default_1.parseDefaultDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodBranded: return (0, branded_1.parseBrandedDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodCatch: return (0, catch_1.parseCatchDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodPipeline: return (0, pipeline_1.parsePipelineDef)(def, refs); case zod_1.ZodFirstPartyTypeKind.ZodFunction: case zod_1.ZodFirstPartyTypeKind.ZodVoid: case zod_1.ZodFirstPartyTypeKind.ZodSymbol: return void 0; default: return ((_) => void 0)(typeName); } }; var addMeta = (def, jsonSchema) => { if (def.description) jsonSchema.description = def.description; return jsonSchema; }; } }); // node_modules/zod-to-json-schema/src/Options.js var require_Options = __commonJS({ "node_modules/zod-to-json-schema/src/Options.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getDefaultOptions = exports.defaultOptions = void 0; exports.defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", definitionPath: "definitions", target: "jsonSchema7", strictUnions: false, definitions: {}, errorMessages: false }; var getDefaultOptions = (options) => typeof options === "string" ? Object.assign(Object.assign({}, exports.defaultOptions), { name: options }) : Object.assign(Object.assign({}, exports.defaultOptions), options); exports.getDefaultOptions = getDefaultOptions; } }); // node_modules/zod-to-json-schema/src/Refs.js var require_Refs = __commonJS({ "node_modules/zod-to-json-schema/src/Refs.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getRefs = void 0; var Options_1 = require_Options(); var getRefs = (options) => { const _options = (0, Options_1.getDefaultOptions)(options); const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath; return Object.assign(Object.assign({}, _options), { currentPath, propertyPath: void 0, seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ def._def, { def: def._def, path: [..._options.basePath, _options.definitionPath, name], // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. jsonSchema: void 0 } ])) }); }; exports.getRefs = getRefs; } }); // node_modules/zod-to-json-schema/src/zodToJsonSchema.js var require_zodToJsonSchema = __commonJS({ "node_modules/zod-to-json-schema/src/zodToJsonSchema.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.zodToJsonSchema = void 0; var parseDef_1 = require_parseDef(); var Refs_1 = require_Refs(); var zodToJsonSchema5 = (schema2, options) => { var _a; const refs = (0, Refs_1.getRefs)(options); const definitions2 = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema3]) => { var _a2; return Object.assign(Object.assign({}, acc), { [name2]: (_a2 = (0, parseDef_1.parseDef)(schema3._def, Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name2] }), true)) !== null && _a2 !== void 0 ? _a2 : {} }); }, {}) : void 0; const name = typeof options === "string" ? options : options === null || options === void 0 ? void 0 : options.name; const main = (_a = (0, parseDef_1.parseDef)(schema2._def, name === void 0 ? refs : Object.assign(Object.assign({}, refs), { currentPath: [...refs.basePath, refs.definitionPath, name] }), false)) !== null && _a !== void 0 ? _a : {}; const combined = name === void 0 ? definitions2 ? Object.assign(Object.assign({}, main), { [refs.definitionPath]: definitions2 }) : main : { $ref: [ ...refs.$refStrategy === "relative" ? [] : refs.basePath, refs.definitionPath, name ].join("/"), [refs.definitionPath]: Object.assign(Object.assign({}, definitions2), { [name]: main }) }; if (refs.target === "jsonSchema7") { combined.$schema = "http://json-schema.org/draft-07/schema#"; } else if (refs.target === "jsonSchema2019-09") { combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; } return combined; }; exports.zodToJsonSchema = zodToJsonSchema5; } }); // node_modules/zod-to-json-schema/index.js var require_zod_to_json_schema = __commonJS({ "node_modules/zod-to-json-schema/index.js"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.zodToJsonSchema = void 0; var zodToJsonSchema_1 = require_zodToJsonSchema(); Object.defineProperty(exports, "zodToJsonSchema", { enumerable: true, get: function() { return zodToJsonSchema_1.zodToJsonSchema; } }); exports.default = zodToJsonSchema_1.zodToJsonSchema; } }); // node_modules/langchain/dist/tools/convert_to_openai.js function formatToOpenAIFunction(tool) { return { name: tool.name, description: tool.description, parameters: (0, import_zod_to_json_schema.zodToJsonSchema)(tool.schema) }; } var import_zod_to_json_schema; var init_convert_to_openai = __esm({ "node_modules/langchain/dist/tools/convert_to_openai.js"() { import_zod_to_json_schema = __toESM(require_zod_to_json_schema(), 1); } }); // node_modules/langchain/dist/util/azure.js function getEndpoint(config) { const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, basePath } = config; if (azureOpenAIApiKey && azureOpenAIBasePath && azureOpenAIApiDeploymentName) { return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; } if (azureOpenAIApiKey) { if (!azureOpenAIApiInstanceName) { throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); } if (!azureOpenAIApiDeploymentName) { throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); } return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; } return basePath; } var init_azure = __esm({ "node_modules/langchain/dist/util/azure.js"() { } }); // node_modules/langchain/dist/chat_models/openai.js var openai_exports = {}; __export(openai_exports, { ChatOpenAI: () => ChatOpenAI, PromptLayerChatOpenAI: () => PromptLayerChatOpenAI }); function messageTypeToOpenAIRole(type2) { switch (type2) { case "system": return "system"; case "ai": return "assistant"; case "human": return "user"; case "function": return "function"; default: throw new Error(`Unknown message type: ${type2}`); } } function openAIResponseToChatMessage(message) { var _a; switch (message.role) { case "user": return new HumanMessage(message.content || ""); case "assistant": return new AIMessage(message.content || "", { function_call: message.function_call }); case "system": return new SystemMessage(message.content || ""); default: return new ChatMessage(message.content || "", (_a = message.role) != null ? _a : "unknown"); } } var import_openai, ChatOpenAI, PromptLayerChatOpenAI; var init_openai = __esm({ "node_modules/langchain/dist/chat_models/openai.js"() { import_openai = __toESM(require_dist2(), 1); init_env2(); init_axios_fetch_adapter(); init_base3(); init_schema(); init_count_tokens(); init_prompt_layer(); init_convert_to_openai(); init_azure(); ChatOpenAI = class extends BaseChatModel { get callKeys() { return [ ...super.callKeys, "options", "function_call", "functions", "tools", "promptIndex" ]; } get lc_secrets() { return { openAIApiKey: "OPENAI_API_KEY", azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" }; } get lc_aliases() { return { modelName: "model", openAIApiKey: "openai_api_key", azureOpenAIApiVersion: "azure_openai_api_version", azureOpenAIApiKey: "azure_openai_api_key", azureOpenAIApiInstanceName: "azure_openai_api_instance_name", azureOpenAIApiDeploymentName: "azure_openai_api_deployment_name" }; } constructor(fields, configuration) { var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n; super(fields != null ? fields : {}); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "temperature", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "topP", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "frequencyPenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "presencePenalty", { enumerable: true, configurable: true, writable: true, value: 0 }); Object.defineProperty(this, "n", { enumerable: true, configurable: true, writable: true, value: 1 }); Object.defineProperty(this, "logitBias", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "modelName", { enumerable: true, configurable: true, writable: true, value: "gpt-3.5-turbo" }); Object.defineProperty(this, "modelKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "stop", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "timeout", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "streaming", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "maxTokens", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "openAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiVersion", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiInstanceName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIApiDeploymentName", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "azureOpenAIBasePath", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "client", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "clientConfig", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.openAIApiKey = (_a = fields == null ? void 0 : fields.openAIApiKey) != null ? _a : getEnvironmentVariable2("OPENAI_API_KEY"); this.azureOpenAIApiKey = (_b = fields == null ? void 0 : fields.azureOpenAIApiKey) != null ? _b : getEnvironmentVariable2("AZURE_OPENAI_API_KEY"); if (!this.azureOpenAIApiKey && !this.openAIApiKey) { throw new Error("OpenAI or Azure OpenAI API key not found"); } this.azureOpenAIApiInstanceName = (_c = fields == null ? void 0 : fields.azureOpenAIApiInstanceName) != null ? _c : getEnvironmentVariable2("AZURE_OPENAI_API_INSTANCE_NAME"); this.azureOpenAIApiDeploymentName = (_d = fields == null ? void 0 : fields.azureOpenAIApiDeploymentName) != null ? _d : getEnvironmentVariable2("AZURE_OPENAI_API_DEPLOYMENT_NAME"); this.azureOpenAIApiVersion = (_e = fields == null ? void 0 : fields.azureOpenAIApiVersion) != null ? _e : getEnvironmentVariable2("AZURE_OPENAI_API_VERSION"); this.azureOpenAIBasePath = (_f = fields == null ? void 0 : fields.azureOpenAIBasePath) != null ? _f : getEnvironmentVariable2("AZURE_OPENAI_BASE_PATH"); this.modelName = (_g = fields == null ? void 0 : fields.modelName) != null ? _g : this.modelName; this.modelKwargs = (_h = fields == null ? void 0 : fields.modelKwargs) != null ? _h : {}; this.timeout = fields == null ? void 0 : fields.timeout; this.temperature = (_i = fields == null ? void 0 : fields.temperature) != null ? _i : this.temperature; this.topP = (_j = fields == null ? void 0 : fields.topP) != null ? _j : this.topP; this.frequencyPenalty = (_k = fields == null ? void 0 : fields.frequencyPenalty) != null ? _k : this.frequencyPenalty; this.presencePenalty = (_l = fields == null ? void 0 : fields.presencePenalty) != null ? _l : this.presencePenalty; this.maxTokens = fields == null ? void 0 : fields.maxTokens; this.n = (_m = fields == null ? void 0 : fields.n) != null ? _m : this.n; this.logitBias = fields == null ? void 0 : fields.logitBias; this.stop = fields == null ? void 0 : fields.stop; this.streaming = (_n = fields == null ? void 0 : fields.streaming) != null ? _n : false; if (this.azureOpenAIApiKey) { if (!this.azureOpenAIApiInstanceName) { throw new Error("Azure OpenAI API instance name not found"); } if (!this.azureOpenAIApiDeploymentName) { throw new Error("Azure OpenAI API deployment name not found"); } if (!this.azureOpenAIApiVersion) { throw new Error("Azure OpenAI API version not found"); } } this.clientConfig = { apiKey: this.openAIApiKey, ...configuration, ...fields == null ? void 0 : fields.configuration }; } /** * Get the parameters used to invoke the model */ invocationParams(options) { var _a, _b; return { model: this.modelName, temperature: this.temperature, top_p: this.topP, frequency_penalty: this.frequencyPenalty, presence_penalty: this.presencePenalty, max_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, n: this.n, logit_bias: this.logitBias, stop: (_a = options == null ? void 0 : options.stop) != null ? _a : this.stop, stream: this.streaming, functions: (_b = options == null ? void 0 : options.functions) != null ? _b : (options == null ? void 0 : options.tools) ? options == null ? void 0 : options.tools.map(formatToOpenAIFunction) : void 0, function_call: options == null ? void 0 : options.function_call, ...this.modelKwargs }; } /** @ignore */ _identifyingParams() { return { model_name: this.modelName, ...this.invocationParams(), ...this.clientConfig }; } /** * Get the identifying parameters for the model */ identifyingParams() { return this._identifyingParams(); } /** @ignore */ async _generate(messages4, options, runManager) { var _a, _b, _c, _d, _e, _f, _g; const tokenUsage = {}; const params = this.invocationParams(options); const messagesMapped = messages4.map((message) => ({ role: messageTypeToOpenAIRole(message._getType()), content: message.content, name: message.name, function_call: message.additional_kwargs.function_call })); const data = params.stream ? await new Promise((resolve, reject) => { let response; let rejected = false; let resolved = false; this.completionWithRetry({ ...params, messages: messagesMapped }, { signal: options == null ? void 0 : options.signal, ...options == null ? void 0 : options.options, adapter: fetchAdapter, responseType: "stream", onmessage: (event) => { var _a2, _b2, _c2, _d2, _e2, _f2, _g2, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q; if (((_b2 = (_a2 = event.data) == null ? void 0 : _a2.trim) == null ? void 0 : _b2.call(_a2)) === "[DONE]") { if (resolved || rejected) { return; } resolved = true; resolve(response); } else { const data2 = JSON.parse(event.data); if (data2 == null ? void 0 : data2.error) { if (rejected) { return; } rejected = true; reject(data2.error); return; } const message = data2; if (!response) { response = { id: message.id, object: message.object, created: message.created, model: message.model, choices: [] }; } for (const part of (_c2 = message.choices) != null ? _c2 : []) { if (part != null) { let choice = response.choices.find((c) => c.index === part.index); if (!choice) { choice = { index: part.index, finish_reason: (_d2 = part.finish_reason) != null ? _d2 : void 0 }; response.choices[part.index] = choice; } if (!choice.message) { choice.message = { role: (_e2 = part.delta) == null ? void 0 : _e2.role, content: "" }; } if (part.delta.function_call && !choice.message.function_call) { choice.message.function_call = { name: "", arguments: "" }; } choice.message.content += (_g2 = (_f2 = part.delta) == null ? void 0 : _f2.content) != null ? _g2 : ""; if (choice.message.function_call) { choice.message.function_call.name += (_j = (_i = (_h = part.delta) == null ? void 0 : _h.function_call) == null ? void 0 : _i.name) != null ? _j : ""; choice.message.function_call.arguments += (_m = (_l = (_k = part.delta) == null ? void 0 : _k.function_call) == null ? void 0 : _l.arguments) != null ? _m : ""; } void (runManager == null ? void 0 : runManager.handleLLMNewToken((_o = (_n = part.delta) == null ? void 0 : _n.content) != null ? _o : "", { prompt: (_p = options.promptIndex) != null ? _p : 0, completion: part.index })); } } if (!resolved && !rejected && ((_q = message.choices) == null ? void 0 : _q.every((c) => c.finish_reason != null))) { resolved = true; resolve(response); } } } }).catch((error) => { if (!rejected) { rejected = true; reject(error); } }); }) : await this.completionWithRetry({ ...params, messages: messagesMapped }, { signal: options == null ? void 0 : options.signal, ...options == null ? void 0 : options.options }); const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = (_a = data.usage) != null ? _a : {}; if (completionTokens) { tokenUsage.completionTokens = ((_b = tokenUsage.completionTokens) != null ? _b : 0) + completionTokens; } if (promptTokens) { tokenUsage.promptTokens = ((_c = tokenUsage.promptTokens) != null ? _c : 0) + promptTokens; } if (totalTokens) { tokenUsage.totalTokens = ((_d = tokenUsage.totalTokens) != null ? _d : 0) + totalTokens; } const generations = []; for (const part of data.choices) { const text4 = (_f = (_e = part.message) == null ? void 0 : _e.content) != null ? _f : ""; generations.push({ text: text4, message: openAIResponseToChatMessage((_g = part.message) != null ? _g : { role: "assistant" }) }); } return { generations, llmOutput: { tokenUsage } }; } async getNumTokensFromMessages(messages4) { let totalCount = 0; let tokensPerMessage = 0; let tokensPerName = 0; if (getModelNameForTiktoken(this.modelName) === "gpt-3.5-turbo") { tokensPerMessage = 4; tokensPerName = -1; } else if (getModelNameForTiktoken(this.modelName).startsWith("gpt-4")) { tokensPerMessage = 3; tokensPerName = 1; } const countPerMessage = await Promise.all(messages4.map(async (message) => { const textCount = await this.getNumTokens(message.content); const roleCount = await this.getNumTokens(messageTypeToOpenAIRole(message._getType())); const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0; const count = textCount + tokensPerMessage + roleCount + nameCount; totalCount += count; return count; })); totalCount += 3; return { totalCount, countPerMessage }; } /** @ignore */ async completionWithRetry(request, options) { if (!this.client) { const openAIEndpointConfig = { azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, azureOpenAIApiKey: this.azureOpenAIApiKey, azureOpenAIBasePath: this.azureOpenAIBasePath, basePath: this.clientConfig.basePath }; const endpoint = getEndpoint(openAIEndpointConfig); const clientConfig = new import_openai.Configuration({ ...this.clientConfig, basePath: endpoint, baseOptions: { timeout: this.timeout, ...this.clientConfig.baseOptions } }); this.client = new import_openai.OpenAIApi(clientConfig); } const axiosOptions = { adapter: isNode2() ? void 0 : fetchAdapter, ...this.clientConfig.baseOptions, ...options }; if (this.azureOpenAIApiKey) { axiosOptions.headers = { "api-key": this.azureOpenAIApiKey, ...axiosOptions.headers }; axiosOptions.params = { "api-version": this.azureOpenAIApiVersion, ...axiosOptions.params }; } return this.caller.call(this.client.createChatCompletion.bind(this.client), request, axiosOptions).then((res) => res.data); } _llmType() { return "openai"; } /** @ignore */ _combineLLMOutput(...llmOutputs) { return llmOutputs.reduce((acc, llmOutput) => { var _a, _b, _c; if (llmOutput && llmOutput.tokenUsage) { acc.tokenUsage.completionTokens += (_a = llmOutput.tokenUsage.completionTokens) != null ? _a : 0; acc.tokenUsage.promptTokens += (_b = llmOutput.tokenUsage.promptTokens) != null ? _b : 0; acc.tokenUsage.totalTokens += (_c = llmOutput.tokenUsage.totalTokens) != null ? _c : 0; } return acc; }, { tokenUsage: { completionTokens: 0, promptTokens: 0, totalTokens: 0 } }); } }; PromptLayerChatOpenAI = class extends ChatOpenAI { constructor(fields) { var _a, _b, _c, _d; super(fields); Object.defineProperty(this, "promptLayerApiKey", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "plTags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "returnPromptLayerId", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.promptLayerApiKey = (_b = fields == null ? void 0 : fields.promptLayerApiKey) != null ? _b : typeof process !== "undefined" ? ( // eslint-disable-next-line no-process-env (_a = process.env) == null ? void 0 : _a.PROMPTLAYER_API_KEY ) : void 0; this.plTags = (_c = fields == null ? void 0 : fields.plTags) != null ? _c : []; this.returnPromptLayerId = (_d = fields == null ? void 0 : fields.returnPromptLayerId) != null ? _d : false; } async _generate(messages4, options, runManager) { const requestStartTime = Date.now(); let parsedOptions; if (Array.isArray(options)) { parsedOptions = { stop: options }; } else if ((options == null ? void 0 : options.timeout) && !options.signal) { parsedOptions = { ...options, signal: AbortSignal.timeout(options.timeout) }; } else { parsedOptions = options != null ? options : {}; } const generatedResponses = await super._generate(messages4, parsedOptions, runManager); const requestEndTime = Date.now(); const _convertMessageToDict = (message) => { let messageDict; if (message._getType() === "human") { messageDict = { role: "user", content: message.content }; } else if (message._getType() === "ai") { messageDict = { role: "assistant", content: message.content }; } else if (message._getType() === "system") { messageDict = { role: "system", content: message.content }; } else if (message._getType() === "generic") { messageDict = { role: message.role, content: message.content }; } else { throw new Error(`Got unknown type ${message}`); } return messageDict; }; const _createMessageDicts = (messages5, callOptions) => { const params = { ...this.invocationParams(), model: this.modelName }; if (callOptions == null ? void 0 : callOptions.stop) { if (Object.keys(params).includes("stop")) { throw new Error("`stop` found in both the input and default params."); } } const messageDicts = messages5.map((message) => _convertMessageToDict(message)); return messageDicts; }; for (let i = 0; i < generatedResponses.generations.length; i += 1) { const generation = generatedResponses.generations[i]; const messageDicts = _createMessageDicts(messages4, parsedOptions); let promptLayerRequestId; const parsedResp = [ { content: generation.text, role: messageTypeToOpenAIRole(generation.message._getType()) } ]; const promptLayerRespBody = await promptLayerTrackRequest(this.caller, "langchain.PromptLayerChatOpenAI", messageDicts, this._identifyingParams(), this.plTags, parsedResp, requestStartTime, requestEndTime, this.promptLayerApiKey); if (this.returnPromptLayerId === true) { if (promptLayerRespBody.success === true) { promptLayerRequestId = promptLayerRespBody.request_id; } if (!generation.generationInfo || typeof generation.generationInfo !== "object") { generation.generationInfo = {}; } generation.generationInfo.promptLayerRequestId = promptLayerRequestId; } } return generatedResponses; } }; } }); // node_modules/langchain/dist/base_language/index.js var getVerbosity, BaseLangChain, BaseLanguageModel; var init_base_language = __esm({ "node_modules/langchain/dist/base_language/index.js"() { init_async_caller2(); init_count_tokens(); init_tiktoken(); init_serializable(); init_count_tokens(); getVerbosity = () => false; BaseLangChain = class extends Serializable { get lc_attributes() { return { callbacks: void 0, verbose: void 0 }; } constructor(params) { var _a, _b, _c; super(params); Object.defineProperty(this, "verbose", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "callbacks", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "tags", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.verbose = (_a = params.verbose) != null ? _a : getVerbosity(); this.callbacks = params.callbacks; this.tags = (_b = params.tags) != null ? _b : []; this.metadata = (_c = params.metadata) != null ? _c : {}; } }; BaseLanguageModel = class extends BaseLangChain { /** * Keys that the language model accepts as call options. */ get callKeys() { return ["stop", "timeout", "signal", "tags", "metadata", "callbacks"]; } constructor({ callbacks, callbackManager, ...params }) { super({ callbacks: callbacks != null ? callbacks : callbackManager, ...params }); Object.defineProperty(this, "caller", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "_encoding", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.caller = new AsyncCaller2(params != null ? params : {}); } async getNumTokens(text4) { let numTokens = Math.ceil(text4.length / 4); if (!this._encoding) { try { this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); } catch (error) { console.warn("Failed to calculate number of tokens, falling back to approximate count", error); } } if (this._encoding) { numTokens = this._encoding.encode(text4).length; } return numTokens; } /** * Get the identifying parameters of the LLM. */ // eslint-disable-next-line @typescript-eslint/no-explicit-any _identifyingParams() { return {}; } /** * @deprecated * Return a json-like object representing this LLM. */ serialize() { return { ...this._identifyingParams(), _type: this._llmType(), _model: this._modelType() }; } /** * @deprecated * Load an LLM from a json-like object describing it. */ static async deserialize(data) { const { _type, _model, ...rest } = data; if (_model && _model !== "base_chat_model") { throw new Error(`Cannot load LLM with model ${_model}`); } const Cls = { openai: (await Promise.resolve().then(() => (init_openai(), openai_exports))).ChatOpenAI }[_type]; if (Cls === void 0) { throw new Error(`Cannot load LLM with type ${_type}`); } return new Cls(rest); } }; } }); // node_modules/langchain/dist/prompts/template.js var parseFString, interpolateFString, DEFAULT_FORMATTER_MAPPING, DEFAULT_PARSER_MAPPING, renderTemplate, parseTemplate, checkValidTemplate; var init_template = __esm({ "node_modules/langchain/dist/prompts/template.js"() { parseFString = (template) => { const chars = template.split(""); const nodes = []; const nextBracket = (bracket, start) => { for (let i2 = start; i2 < chars.length; i2 += 1) { if (bracket.includes(chars[i2])) { return i2; } } return -1; }; let i = 0; while (i < chars.length) { if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { nodes.push({ type: "literal", text: "{" }); i += 2; } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { nodes.push({ type: "literal", text: "}" }); i += 2; } else if (chars[i] === "{") { const j = nextBracket("}", i); if (j < 0) { throw new Error("Unclosed '{' in template."); } nodes.push({ type: "variable", name: chars.slice(i + 1, j).join("") }); i = j + 1; } else if (chars[i] === "}") { throw new Error("Single '}' in template."); } else { const next = nextBracket("{}", i); const text4 = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); nodes.push({ type: "literal", text: text4 }); i = next < 0 ? chars.length : next; } } return nodes; }; interpolateFString = (template, values) => parseFString(template).reduce((res, node2) => { if (node2.type === "variable") { if (node2.name in values) { return res + values[node2.name]; } throw new Error(`Missing value for input ${node2.name}`); } return res + node2.text; }, ""); DEFAULT_FORMATTER_MAPPING = { "f-string": interpolateFString, jinja2: (_, __) => "" }; DEFAULT_PARSER_MAPPING = { "f-string": parseFString, jinja2: (_) => [] }; renderTemplate = (template, templateFormat, inputValues) => DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); checkValidTemplate = (template, templateFormat, inputVariables) => { if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); throw new Error(`Invalid template format. Got \`${templateFormat}\`; should be one of ${validFormats}`); } try { const dummyInputs = inputVariables.reduce((acc, v) => { acc[v] = "foo"; return acc; }, {}); renderTemplate(template, templateFormat, dummyInputs); } catch (e) { throw new Error(`Invalid prompt schema: ${e.message}`); } }; } }); // node_modules/langchain/dist/prompts/prompt.js var prompt_exports = {}; __export(prompt_exports, { PromptTemplate: () => PromptTemplate }); var PromptTemplate; var init_prompt = __esm({ "node_modules/langchain/dist/prompts/prompt.js"() { init_base4(); init_template(); PromptTemplate = class extends BaseStringPromptTemplate { constructor(input) { super(input); Object.defineProperty(this, "template", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "templateFormat", { enumerable: true, configurable: true, writable: true, value: "f-string" }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); Object.assign(this, input); if (this.validateTemplate) { let totalInputVariables = this.inputVariables; if (this.partialVariables) { totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); } checkValidTemplate(this.template, this.templateFormat, totalInputVariables); } } _getPromptType() { return "prompt"; } async format(values) { const allValues = await this.mergePartialAndUserVariables(values); return renderTemplate(this.template, this.templateFormat, allValues); } /** * Take examples in list format with prefix and suffix to create a prompt. * * Intendend to be used a a way to dynamically create a prompt from examples. * * @param examples - List of examples to use in the prompt. * @param suffix - String to go after the list of examples. Should generally set up the user's input. * @param inputVariables - A list of variable names the final prompt template will expect * @param exampleSeparator - The separator to use in between examples * @param prefix - String that should go before any examples. Generally includes examples. * * @returns The final prompt template generated. */ static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { const template = [prefix, ...examples, suffix].join(exampleSeparator); return new PromptTemplate({ inputVariables, template }); } /** * Load prompt template from a template f-string */ static fromTemplate(template, { templateFormat = "f-string", ...rest } = {}) { const names = /* @__PURE__ */ new Set(); parseTemplate(template, templateFormat).forEach((node2) => { if (node2.type === "variable") { names.add(node2.name); } }); return new PromptTemplate({ inputVariables: [...names], templateFormat, template, ...rest }); } async partial(values) { var _a; const promptDict = { ...this }; promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); promptDict.partialVariables = { ...(_a = this.partialVariables) != null ? _a : {}, ...values }; return new PromptTemplate(promptDict); } serialize() { if (this.outputParser !== void 0) { throw new Error("Cannot serialize a prompt template with an output parser"); } return { _type: this._getPromptType(), input_variables: this.inputVariables, template: this.template, template_format: this.templateFormat }; } static async deserialize(data) { if (!data.template) { throw new Error("Prompt template must have a template"); } const res = new PromptTemplate({ inputVariables: data.input_variables, template: data.template, templateFormat: data.template_format }); return res; } }; } }); // node_modules/langchain/dist/prompts/few_shot.js var few_shot_exports = {}; __export(few_shot_exports, { FewShotPromptTemplate: () => FewShotPromptTemplate }); var FewShotPromptTemplate; var init_few_shot = __esm({ "node_modules/langchain/dist/prompts/few_shot.js"() { init_base4(); init_template(); init_prompt(); FewShotPromptTemplate = class extends BaseStringPromptTemplate { constructor(input) { super(input); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "examples", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "exampleSelector", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "examplePrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "suffix", { enumerable: true, configurable: true, writable: true, value: "" }); Object.defineProperty(this, "exampleSeparator", { enumerable: true, configurable: true, writable: true, value: "\n\n" }); Object.defineProperty(this, "prefix", { enumerable: true, configurable: true, writable: true, value: "" }); Object.defineProperty(this, "templateFormat", { enumerable: true, configurable: true, writable: true, value: "f-string" }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); Object.assign(this, input); if (this.examples !== void 0 && this.exampleSelector !== void 0) { throw new Error("Only one of 'examples' and 'example_selector' should be provided"); } if (this.examples === void 0 && this.exampleSelector === void 0) { throw new Error("One of 'examples' and 'example_selector' should be provided"); } if (this.validateTemplate) { let totalInputVariables = this.inputVariables; if (this.partialVariables) { totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); } checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); } } _getPromptType() { return "few_shot"; } async getExamples(inputVariables) { if (this.examples !== void 0) { return this.examples; } if (this.exampleSelector !== void 0) { return this.exampleSelector.selectExamples(inputVariables); } throw new Error("One of 'examples' and 'example_selector' should be provided"); } async partial(values) { var _a; const promptDict = { ...this }; promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); promptDict.partialVariables = { ...(_a = this.partialVariables) != null ? _a : {}, ...values }; return new FewShotPromptTemplate(promptDict); } async format(values) { const allValues = await this.mergePartialAndUserVariables(values); const examples = await this.getExamples(allValues); const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); const template = [this.prefix, ...exampleStrings, this.suffix].join(this.exampleSeparator); return renderTemplate(template, this.templateFormat, allValues); } serialize() { if (this.exampleSelector || !this.examples) { throw new Error("Serializing an example selector is not currently supported"); } if (this.outputParser !== void 0) { throw new Error("Serializing an output parser is not currently supported"); } return { _type: this._getPromptType(), input_variables: this.inputVariables, example_prompt: this.examplePrompt.serialize(), example_separator: this.exampleSeparator, suffix: this.suffix, prefix: this.prefix, template_format: this.templateFormat, examples: this.examples }; } static async deserialize(data) { const { example_prompt } = data; if (!example_prompt) { throw new Error("Missing example prompt"); } const examplePrompt = await PromptTemplate.deserialize(example_prompt); let examples; if (Array.isArray(data.examples)) { examples = data.examples; } else { throw new Error("Invalid examples format. Only list or string are supported."); } return new FewShotPromptTemplate({ inputVariables: data.input_variables, examplePrompt, examples, exampleSeparator: data.example_separator, prefix: data.prefix, suffix: data.suffix, templateFormat: data.template_format }); } }; } }); // node_modules/langchain/dist/prompts/base.js var StringPromptValue, BasePromptTemplate, BaseStringPromptTemplate; var init_base4 = __esm({ "node_modules/langchain/dist/prompts/base.js"() { init_schema(); init_serializable(); StringPromptValue = class extends BasePromptValue { constructor(value) { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "prompts", "base"] }); Object.defineProperty(this, "value", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.value = value; } toString() { return this.value; } toChatMessages() { return [new HumanMessage(this.value)]; } }; BasePromptTemplate = class extends Serializable { get lc_attributes() { return { partialVariables: void 0 // python doesn't support this yet }; } constructor(input) { super(input); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "prompts", this._getPromptType()] }); Object.defineProperty(this, "inputVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "partialVariables", { enumerable: true, configurable: true, writable: true, value: {} }); const { inputVariables } = input; if (inputVariables.includes("stop")) { throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); } Object.assign(this, input); } async mergePartialAndUserVariables(userVariables) { var _a; const partialVariables = (_a = this.partialVariables) != null ? _a : {}; const partialValues = {}; for (const [key, value] of Object.entries(partialVariables)) { if (typeof value === "string") { partialValues[key] = value; } else { partialValues[key] = await value(); } } const allKwargs = { ...partialValues, ...userVariables }; return allKwargs; } /** * Return a json-like object representing this prompt template. * @deprecated */ serialize() { throw new Error("Use .toJSON() instead"); } /** * @deprecated * Load a prompt template from a json-like object describing it. * * @remarks * Deserializing needs to be async because templates (e.g. {@link FewShotPromptTemplate}) can * reference remote resources that we read asynchronously with a web * request. */ static async deserialize(data) { switch (data._type) { case "prompt": { const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); return PromptTemplate2.deserialize(data); } case void 0: { const { PromptTemplate: PromptTemplate2 } = await Promise.resolve().then(() => (init_prompt(), prompt_exports)); return PromptTemplate2.deserialize({ ...data, _type: "prompt" }); } case "few_shot": { const { FewShotPromptTemplate: FewShotPromptTemplate2 } = await Promise.resolve().then(() => (init_few_shot(), few_shot_exports)); return FewShotPromptTemplate2.deserialize(data); } default: throw new Error(`Invalid prompt type in config: ${data._type}`); } } }; BaseStringPromptTemplate = class extends BasePromptTemplate { async formatPromptValue(values) { const formattedPrompt = await this.format(values); return new StringPromptValue(formattedPrompt); } }; } }); // node_modules/langchain/dist/schema/output_parser.js var BaseLLMOutputParser, BaseOutputParser; var init_output_parser = __esm({ "node_modules/langchain/dist/schema/output_parser.js"() { init_serializable(); BaseLLMOutputParser = class extends Serializable { parseResultWithPrompt(generations, _prompt, callbacks) { return this.parseResult(generations, callbacks); } }; BaseOutputParser = class extends BaseLLMOutputParser { parseResult(generations, callbacks) { return this.parse(generations[0].text, callbacks); } async parseWithPrompt(text4, _prompt, callbacks) { return this.parse(text4, callbacks); } /** * Return the string type key uniquely identifying this class of parser */ _type() { throw new Error("_type not implemented"); } }; } }); // node_modules/langchain/dist/output_parsers/noop.js var NoOpOutputParser; var init_noop = __esm({ "node_modules/langchain/dist/output_parsers/noop.js"() { init_output_parser(); NoOpOutputParser = class extends BaseOutputParser { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "output_parsers", "default"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } parse(text4) { return Promise.resolve(text4); } getFormatInstructions() { return ""; } }; } }); // node_modules/langchain/dist/chains/llm_chain.js var llm_chain_exports = {}; __export(llm_chain_exports, { LLMChain: () => LLMChain }); var LLMChain; var init_llm_chain = __esm({ "node_modules/langchain/dist/chains/llm_chain.js"() { init_base5(); init_base4(); init_base_language(); init_noop(); LLMChain = class extends BaseChain { get inputKeys() { return this.prompt.inputVariables; } get outputKeys() { return [this.outputKey]; } constructor(fields) { var _a, _b; super(fields); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "prompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "llm", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "llmKwargs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "text" }); Object.defineProperty(this, "outputParser", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.prompt = fields.prompt; this.llm = fields.llm; this.llmKwargs = fields.llmKwargs; this.outputKey = (_a = fields.outputKey) != null ? _a : this.outputKey; this.outputParser = (_b = fields.outputParser) != null ? _b : new NoOpOutputParser(); if (this.prompt.outputParser) { if (fields.outputParser) { throw new Error("Cannot set both outputParser and prompt.outputParser"); } this.outputParser = this.prompt.outputParser; } } /** @ignore */ _selectMemoryInputs(values) { const valuesForMemory = super._selectMemoryInputs(values); for (const key of this.llm.callKeys) { if (key in values) { delete valuesForMemory[key]; } } return valuesForMemory; } /** @ignore */ async _getFinalOutput(generations, promptValue, runManager) { let finalCompletion; if (this.outputParser) { finalCompletion = await this.outputParser.parseResultWithPrompt(generations, promptValue, runManager == null ? void 0 : runManager.getChild()); } else { finalCompletion = generations[0].text; } return finalCompletion; } /** * Run the core logic of this chain and add to output if desired. * * Wraps _call and handles memory. */ call(values, callbacks) { return super.call(values, callbacks); } /** @ignore */ async _call(values, runManager) { const valuesForPrompt = { ...values }; const valuesForLLM = { ...this.llmKwargs }; for (const key of this.llm.callKeys) { if (key in values) { valuesForLLM[key] = values[key]; delete valuesForPrompt[key]; } } const promptValue = await this.prompt.formatPromptValue(valuesForPrompt); const { generations } = await this.llm.generatePrompt([promptValue], valuesForLLM, runManager == null ? void 0 : runManager.getChild()); return { [this.outputKey]: await this._getFinalOutput(generations[0], promptValue, runManager) }; } /** * Format prompt with values and pass to LLM * * @param values - keys to pass to prompt template * @param callbackManager - CallbackManager to use * @returns Completion from LLM. * * @example * ```ts * llm.predict({ adjective: "funny" }) * ``` */ async predict(values, callbackManager) { const output = await this.call(values, callbackManager); return output[this.outputKey]; } _chainType() { return "llm"; } static async deserialize(data) { const { llm, prompt } = data; if (!llm) { throw new Error("LLMChain must have llm"); } if (!prompt) { throw new Error("LLMChain must have prompt"); } return new LLMChain({ llm: await BaseLanguageModel.deserialize(llm), prompt: await BasePromptTemplate.deserialize(prompt) }); } /** @deprecated */ serialize() { return { _type: `${this._chainType()}_chain`, llm: this.llm.serialize(), prompt: this.prompt.serialize() }; } }; } }); // node_modules/langchain/dist/util/set.js function intersection(setA, setB) { const _intersection = /* @__PURE__ */ new Set(); for (const elem of setB) { if (setA.has(elem)) { _intersection.add(elem); } } return _intersection; } function union(setA, setB) { const _union = new Set(setA); for (const elem of setB) { _union.add(elem); } return _union; } function difference(setA, setB) { const _difference = new Set(setA); for (const elem of setB) { _difference.delete(elem); } return _difference; } var init_set = __esm({ "node_modules/langchain/dist/util/set.js"() { } }); // node_modules/langchain/dist/chains/sequential_chain.js var sequential_chain_exports = {}; __export(sequential_chain_exports, { SequentialChain: () => SequentialChain, SimpleSequentialChain: () => SimpleSequentialChain }); function formatSet(input) { return Array.from(input).map((i) => `"${i}"`).join(", "); } var SequentialChain, SimpleSequentialChain; var init_sequential_chain = __esm({ "node_modules/langchain/dist/chains/sequential_chain.js"() { init_base5(); init_set(); SequentialChain = class extends BaseChain { get inputKeys() { return this.inputVariables; } get outputKeys() { return this.outputVariables; } constructor(fields) { var _a, _b; super(fields); Object.defineProperty(this, "chains", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "outputVariables", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "returnAll", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.chains = fields.chains; this.inputVariables = fields.inputVariables; this.outputVariables = (_a = fields.outputVariables) != null ? _a : []; if (this.outputVariables.length > 0 && fields.returnAll) { throw new Error("Either specify variables to return using `outputVariables` or use `returnAll` param. Cannot apply both conditions at the same time."); } this.returnAll = (_b = fields.returnAll) != null ? _b : false; this._validateChains(); } /** @ignore */ _validateChains() { var _a, _b; if (this.chains.length === 0) { throw new Error("Sequential chain must have at least one chain."); } const memoryKeys = (_b = (_a = this.memory) == null ? void 0 : _a.memoryKeys) != null ? _b : []; const inputKeysSet = new Set(this.inputKeys); const memoryKeysSet = new Set(memoryKeys); const keysIntersection = intersection(inputKeysSet, memoryKeysSet); if (keysIntersection.size > 0) { throw new Error(`The following keys: ${formatSet(keysIntersection)} are overlapping between memory and input keys of the chain variables. This can lead to unexpected behaviour. Please use input and memory keys that don't overlap.`); } const availableKeys = union(inputKeysSet, memoryKeysSet); for (const chain of this.chains) { const missingKeys = difference(new Set(chain.inputKeys), availableKeys); if (missingKeys.size > 0) { throw new Error(`Missing variables for chain "${chain._chainType()}": ${formatSet(missingKeys)}. Only got the following variables: ${formatSet(availableKeys)}.`); } const outputKeysSet = new Set(chain.outputKeys); const overlappingOutputKeys = intersection(availableKeys, outputKeysSet); if (overlappingOutputKeys.size > 0) { throw new Error(`The following output variables for chain "${chain._chainType()}" are overlapping: ${formatSet(overlappingOutputKeys)}. This can lead to unexpected behaviour.`); } for (const outputKey of outputKeysSet) { availableKeys.add(outputKey); } } if (this.outputVariables.length === 0) { if (this.returnAll) { const outputKeys = difference(availableKeys, inputKeysSet); this.outputVariables = Array.from(outputKeys); } else { this.outputVariables = this.chains[this.chains.length - 1].outputKeys; } } else { const missingKeys = difference(new Set(this.outputVariables), new Set(availableKeys)); if (missingKeys.size > 0) { throw new Error(`The following output variables were expected to be in the final chain output but were not found: ${formatSet(missingKeys)}.`); } } } /** @ignore */ async _call(values, runManager) { let input = {}; const allChainValues = values; let i = 0; for (const chain of this.chains) { i += 1; input = await chain.call(allChainValues, runManager == null ? void 0 : runManager.getChild(`step_${i}`)); for (const key of Object.keys(input)) { allChainValues[key] = input[key]; } } const output = {}; for (const key of this.outputVariables) { output[key] = allChainValues[key]; } return output; } _chainType() { return "sequential_chain"; } static async deserialize(data) { const chains = []; const inputVariables = data.input_variables; const outputVariables = data.output_variables; const serializedChains = data.chains; for (const serializedChain of serializedChains) { const deserializedChain = await BaseChain.deserialize(serializedChain); chains.push(deserializedChain); } return new SequentialChain({ chains, inputVariables, outputVariables }); } serialize() { const chains = []; for (const chain of this.chains) { chains.push(chain.serialize()); } return { _type: this._chainType(), input_variables: this.inputVariables, output_variables: this.outputVariables, chains }; } }; SimpleSequentialChain = class extends BaseChain { get inputKeys() { return [this.inputKey]; } get outputKeys() { return [this.outputKey]; } constructor(fields) { var _a; super(fields); Object.defineProperty(this, "chains", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input" }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "output" }); Object.defineProperty(this, "trimOutputs", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.chains = fields.chains; this.trimOutputs = (_a = fields.trimOutputs) != null ? _a : false; this._validateChains(); } /** @ignore */ _validateChains() { for (const chain of this.chains) { if (chain.inputKeys.filter((k) => { var _a; return !((_a = chain.memory) == null ? void 0 : _a.memoryKeys.includes(k)); }).length !== 1) { throw new Error(`Chains used in SimpleSequentialChain should all have one input, got ${chain.inputKeys.length} for ${chain._chainType()}.`); } if (chain.outputKeys.length !== 1) { throw new Error(`Chains used in SimpleSequentialChain should all have one output, got ${chain.outputKeys.length} for ${chain._chainType()}.`); } } } /** @ignore */ async _call(values, runManager) { let input = values[this.inputKey]; let i = 0; for (const chain of this.chains) { i += 1; input = (await chain.call({ [chain.inputKeys[0]]: input, signal: values.signal }, runManager == null ? void 0 : runManager.getChild(`step_${i}`)))[chain.outputKeys[0]]; if (this.trimOutputs) { input = input.trim(); } await (runManager == null ? void 0 : runManager.handleText(input)); } return { [this.outputKey]: input }; } _chainType() { return "simple_sequential_chain"; } static async deserialize(data) { const chains = []; const serializedChains = data.chains; for (const serializedChain of serializedChains) { const deserializedChain = await BaseChain.deserialize(serializedChain); chains.push(deserializedChain); } return new SimpleSequentialChain({ chains }); } serialize() { const chains = []; for (const chain of this.chains) { chains.push(chain.serialize()); } return { _type: this._chainType(), chains }; } }; } }); // node_modules/langchain/dist/chains/combine_docs_chain.js var combine_docs_chain_exports = {}; __export(combine_docs_chain_exports, { MapReduceDocumentsChain: () => MapReduceDocumentsChain, RefineDocumentsChain: () => RefineDocumentsChain, StuffDocumentsChain: () => StuffDocumentsChain }); var StuffDocumentsChain, MapReduceDocumentsChain, RefineDocumentsChain; var init_combine_docs_chain = __esm({ "node_modules/langchain/dist/chains/combine_docs_chain.js"() { init_base5(); init_llm_chain(); init_prompt(); StuffDocumentsChain = class extends BaseChain { get inputKeys() { return [this.inputKey, ...this.llmChain.inputKeys].filter((key) => key !== this.documentVariableName); } get outputKeys() { return this.llmChain.outputKeys; } constructor(fields) { var _a, _b; super(fields); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input_documents" }); Object.defineProperty(this, "documentVariableName", { enumerable: true, configurable: true, writable: true, value: "context" }); this.llmChain = fields.llmChain; this.documentVariableName = (_a = fields.documentVariableName) != null ? _a : this.documentVariableName; this.inputKey = (_b = fields.inputKey) != null ? _b : this.inputKey; } /** @ignore */ _prepInputs(values) { if (!(this.inputKey in values)) { throw new Error(`Document key ${this.inputKey} not found.`); } const { [this.inputKey]: docs, ...rest } = values; const texts = docs.map(({ pageContent }) => pageContent); const text4 = texts.join("\n\n"); return { ...rest, [this.documentVariableName]: text4 }; } /** @ignore */ async _call(values, runManager) { const result = await this.llmChain.call(this._prepInputs(values), runManager == null ? void 0 : runManager.getChild("combine_documents")); return result; } _chainType() { return "stuff_documents_chain"; } static async deserialize(data) { if (!data.llm_chain) { throw new Error("Missing llm_chain"); } return new StuffDocumentsChain({ llmChain: await LLMChain.deserialize(data.llm_chain) }); } serialize() { return { _type: this._chainType(), llm_chain: this.llmChain.serialize() }; } }; MapReduceDocumentsChain = class extends BaseChain { get inputKeys() { return [this.inputKey, ...this.combineDocumentChain.inputKeys]; } get outputKeys() { return this.combineDocumentChain.outputKeys; } constructor(fields) { var _a, _b, _c, _d, _e, _f; super(fields); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input_documents" }); Object.defineProperty(this, "documentVariableName", { enumerable: true, configurable: true, writable: true, value: "context" }); Object.defineProperty(this, "returnIntermediateSteps", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "maxTokens", { enumerable: true, configurable: true, writable: true, value: 3e3 }); Object.defineProperty(this, "maxIterations", { enumerable: true, configurable: true, writable: true, value: 10 }); Object.defineProperty(this, "ensureMapStep", { enumerable: true, configurable: true, writable: true, value: false }); Object.defineProperty(this, "combineDocumentChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.llmChain = fields.llmChain; this.combineDocumentChain = fields.combineDocumentChain; this.documentVariableName = (_a = fields.documentVariableName) != null ? _a : this.documentVariableName; this.ensureMapStep = (_b = fields.ensureMapStep) != null ? _b : this.ensureMapStep; this.inputKey = (_c = fields.inputKey) != null ? _c : this.inputKey; this.maxTokens = (_d = fields.maxTokens) != null ? _d : this.maxTokens; this.maxIterations = (_e = fields.maxIterations) != null ? _e : this.maxIterations; this.returnIntermediateSteps = (_f = fields.returnIntermediateSteps) != null ? _f : false; } /** @ignore */ async _call(values, runManager) { if (!(this.inputKey in values)) { throw new Error(`Document key ${this.inputKey} not found.`); } const { [this.inputKey]: docs, ...rest } = values; let currentDocs = docs; let intermediateSteps = []; for (let i = 0; i < this.maxIterations; i += 1) { const inputs = currentDocs.map((d) => ({ [this.documentVariableName]: d.pageContent, ...rest })); const canSkipMapStep = i !== 0 || !this.ensureMapStep; if (canSkipMapStep) { const formatted = await this.combineDocumentChain.llmChain.prompt.format(this.combineDocumentChain._prepInputs({ [this.combineDocumentChain.inputKey]: currentDocs, ...rest })); const length = await this.combineDocumentChain.llmChain.llm.getNumTokens(formatted); const withinTokenLimit = length < this.maxTokens; if (withinTokenLimit) { break; } } const results = await this.llmChain.apply( inputs, // If we have a runManager, then we need to create a child for each input // so that we can track the progress of each input. runManager ? Array.from({ length: inputs.length }, (_, i2) => runManager.getChild(`map_${i2 + 1}`)) : void 0 ); const { outputKey } = this.llmChain; if (this.returnIntermediateSteps) { intermediateSteps = intermediateSteps.concat(results.map((r) => r[outputKey])); } currentDocs = results.map((r) => ({ pageContent: r[outputKey], metadata: {} })); } const newInputs = { [this.combineDocumentChain.inputKey]: currentDocs, ...rest }; const result = await this.combineDocumentChain.call(newInputs, runManager == null ? void 0 : runManager.getChild("combine_documents")); if (this.returnIntermediateSteps) { return { ...result, intermediateSteps }; } return result; } _chainType() { return "map_reduce_documents_chain"; } static async deserialize(data) { if (!data.llm_chain) { throw new Error("Missing llm_chain"); } if (!data.combine_document_chain) { throw new Error("Missing combine_document_chain"); } return new MapReduceDocumentsChain({ llmChain: await LLMChain.deserialize(data.llm_chain), combineDocumentChain: await StuffDocumentsChain.deserialize(data.combine_document_chain) }); } serialize() { return { _type: this._chainType(), llm_chain: this.llmChain.serialize(), combine_document_chain: this.combineDocumentChain.serialize() }; } }; RefineDocumentsChain = class extends BaseChain { get defaultDocumentPrompt() { return new PromptTemplate({ inputVariables: ["page_content"], template: "{page_content}" }); } get inputKeys() { return [ .../* @__PURE__ */ new Set([ this.inputKey, ...this.llmChain.inputKeys, ...this.refineLLMChain.inputKeys ]) ].filter((key) => key !== this.documentVariableName && key !== this.initialResponseName); } get outputKeys() { return [this.outputKey]; } constructor(fields) { var _a, _b, _c, _d, _e; super(fields); Object.defineProperty(this, "llmChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "input_documents" }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "output_text" }); Object.defineProperty(this, "documentVariableName", { enumerable: true, configurable: true, writable: true, value: "context" }); Object.defineProperty(this, "initialResponseName", { enumerable: true, configurable: true, writable: true, value: "existing_answer" }); Object.defineProperty(this, "refineLLMChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "documentPrompt", { enumerable: true, configurable: true, writable: true, value: this.defaultDocumentPrompt }); this.llmChain = fields.llmChain; this.refineLLMChain = fields.refineLLMChain; this.documentVariableName = (_a = fields.documentVariableName) != null ? _a : this.documentVariableName; this.inputKey = (_b = fields.inputKey) != null ? _b : this.inputKey; this.outputKey = (_c = fields.outputKey) != null ? _c : this.outputKey; this.documentPrompt = (_d = fields.documentPrompt) != null ? _d : this.documentPrompt; this.initialResponseName = (_e = fields.initialResponseName) != null ? _e : this.initialResponseName; } /** @ignore */ async _constructInitialInputs(doc, rest) { const baseInfo = { page_content: doc.pageContent, ...doc.metadata }; const documentInfo = {}; this.documentPrompt.inputVariables.forEach((value) => { documentInfo[value] = baseInfo[value]; }); const baseInputs = { [this.documentVariableName]: await this.documentPrompt.format({ ...documentInfo }) }; const inputs = { ...baseInputs, ...rest }; return inputs; } /** @ignore */ async _constructRefineInputs(doc, res) { const baseInfo = { page_content: doc.pageContent, ...doc.metadata }; const documentInfo = {}; this.documentPrompt.inputVariables.forEach((value) => { documentInfo[value] = baseInfo[value]; }); const baseInputs = { [this.documentVariableName]: await this.documentPrompt.format({ ...documentInfo }) }; const inputs = { [this.initialResponseName]: res, ...baseInputs }; return inputs; } /** @ignore */ async _call(values, runManager) { if (!(this.inputKey in values)) { throw new Error(`Document key ${this.inputKey} not found.`); } const { [this.inputKey]: docs, ...rest } = values; const currentDocs = docs; const initialInputs = await this._constructInitialInputs(currentDocs[0], rest); let res = await this.llmChain.predict({ ...initialInputs }, runManager == null ? void 0 : runManager.getChild("answer")); const refineSteps = [res]; for (let i = 1; i < currentDocs.length; i += 1) { const refineInputs = await this._constructRefineInputs(currentDocs[i], res); const inputs = { ...refineInputs, ...rest }; res = await this.refineLLMChain.predict({ ...inputs }, runManager == null ? void 0 : runManager.getChild("refine")); refineSteps.push(res); } return { [this.outputKey]: res }; } _chainType() { return "refine_documents_chain"; } static async deserialize(data) { const SerializedLLMChain = data.llm_chain; if (!SerializedLLMChain) { throw new Error("Missing llm_chain"); } const SerializedRefineDocumentChain = data.refine_llm_chain; if (!SerializedRefineDocumentChain) { throw new Error("Missing refine_llm_chain"); } return new RefineDocumentsChain({ llmChain: await LLMChain.deserialize(SerializedLLMChain), refineLLMChain: await LLMChain.deserialize(SerializedRefineDocumentChain) }); } serialize() { return { _type: this._chainType(), llm_chain: this.llmChain.serialize(), refine_llm_chain: this.refineLLMChain.serialize() }; } }; } }); // node_modules/langchain/dist/prompts/chat.js var BaseMessagePromptTemplate, ChatPromptValue, MessagesPlaceholder, BaseMessageStringPromptTemplate, BaseChatPromptTemplate, HumanMessagePromptTemplate, AIMessagePromptTemplate, SystemMessagePromptTemplate, ChatPromptTemplate; var init_chat = __esm({ "node_modules/langchain/dist/prompts/chat.js"() { init_schema(); init_serializable(); init_base4(); init_prompt(); BaseMessagePromptTemplate = class extends Serializable { constructor() { super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "prompts", "chat"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); } }; ChatPromptValue = class extends BasePromptValue { constructor(fields) { if (Array.isArray(fields)) { fields = { messages: fields }; } super(...arguments); Object.defineProperty(this, "lc_namespace", { enumerable: true, configurable: true, writable: true, value: ["langchain", "prompts", "chat"] }); Object.defineProperty(this, "lc_serializable", { enumerable: true, configurable: true, writable: true, value: true }); Object.defineProperty(this, "messages", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.messages = fields.messages; } toString() { return JSON.stringify(this.messages); } toChatMessages() { return this.messages; } }; MessagesPlaceholder = class extends BaseMessagePromptTemplate { constructor(fields) { if (typeof fields === "string") { fields = { variableName: fields }; } super(fields); Object.defineProperty(this, "variableName", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.variableName = fields.variableName; } get inputVariables() { return [this.variableName]; } formatMessages(values) { return Promise.resolve(values[this.variableName]); } }; BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { constructor(fields) { if (!("prompt" in fields)) { fields = { prompt: fields }; } super(fields); Object.defineProperty(this, "prompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.prompt = fields.prompt; } get inputVariables() { return this.prompt.inputVariables; } async formatMessages(values) { return [await this.format(values)]; } }; BaseChatPromptTemplate = class extends BasePromptTemplate { constructor(input) { super(input); } async format(values) { return (await this.formatPromptValue(values)).toString(); } async formatPromptValue(values) { const resultMessages = await this.formatMessages(values); return new ChatPromptValue(resultMessages); } }; HumanMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { async format(values) { return new HumanMessage(await this.prompt.format(values)); } static fromTemplate(template) { return new this(PromptTemplate.fromTemplate(template)); } }; AIMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { async format(values) { return new AIMessage(await this.prompt.format(values)); } static fromTemplate(template) { return new this(PromptTemplate.fromTemplate(template)); } }; SystemMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { async format(values) { return new SystemMessage(await this.prompt.format(values)); } static fromTemplate(template) { return new this(PromptTemplate.fromTemplate(template)); } }; ChatPromptTemplate = class extends BaseChatPromptTemplate { get lc_aliases() { return { promptMessages: "messages" }; } constructor(input) { super(input); Object.defineProperty(this, "promptMessages", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "validateTemplate", { enumerable: true, configurable: true, writable: true, value: true }); Object.assign(this, input); if (this.validateTemplate) { const inputVariablesMessages = /* @__PURE__ */ new Set(); for (const promptMessage of this.promptMessages) { for (const inputVariable of promptMessage.inputVariables) { inputVariablesMessages.add(inputVariable); } } const inputVariablesInstance = new Set(this.partialVariables ? this.inputVariables.concat(Object.keys(this.partialVariables)) : this.inputVariables); const difference2 = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); if (difference2.size > 0) { throw new Error(`Input variables \`${[ ...difference2 ]}\` are not used in any of the prompt messages.`); } const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); if (otherDifference.size > 0) { throw new Error(`Input variables \`${[ ...otherDifference ]}\` are used in prompt messages but not in the prompt template.`); } } } _getPromptType() { return "chat"; } async formatMessages(values) { const allValues = await this.mergePartialAndUserVariables(values); let resultMessages = []; for (const promptMessage of this.promptMessages) { const inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { if (!(inputVariable in allValues)) { throw new Error(`Missing value for input variable \`${inputVariable}\``); } acc[inputVariable] = allValues[inputVariable]; return acc; }, {}); const message = await promptMessage.formatMessages(inputValues); resultMessages = resultMessages.concat(message); } return resultMessages; } async partial(values) { var _a; const promptDict = { ...this }; promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); promptDict.partialVariables = { ...(_a = this.partialVariables) != null ? _a : {}, ...values }; return new ChatPromptTemplate(promptDict); } static fromPromptMessages(promptMessages) { const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat( // eslint-disable-next-line no-instanceof/no-instanceof promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [promptMessage] ), []); const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => ( // eslint-disable-next-line no-instanceof/no-instanceof promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc ), /* @__PURE__ */ Object.create(null)); const inputVariables = /* @__PURE__ */ new Set(); for (const promptMessage of flattenedMessages) { for (const inputVariable of promptMessage.inputVariables) { if (inputVariable in flattenedPartialVariables) { continue; } inputVariables.add(inputVariable); } } return new ChatPromptTemplate({ inputVariables: [...inputVariables], promptMessages: flattenedMessages, partialVariables: flattenedPartialVariables }); } }; } }); // node_modules/langchain/dist/prompts/selectors/conditional.js function isChatModel(llm) { return llm._modelType() === "base_chat_model"; } var BasePromptSelector, ConditionalPromptSelector; var init_conditional = __esm({ "node_modules/langchain/dist/prompts/selectors/conditional.js"() { BasePromptSelector = class { async getPromptAsync(llm, options) { var _a; const prompt = this.getPrompt(llm); return prompt.partial((_a = options == null ? void 0 : options.partialVariables) != null ? _a : {}); } }; ConditionalPromptSelector = class extends BasePromptSelector { constructor(default_prompt, conditionals = []) { super(); Object.defineProperty(this, "defaultPrompt", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "conditionals", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.defaultPrompt = default_prompt; this.conditionals = conditionals; } getPrompt(llm) { for (const [condition, prompt] of this.conditionals) { if (condition(llm)) { return prompt; } } return this.defaultPrompt; } }; } }); // node_modules/langchain/dist/chains/question_answering/stuff_prompts.js var DEFAULT_QA_PROMPT, system_template, messages, CHAT_PROMPT, QA_PROMPT_SELECTOR; var init_stuff_prompts = __esm({ "node_modules/langchain/dist/chains/question_answering/stuff_prompts.js"() { init_prompt(); init_chat(); init_conditional(); DEFAULT_QA_PROMPT = /* @__PURE__ */ new PromptTemplate({ template: "Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.\n\n{context}\n\nQuestion: {question}\nHelpful Answer:", inputVariables: ["context", "question"] }); system_template = `Use the following pieces of context to answer the users question. If you don't know the answer, just say that you don't know, don't try to make up an answer. ---------------- {context}`; messages = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(system_template), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromPromptMessages(messages); QA_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_QA_PROMPT, [[isChatModel, CHAT_PROMPT]]); } }); // node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js var qa_template, DEFAULT_COMBINE_QA_PROMPT, system_template2, messages2, CHAT_QA_PROMPT, COMBINE_QA_PROMPT_SELECTOR, combine_prompt, COMBINE_PROMPT, system_combine_template, combine_messages, CHAT_COMBINE_PROMPT, COMBINE_PROMPT_SELECTOR; var init_map_reduce_prompts = __esm({ "node_modules/langchain/dist/chains/question_answering/map_reduce_prompts.js"() { init_prompt(); init_chat(); init_conditional(); qa_template = `Use the following portion of a long document to see if any of the text is relevant to answer the question. Return any relevant text verbatim. {context} Question: {question} Relevant text, if any:`; DEFAULT_COMBINE_QA_PROMPT = /* @__PURE__ */ PromptTemplate.fromTemplate(qa_template); system_template2 = `Use the following portion of a long document to see if any of the text is relevant to answer the question. Return any relevant text verbatim. ---------------- {context}`; messages2 = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(system_template2), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_QA_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromPromptMessages(messages2); COMBINE_QA_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_COMBINE_QA_PROMPT, [ [isChatModel, CHAT_QA_PROMPT] ]); combine_prompt = `Given the following extracted parts of a long document and a question, create a final answer. If you don't know the answer, just say that you don't know. Don't try to make up an answer. QUESTION: Which state/country's law governs the interpretation of the contract? ========= Content: This Agreement is governed by English law and the parties submit to the exclusive jurisdiction of the English courts in relation to any dispute (contractual or non-contractual) concerning this Agreement save that either party may apply to any court for an injunction or other relief to protect its Intellectual Property Rights. Content: No Waiver. Failure or delay in exercising any right or remedy under this Agreement shall not constitute a waiver of such (or any other) right or remedy. 11.7 Severability. The invalidity, illegality or unenforceability of any term (or part of a term) of this Agreement shall not affect the continuation in force of the remainder of the term (if any) and this Agreement. 11.8 No Agency. Except as expressly stated otherwise, nothing in this Agreement shall create an agency, partnership or joint venture of any kind between the parties. 11.9 No Third-Party Beneficiaries. Content: (b) if Google believes, in good faith, that the Distributor has violated or caused Google to violate any Anti-Bribery Laws (as defined in Clause 8.5) or that such a violation is reasonably likely to occur, ========= FINAL ANSWER: This Agreement is governed by English law. QUESTION: What did the president say about Michael Jackson? ========= Content: Madam Speaker, Madam Vice President, our First Lady and Second Gentleman. Members of Congress and the Cabinet. Justices of the Supreme Court. My fellow Americans. Last year COVID-19 kept us apart. This year we are finally together again. Tonight, we meet as Democrats Republicans and Independents. But most importantly as Americans. With a duty to one another to the American people to the Constitution. And with an unwavering resolve that freedom will always triumph over tyranny. Six days ago, Russia\u2019s Vladimir Putin sought to shake the foundations of the free world thinking he could make it bend to his menacing ways. But he badly miscalculated. He thought he could roll into Ukraine and the world would roll over. Instead he met a wall of strength he never imagined. He met the Ukrainian people. From President Zelenskyy to every Ukrainian, their fearlessness, their courage, their determination, inspires the world. Groups of citizens blocking tanks with their bodies. Everyone from students to retirees teachers turned soldiers defending their homeland. Content: And we won\u2019t stop. We have lost so much to COVID-19. Time with one another. And worst of all, so much loss of life. Let\u2019s use this moment to reset. Let\u2019s stop looking at COVID-19 as a partisan dividing line and see it for what it is: A God-awful disease. Let\u2019s stop seeing each other as enemies, and start seeing each other for who we really are: Fellow Americans. We can\u2019t change how divided we\u2019ve been. But we can change how we move forward\u2014on COVID-19 and other issues we must face together. I recently visited the New York City Police Department days after the funerals of Officer Wilbert Mora and his partner, Officer Jason Rivera. They were responding to a 9-1-1 call when a man shot and killed them with a stolen gun. Officer Mora was 27 years old. Officer Rivera was 22. Both Dominican Americans who\u2019d grown up on the same streets they later chose to patrol as police officers. I spoke with their families and told them that we are forever in debt for their sacrifice, and we will carry on their mission to restore the trust and safety every community deserves. Content: And a proud Ukrainian people, who have known 30 years of independence, have repeatedly shown that they will not tolerate anyone who tries to take their country backwards. To all Americans, I will be honest with you, as I\u2019ve always promised. A Russian dictator, invading a foreign country, has costs around the world. And I\u2019m taking robust action to make sure the pain of our sanctions is targeted at Russia\u2019s economy. And I will use every tool at our disposal to protect American businesses and consumers. Tonight, I can announce that the United States has worked with 30 other countries to release 60 Million barrels of oil from reserves around the world. America will lead that effort, releasing 30 Million barrels from our own Strategic Petroleum Reserve. And we stand ready to do more if necessary, unified with our allies. These steps will help blunt gas prices here at home. And I know the news about what\u2019s happening can seem alarming. But I want you to know that we are going to be okay. Content: More support for patients and families. To get there, I call on Congress to fund ARPA-H, the Advanced Research Projects Agency for Health. It\u2019s based on DARPA\u2014the Defense Department project that led to the Internet, GPS, and so much more. ARPA-H will have a singular purpose\u2014to drive breakthroughs in cancer, Alzheimer\u2019s, diabetes, and more. A unity agenda for the nation. We can do this. My fellow Americans\u2014tonight , we have gathered in a sacred space\u2014the citadel of our democracy. In this Capitol, generation after generation, Americans have debated great questions amid great strife, and have done great things. We have fought for freedom, expanded liberty, defeated totalitarianism and terror. And built the strongest, freest, and most prosperous nation the world has ever known. Now is the hour. Our moment of responsibility. Our test of resolve and conscience, of history itself. It is in this moment that our character is formed. Our purpose is found. Our future is forged. Well I know this nation. ========= FINAL ANSWER: The president did not mention Michael Jackson. QUESTION: {question} ========= {summaries} ========= FINAL ANSWER:`; COMBINE_PROMPT = /* @__PURE__ */ PromptTemplate.fromTemplate(combine_prompt); system_combine_template = `Given the following extracted parts of a long document and a question, create a final answer. If you don't know the answer, just say that you don't know. Don't try to make up an answer. ---------------- {summaries}`; combine_messages = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(system_combine_template), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_COMBINE_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromPromptMessages(combine_messages); COMBINE_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(COMBINE_PROMPT, [ [isChatModel, CHAT_COMBINE_PROMPT] ]); } }); // node_modules/langchain/dist/prompts/selectors/LengthBasedExampleSelector.js var init_LengthBasedExampleSelector = __esm({ "node_modules/langchain/dist/prompts/selectors/LengthBasedExampleSelector.js"() { init_base4(); } }); // node_modules/langchain/dist/document.js var Document; var init_document = __esm({ "node_modules/langchain/dist/document.js"() { Document = class { constructor(fields) { var _a; Object.defineProperty(this, "pageContent", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "metadata", { enumerable: true, configurable: true, writable: true, value: void 0 }); this.pageContent = fields.pageContent ? fields.pageContent.toString() : this.pageContent; this.metadata = (_a = fields.metadata) != null ? _a : {}; } }; } }); // node_modules/langchain/dist/prompts/selectors/SemanticSimilarityExampleSelector.js var init_SemanticSimilarityExampleSelector = __esm({ "node_modules/langchain/dist/prompts/selectors/SemanticSimilarityExampleSelector.js"() { init_document(); init_base4(); } }); // node_modules/langchain/dist/prompts/pipeline.js var init_pipeline = __esm({ "node_modules/langchain/dist/prompts/pipeline.js"() { init_base4(); init_chat(); } }); // node_modules/langchain/dist/prompts/index.js var init_prompts = __esm({ "node_modules/langchain/dist/prompts/index.js"() { init_base4(); init_prompt(); init_conditional(); init_LengthBasedExampleSelector(); init_SemanticSimilarityExampleSelector(); init_few_shot(); init_chat(); init_template(); init_pipeline(); } }); // node_modules/langchain/dist/chains/question_answering/refine_prompts.js var DEFAULT_REFINE_PROMPT_TMPL, DEFAULT_REFINE_PROMPT, refineTemplate, messages3, CHAT_REFINE_PROMPT, REFINE_PROMPT_SELECTOR, DEFAULT_TEXT_QA_PROMPT_TMPL, DEFAULT_TEXT_QA_PROMPT, chat_qa_prompt_template, chat_messages, CHAT_QUESTION_PROMPT, QUESTION_PROMPT_SELECTOR; var init_refine_prompts = __esm({ "node_modules/langchain/dist/chains/question_answering/refine_prompts.js"() { init_prompts(); init_conditional(); DEFAULT_REFINE_PROMPT_TMPL = `The original question is as follows: {question} We have provided an existing answer: {existing_answer} We have the opportunity to refine the existing answer (only if needed) with some more context below. ------------ {context} ------------ Given the new context, refine the original answer to better answer the question. If the context isn't useful, return the original answer.`; DEFAULT_REFINE_PROMPT = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["question", "existing_answer", "context"], template: DEFAULT_REFINE_PROMPT_TMPL }); refineTemplate = `The original question is as follows: {question} We have provided an existing answer: {existing_answer} We have the opportunity to refine the existing answer (only if needed) with some more context below. ------------ {context} ------------ Given the new context, refine the original answer to better answer the question. If the context isn't useful, return the original answer.`; messages3 = [ /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}"), /* @__PURE__ */ AIMessagePromptTemplate.fromTemplate("{existing_answer}"), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate(refineTemplate) ]; CHAT_REFINE_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromPromptMessages(messages3); REFINE_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_REFINE_PROMPT, [ [isChatModel, CHAT_REFINE_PROMPT] ]); DEFAULT_TEXT_QA_PROMPT_TMPL = `Context information is below. --------------------- {context} --------------------- Given the context information and not prior knowledge, answer the question: {question}`; DEFAULT_TEXT_QA_PROMPT = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["context", "question"], template: DEFAULT_TEXT_QA_PROMPT_TMPL }); chat_qa_prompt_template = `Context information is below. --------------------- {context} --------------------- Given the context information and not prior knowledge, answer any questions`; chat_messages = [ /* @__PURE__ */ SystemMessagePromptTemplate.fromTemplate(chat_qa_prompt_template), /* @__PURE__ */ HumanMessagePromptTemplate.fromTemplate("{question}") ]; CHAT_QUESTION_PROMPT = /* @__PURE__ */ ChatPromptTemplate.fromPromptMessages(chat_messages); QUESTION_PROMPT_SELECTOR = /* @__PURE__ */ new ConditionalPromptSelector(DEFAULT_TEXT_QA_PROMPT, [ [isChatModel, CHAT_QUESTION_PROMPT] ]); } }); // node_modules/langchain/dist/chains/question_answering/load.js function loadQAStuffChain(llm, params = {}) { const { prompt = QA_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; const llmChain = new LLMChain({ prompt, llm, verbose }); const chain = new StuffDocumentsChain({ llmChain, verbose }); return chain; } function loadQAMapReduceChain(llm, params = {}) { const { combineMapPrompt = COMBINE_QA_PROMPT_SELECTOR.getPrompt(llm), combinePrompt = COMBINE_PROMPT_SELECTOR.getPrompt(llm), verbose, returnIntermediateSteps } = params; const llmChain = new LLMChain({ prompt: combineMapPrompt, llm, verbose }); const combineLLMChain = new LLMChain({ prompt: combinePrompt, llm, verbose }); const combineDocumentChain = new StuffDocumentsChain({ llmChain: combineLLMChain, documentVariableName: "summaries", verbose }); const chain = new MapReduceDocumentsChain({ llmChain, combineDocumentChain, returnIntermediateSteps, verbose }); return chain; } function loadQARefineChain(llm, params = {}) { const { questionPrompt = QUESTION_PROMPT_SELECTOR.getPrompt(llm), refinePrompt = REFINE_PROMPT_SELECTOR.getPrompt(llm), verbose } = params; const llmChain = new LLMChain({ prompt: questionPrompt, llm, verbose }); const refineLLMChain = new LLMChain({ prompt: refinePrompt, llm, verbose }); const chain = new RefineDocumentsChain({ llmChain, refineLLMChain, verbose }); return chain; } var loadQAChain; var init_load = __esm({ "node_modules/langchain/dist/chains/question_answering/load.js"() { init_llm_chain(); init_combine_docs_chain(); init_stuff_prompts(); init_map_reduce_prompts(); init_refine_prompts(); loadQAChain = (llm, params = { type: "stuff" }) => { const { type: type2 } = params; if (type2 === "stuff") { return loadQAStuffChain(llm, params); } if (type2 === "map_reduce") { return loadQAMapReduceChain(llm, params); } if (type2 === "refine") { return loadQARefineChain(llm, params); } throw new Error(`Invalid _type: ${type2}`); }; } }); // node_modules/langchain/dist/chains/vector_db_qa.js var vector_db_qa_exports = {}; __export(vector_db_qa_exports, { VectorDBQAChain: () => VectorDBQAChain }); var VectorDBQAChain; var init_vector_db_qa = __esm({ "node_modules/langchain/dist/chains/vector_db_qa.js"() { init_base5(); init_load(); VectorDBQAChain = class extends BaseChain { get inputKeys() { return [this.inputKey]; } get outputKeys() { return this.combineDocumentsChain.outputKeys.concat(this.returnSourceDocuments ? ["sourceDocuments"] : []); } constructor(fields) { var _a, _b, _c; super(fields); Object.defineProperty(this, "k", { enumerable: true, configurable: true, writable: true, value: 4 }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "query" }); Object.defineProperty(this, "vectorstore", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "combineDocumentsChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "returnSourceDocuments", { enumerable: true, configurable: true, writable: true, value: false }); this.vectorstore = fields.vectorstore; this.combineDocumentsChain = fields.combineDocumentsChain; this.inputKey = (_a = fields.inputKey) != null ? _a : this.inputKey; this.k = (_b = fields.k) != null ? _b : this.k; this.returnSourceDocuments = (_c = fields.returnSourceDocuments) != null ? _c : this.returnSourceDocuments; } /** @ignore */ async _call(values, runManager) { if (!(this.inputKey in values)) { throw new Error(`Question key ${this.inputKey} not found.`); } const question = values[this.inputKey]; const docs = await this.vectorstore.similaritySearch(question, this.k, values.filter); const inputs = { question, input_documents: docs }; const result = await this.combineDocumentsChain.call(inputs, runManager == null ? void 0 : runManager.getChild("combine_documents")); if (this.returnSourceDocuments) { return { ...result, sourceDocuments: docs }; } return result; } _chainType() { return "vector_db_qa"; } static async deserialize(data, values) { if (!("vectorstore" in values)) { throw new Error(`Need to pass in a vectorstore to deserialize VectorDBQAChain`); } const { vectorstore } = values; if (!data.combine_documents_chain) { throw new Error(`VectorDBQAChain must have combine_documents_chain in serialized data`); } return new VectorDBQAChain({ combineDocumentsChain: await BaseChain.deserialize(data.combine_documents_chain), k: data.k, vectorstore }); } serialize() { return { _type: this._chainType(), combine_documents_chain: this.combineDocumentsChain.serialize(), k: this.k }; } static fromLLM(llm, vectorstore, options) { const qaChain = loadQAStuffChain(llm); return new this({ vectorstore, combineDocumentsChain: qaChain, ...options }); } }; } }); // node_modules/langchain/dist/chains/api/prompts.js var API_URL_RAW_PROMPT_TEMPLATE, API_URL_PROMPT_TEMPLATE, API_RESPONSE_RAW_PROMPT_TEMPLATE, API_RESPONSE_PROMPT_TEMPLATE; var init_prompts2 = __esm({ "node_modules/langchain/dist/chains/api/prompts.js"() { init_prompt(); API_URL_RAW_PROMPT_TEMPLATE = `You are given the below API Documentation: {api_docs} Using this documentation, generate the full API url to call for answering the user question. You should build the API url in order to get a response that is as short as possible, while still getting the necessary information to answer the question. Pay attention to deliberately exclude any unnecessary pieces of data in the API call. Question:{question} API url:`; API_URL_PROMPT_TEMPLATE = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["api_docs", "question"], template: API_URL_RAW_PROMPT_TEMPLATE }); API_RESPONSE_RAW_PROMPT_TEMPLATE = `${API_URL_RAW_PROMPT_TEMPLATE} {api_url} Here is the response from the API: {api_response} Summarize this response to answer the original question. Summary:`; API_RESPONSE_PROMPT_TEMPLATE = /* @__PURE__ */ new PromptTemplate({ inputVariables: ["api_docs", "question", "api_url", "api_response"], template: API_RESPONSE_RAW_PROMPT_TEMPLATE }); } }); // node_modules/langchain/dist/chains/api/api_chain.js var api_chain_exports = {}; __export(api_chain_exports, { APIChain: () => APIChain }); var APIChain; var init_api_chain = __esm({ "node_modules/langchain/dist/chains/api/api_chain.js"() { init_base5(); init_llm_chain(); init_prompts2(); APIChain = class extends BaseChain { get inputKeys() { return [this.inputKey]; } get outputKeys() { return [this.outputKey]; } constructor(fields) { var _a, _b, _c; super(fields); Object.defineProperty(this, "apiAnswerChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "apiRequestChain", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "apiDocs", { enumerable: true, configurable: true, writable: true, value: void 0 }); Object.defineProperty(this, "headers", { enumerable: true, configurable: true, writable: true, value: {} }); Object.defineProperty(this, "inputKey", { enumerable: true, configurable: true, writable: true, value: "question" }); Object.defineProperty(this, "outputKey", { enumerable: true, configurable: true, writable: true, value: "output" }); this.apiRequestChain = fields.apiRequestChain; this.apiAnswerChain = fields.apiAnswerChain; this.apiDocs = fields.apiDocs; this.inputKey = (_a = fields.inputKey) != null ? _a : this.inputKey; this.outputKey = (_b = fields.outputKey) != null ? _b : this.outputKey; this.headers = (_c = fields.headers) != null ? _c : this.headers; } /** @ignore */ async _call(values, runManager) { const question = values[this.inputKey]; const api_url = await this.apiRequestChain.predict({ question, api_docs: this.apiDocs }, runManager == null ? void 0 : runManager.getChild("request")); const res = await fetch(api_url, { headers: this.headers }); const api_response = await res.text(); const answer = await this.apiAnswerChain.predict({ question, api_docs: this.apiDocs, api_url, api_response }, runManager == null ? void 0 : runManager.getChild("response")); return { [this.outputKey]: answer }; } _chainType() { return "api_chain"; } static async deserialize(data) { const { api_request_chain, api_answer_chain, api_docs } = data; if (!api_request_chain) { throw new Error("LLMChain must have api_request_chain"); } if (!api_answer_chain) { throw new Error("LLMChain must have api_answer_chain"); } if (!api_docs) { throw new Error("LLMChain must have api_docs"); } return new APIChain({ apiAnswerChain: await LLMChain.deserialize(api_answer_chain), apiRequestChain: await LLMChain.deserialize(api_request_chain), apiDocs: api_docs }); } serialize() { return { _type: this._chainType(), api_answer_chain: this.apiAnswerChain.serialize(), api_request_chain: this.apiRequestChain.serialize(), api_docs: this.apiDocs }; } static fromLLMAndAPIDocs(llm, apiDocs, options = {}) { const { apiUrlPrompt = API_URL_PROMPT_TEMPLATE, apiResponsePrompt = API_RESPONSE_PROMPT_TEMPLATE } = options; const apiRequestChain = new LLMChain({ prompt: apiUrlPrompt, llm }); const apiAnswerChain = new LLMChain({ prompt: apiResponsePrompt, llm }); return new this({ apiAnswerChain, apiRequestChain, apiDocs, ...options }); } }; } }); // node_modules/langchain/dist/chains/base.js var BaseChain; var init_base5 = __esm({ "node_modules/langchain/dist/chains/base.js"() { init_schema(); init_manager(); init_base_language(); BaseChain = class extends BaseLangChain { get lc_namespace() { return ["langchain", "chains", this._chainType()]; } constructor(fields, verbose, callbacks) { if (arguments.length === 1 && typeof fields === "object" && !("saveContext" in fields)) { const { memory, callbackManager, ...rest } = fields; super({ ...rest, callbacks: callbackManager != null ? callbackManager : rest.callbacks }); this.memory = memory; } else { super({ verbose, callbacks }); this.memory = fields; } } /** @ignore */ _selectMemoryInputs(values) { const valuesForMemory = { ...values }; if ("signal" in valuesForMemory) { delete valuesForMemory.signal; } if ("timeout" in valuesForMemory) { delete valuesForMemory.timeout; } return valuesForMemory; } /** * Return a json-like object representing this chain. */ serialize() { throw new Error("Method not implemented."); } async run(input, config) { const inputKeys = this.inputKeys.filter((k) => { var _a; return !((_a = this.memory) == null ? void 0 : _a.memoryKeys.includes(k)); }); const isKeylessInput = inputKeys.length <= 1; if (!isKeylessInput) { throw new Error(`Chain ${this._chainType()} expects multiple inputs, cannot use 'run' `); } const values = inputKeys.length ? { [inputKeys[0]]: input } : {}; const returnValues = await this.call(values, config); const keys3 = Object.keys(returnValues); if (keys3.length === 1) { return returnValues[keys3[0]]; } throw new Error("return values have multiple keys, `run` only supported when one key currently"); } /** * Run the core logic of this chain and add to output if desired. * * Wraps _call and handles memory. */ async call(values, config, tags) { const fullValues = { ...values }; if (fullValues.timeout && !fullValues.signal) { fullValues.signal = AbortSignal.timeout(fullValues.timeout); delete fullValues.timeout; } if (!(this.memory == null)) { const newValues = await this.memory.loadMemoryVariables(this._selectMemoryInputs(values)); for (const [key, value] of Object.entries(newValues)) { fullValues[key] = value; } } const parsedConfig = parseCallbackConfigArg(config); const callbackManager_ = await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags || tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); const runManager = await (callbackManager_ == null ? void 0 : callbackManager_.handleChainStart(this.toJSON(), fullValues)); let outputValues; try { outputValues = await (values.signal ? Promise.race([ this._call(fullValues, runManager), new Promise((_, reject) => { var _a; (_a = values.signal) == null ? void 0 : _a.addEventListener("abort", () => { reject(new Error("AbortError")); }); }) ]) : this._call(fullValues, runManager)); } catch (e) { await (runManager == null ? void 0 : runManager.handleChainError(e)); throw e; } if (!(this.memory == null)) { await this.memory.saveContext(this._selectMemoryInputs(values), outputValues); } await (runManager == null ? void 0 : runManager.handleChainEnd(outputValues)); Object.defineProperty(outputValues, RUN_KEY, { value: runManager ? { runId: runManager == null ? void 0 : runManager.runId } : void 0, configurable: true }); return outputValues; } /** * Call the chain on all inputs in the list */ async apply(inputs, config) { return Promise.all(inputs.map(async (i, idx) => this.call(i, config == null ? void 0 : config[idx]))); } /** * Load a chain from a json-like object describing it. */ static async deserialize(data, values = {}) { switch (data._type) { case "llm_chain": { const { LLMChain: LLMChain2 } = await Promise.resolve().then(() => (init_llm_chain(), llm_chain_exports)); return LLMChain2.deserialize(data); } case "sequential_chain": { const { SequentialChain: SequentialChain2 } = await Promise.resolve().then(() => (init_sequential_chain(), sequential_chain_exports)); return SequentialChain2.deserialize(data); } case "simple_sequential_chain": { const { SimpleSequentialChain: SimpleSequentialChain2 } = await Promise.resolve().then(() => (init_sequential_chain(), sequential_chain_exports)); return SimpleSequentialChain2.deserialize(data); } case "stuff_documents_chain": { const { StuffDocumentsChain: StuffDocumentsChain2 } = await Promise.resolve().then(() => (init_combine_docs_chain(), combine_docs_chain_exports)); return StuffDocumentsChain2.deserialize(data); } case "map_reduce_documents_chain": { const { MapReduceDocumentsChain: MapReduceDocumentsChain2 } = await Promise.resolve().then(() => (init_combine_docs_chain(), combine_docs_chain_exports)); return MapReduceDocumentsChain2.deserialize(data); } case "refine_documents_chain": { const { RefineDocumentsChain: RefineDocumentsChain2 } = await Promise.resolve().then(() => (init_combine_docs_chain(), combine_docs_chain_exports)); return RefineDocumentsChain2.deserialize(data); } case "vector_db_qa": { const { VectorDBQAChain: VectorDBQAChain2 } = await Promise.resolve().then(() => (init_vector_db_qa(), vector_db_qa_exports)); return VectorDBQAChain2.deserialize(data, values); } case "api_chain": { const { APIChain: APIChain2 } = await Promise.resolve().then(() => (init_api_chain(), api_chain_exports)); return APIChain2.deserialize(data); } default: throw new Error(`Invalid prompt type in config: ${data._type}`); } } }; } }); // node_modules/moment/moment.js var require_moment = __commonJS({ "node_modules/moment/moment.js"(exports, module2) { (function(global2, factory) { typeof exports === "object" && typeof module2 !== "undefined" ? module2.exports = factory() : typeof define === "function" && define.amd ? define(factory) : global2.moment = factory(); })(exports, function() { "use strict"; var hookCallback; function hooks() { return hookCallback.apply(null, arguments); } function setHookCallback(callback) { hookCallback = callback; } function isArray4(input) { return input instanceof Array || Object.prototype.toString.call(input) === "[object Array]"; } function isObject4(input) { return input != null && Object.prototype.toString.call(input) === "[object Object]"; } function hasOwnProp(a2, b) { return Object.prototype.hasOwnProperty.call(a2, b); } function isObjectEmpty(obj) { if (Object.getOwnPropertyNames) { return Object.getOwnPropertyNames(obj).length === 0; } else { var k; for (k in obj) { if (hasOwnProp(obj, k)) { return false; } } return true; } } function isUndefined3(input) { return input === void 0; } function isNumber2(input) { return typeof input === "number" || Object.prototype.toString.call(input) === "[object Number]"; } function isDate3(input) { return input instanceof Date || Object.prototype.toString.call(input) === "[object Date]"; } function map2(arr, fn) { var res = [], i, arrLen = arr.length; for (i = 0; i < arrLen; ++i) { res.push(fn(arr[i], i)); } return res; } function extend5(a2, b) { for (var i in b) { if (hasOwnProp(b, i)) { a2[i] = b[i]; } } if (hasOwnProp(b, "toString")) { a2.toString = b.toString; } if (hasOwnProp(b, "valueOf")) { a2.valueOf = b.valueOf; } return a2; } function createUTC(input, format2, locale2, strict) { return createLocalOrUTC(input, format2, locale2, strict, true).utc(); } function defaultParsingFlags() { return { empty: false, unusedTokens: [], unusedInput: [], overflow: -2, charsLeftOver: 0, nullInput: false, invalidEra: null, invalidMonth: null, invalidFormat: false, userInvalidated: false, iso: false, parsedDateParts: [], era: null, meridiem: null, rfc2822: false, weekdayMismatch: false }; } function getParsingFlags(m) { if (m._pf == null) { m._pf = defaultParsingFlags(); } return m._pf; } var some; if (Array.prototype.some) { some = Array.prototype.some; } else { some = function(fun) { var t = Object(this), len = t.length >>> 0, i; for (i = 0; i < len; i++) { if (i in t && fun.call(this, t[i], i, t)) { return true; } } return false; }; } function isValid(m) { if (m._isValid == null) { var flags = getParsingFlags(m), parsedParts = some.call(flags.parsedDateParts, function(i) { return i != null; }), isNowValid = !isNaN(m._d.getTime()) && flags.overflow < 0 && !flags.empty && !flags.invalidEra && !flags.invalidMonth && !flags.invalidWeekday && !flags.weekdayMismatch && !flags.nullInput && !flags.invalidFormat && !flags.userInvalidated && (!flags.meridiem || flags.meridiem && parsedParts); if (m._strict) { isNowValid = isNowValid && flags.charsLeftOver === 0 && flags.unusedTokens.length === 0 && flags.bigHour === void 0; } if (Object.isFrozen == null || !Object.isFrozen(m)) { m._isValid = isNowValid; } else { return isNowValid; } } return m._isValid; } function createInvalid(flags) { var m = createUTC(NaN); if (flags != null) { extend5(getParsingFlags(m), flags); } else { getParsingFlags(m).userInvalidated = true; } return m; } var momentProperties = hooks.momentProperties = [], updateInProgress = false; function copyConfig(to2, from2) { var i, prop, val, momentPropertiesLen = momentProperties.length; if (!isUndefined3(from2._isAMomentObject)) { to2._isAMomentObject = from2._isAMomentObject; } if (!isUndefined3(from2._i)) { to2._i = from2._i; } if (!isUndefined3(from2._f)) { to2._f = from2._f; } if (!isUndefined3(from2._l)) { to2._l = from2._l; } if (!isUndefined3(from2._strict)) { to2._strict = from2._strict; } if (!isUndefined3(from2._tzm)) { to2._tzm = from2._tzm; } if (!isUndefined3(from2._isUTC)) { to2._isUTC = from2._isUTC; } if (!isUndefined3(from2._offset)) { to2._offset = from2._offset; } if (!isUndefined3(from2._pf)) { to2._pf = getParsingFlags(from2); } if (!isUndefined3(from2._locale)) { to2._locale = from2._locale; } if (momentPropertiesLen > 0) { for (i = 0; i < momentPropertiesLen; i++) { prop = momentProperties[i]; val = from2[prop]; if (!isUndefined3(val)) { to2[prop] = val; } } } return to2; } function Moment(config) { copyConfig(this, config); this._d = new Date(config._d != null ? config._d.getTime() : NaN); if (!this.isValid()) { this._d = new Date(NaN); } if (updateInProgress === false) { updateInProgress = true; hooks.updateOffset(this); updateInProgress = false; } } function isMoment(obj) { return obj instanceof Moment || obj != null && obj._isAMomentObject != null; } function warn(msg) { if (hooks.suppressDeprecationWarnings === false && typeof console !== "undefined" && console.warn) { console.warn("Deprecation warning: " + msg); } } function deprecate(msg, fn) { var firstTime = true; return extend5(function() { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(null, msg); } if (firstTime) { var args = [], arg, i, key, argLen = arguments.length; for (i = 0; i < argLen; i++) { arg = ""; if (typeof arguments[i] === "object") { arg += "\n[" + i + "] "; for (key in arguments[0]) { if (hasOwnProp(arguments[0], key)) { arg += key + ": " + arguments[0][key] + ", "; } } arg = arg.slice(0, -2); } else { arg = arguments[i]; } args.push(arg); } warn( msg + "\nArguments: " + Array.prototype.slice.call(args).join("") + "\n" + new Error().stack ); firstTime = false; } return fn.apply(this, arguments); }, fn); } var deprecations = {}; function deprecateSimple(name, msg) { if (hooks.deprecationHandler != null) { hooks.deprecationHandler(name, msg); } if (!deprecations[name]) { warn(msg); deprecations[name] = true; } } hooks.suppressDeprecationWarnings = false; hooks.deprecationHandler = null; function isFunction2(input) { return typeof Function !== "undefined" && input instanceof Function || Object.prototype.toString.call(input) === "[object Function]"; } function set2(config) { var prop, i; for (i in config) { if (hasOwnProp(config, i)) { prop = config[i]; if (isFunction2(prop)) { this[i] = prop; } else { this["_" + i] = prop; } } } this._config = config; this._dayOfMonthOrdinalParseLenient = new RegExp( (this._dayOfMonthOrdinalParse.source || this._ordinalParse.source) + "|" + /\d{1,2}/.source ); } function mergeConfigs(parentConfig, childConfig) { var res = extend5({}, parentConfig), prop; for (prop in childConfig) { if (hasOwnProp(childConfig, prop)) { if (isObject4(parentConfig[prop]) && isObject4(childConfig[prop])) { res[prop] = {}; extend5(res[prop], parentConfig[prop]); extend5(res[prop], childConfig[prop]); } else if (childConfig[prop] != null) { res[prop] = childConfig[prop]; } else { delete res[prop]; } } } for (prop in parentConfig) { if (hasOwnProp(parentConfig, prop) && !hasOwnProp(childConfig, prop) && isObject4(parentConfig[prop])) { res[prop] = extend5({}, res[prop]); } } return res; } function Locale(config) { if (config != null) { this.set(config); } } var keys3; if (Object.keys) { keys3 = Object.keys; } else { keys3 = function(obj) { var i, res = []; for (i in obj) { if (hasOwnProp(obj, i)) { res.push(i); } } return res; }; } var defaultCalendar = { sameDay: "[Today at] LT", nextDay: "[Tomorrow at] LT", nextWeek: "dddd [at] LT", lastDay: "[Yesterday at] LT", lastWeek: "[Last] dddd [at] LT", sameElse: "L" }; function calendar(key, mom, now2) { var output = this._calendar[key] || this._calendar["sameElse"]; return isFunction2(output) ? output.call(mom, now2) : output; } function zeroFill(number2, targetLength, forceSign) { var absNumber = "" + Math.abs(number2), zerosToFill = targetLength - absNumber.length, sign2 = number2 >= 0; return (sign2 ? forceSign ? "+" : "" : "-") + Math.pow(10, Math.max(0, zerosToFill)).toString().substr(1) + absNumber; } var formattingTokens = /(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g, localFormattingTokens = /(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g, formatFunctions = {}, formatTokenFunctions = {}; function addFormatToken(token2, padded, ordinal2, callback) { var func = callback; if (typeof callback === "string") { func = function() { return this[callback](); }; } if (token2) { formatTokenFunctions[token2] = func; } if (padded) { formatTokenFunctions[padded[0]] = function() { return zeroFill(func.apply(this, arguments), padded[1], padded[2]); }; } if (ordinal2) { formatTokenFunctions[ordinal2] = function() { return this.localeData().ordinal( func.apply(this, arguments), token2 ); }; } } function removeFormattingTokens(input) { if (input.match(/\[[\s\S]/)) { return input.replace(/^\[|\]$/g, ""); } return input.replace(/\\/g, ""); } function makeFormatFunction(format2) { var array = format2.match(formattingTokens), i, length; for (i = 0, length = array.length; i < length; i++) { if (formatTokenFunctions[array[i]]) { array[i] = formatTokenFunctions[array[i]]; } else { array[i] = removeFormattingTokens(array[i]); } } return function(mom) { var output = "", i2; for (i2 = 0; i2 < length; i2++) { output += isFunction2(array[i2]) ? array[i2].call(mom, format2) : array[i2]; } return output; }; } function formatMoment(m, format2) { if (!m.isValid()) { return m.localeData().invalidDate(); } format2 = expandFormat(format2, m.localeData()); formatFunctions[format2] = formatFunctions[format2] || makeFormatFunction(format2); return formatFunctions[format2](m); } function expandFormat(format2, locale2) { var i = 5; function replaceLongDateFormatTokens(input) { return locale2.longDateFormat(input) || input; } localFormattingTokens.lastIndex = 0; while (i >= 0 && localFormattingTokens.test(format2)) { format2 = format2.replace( localFormattingTokens, replaceLongDateFormatTokens ); localFormattingTokens.lastIndex = 0; i -= 1; } return format2; } var defaultLongDateFormat = { LTS: "h:mm:ss A", LT: "h:mm A", L: "MM/DD/YYYY", LL: "MMMM D, YYYY", LLL: "MMMM D, YYYY h:mm A", LLLL: "dddd, MMMM D, YYYY h:mm A" }; function longDateFormat(key) { var format2 = this._longDateFormat[key], formatUpper = this._longDateFormat[key.toUpperCase()]; if (format2 || !formatUpper) { return format2; } this._longDateFormat[key] = formatUpper.match(formattingTokens).map(function(tok) { if (tok === "MMMM" || tok === "MM" || tok === "DD" || tok === "dddd") { return tok.slice(1); } return tok; }).join(""); return this._longDateFormat[key]; } var defaultInvalidDate = "Invalid date"; function invalidDate() { return this._invalidDate; } var defaultOrdinal = "%d", defaultDayOfMonthOrdinalParse = /\d{1,2}/; function ordinal(number2) { return this._ordinal.replace("%d", number2); } var defaultRelativeTime = { future: "in %s", past: "%s ago", s: "a few seconds", ss: "%d seconds", m: "a minute", mm: "%d minutes", h: "an hour", hh: "%d hours", d: "a day", dd: "%d days", w: "a week", ww: "%d weeks", M: "a month", MM: "%d months", y: "a year", yy: "%d years" }; function relativeTime(number2, withoutSuffix, string3, isFuture) { var output = this._relativeTime[string3]; return isFunction2(output) ? output(number2, withoutSuffix, string3, isFuture) : output.replace(/%d/i, number2); } function pastFuture(diff2, output) { var format2 = this._relativeTime[diff2 > 0 ? "future" : "past"]; return isFunction2(format2) ? format2(output) : format2.replace(/%s/i, output); } var aliases = {}; function addUnitAlias(unit, shorthand) { var lowerCase = unit.toLowerCase(); aliases[lowerCase] = aliases[lowerCase + "s"] = aliases[shorthand] = unit; } function normalizeUnits(units) { return typeof units === "string" ? aliases[units] || aliases[units.toLowerCase()] : void 0; } function normalizeObjectUnits(inputObject) { var normalizedInput = {}, normalizedProp, prop; for (prop in inputObject) { if (hasOwnProp(inputObject, prop)) { normalizedProp = normalizeUnits(prop); if (normalizedProp) { normalizedInput[normalizedProp] = inputObject[prop]; } } } return normalizedInput; } var priorities = {}; function addUnitPriority(unit, priority) { priorities[unit] = priority; } function getPrioritizedUnits(unitsObj) { var units = [], u; for (u in unitsObj) { if (hasOwnProp(unitsObj, u)) { units.push({ unit: u, priority: priorities[u] }); } } units.sort(function(a2, b) { return a2.priority - b.priority; }); return units; } function isLeapYear(year) { return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0; } function absFloor(number2) { if (number2 < 0) { return Math.ceil(number2) || 0; } else { return Math.floor(number2); } } function toInt(argumentForCoercion) { var coercedNumber = +argumentForCoercion, value = 0; if (coercedNumber !== 0 && isFinite(coercedNumber)) { value = absFloor(coercedNumber); } return value; } function makeGetSet(unit, keepTime) { return function(value) { if (value != null) { set$1(this, unit, value); hooks.updateOffset(this, keepTime); return this; } else { return get(this, unit); } }; } function get(mom, unit) { return mom.isValid() ? mom._d["get" + (mom._isUTC ? "UTC" : "") + unit]() : NaN; } function set$1(mom, unit, value) { if (mom.isValid() && !isNaN(value)) { if (unit === "FullYear" && isLeapYear(mom.year()) && mom.month() === 1 && mom.date() === 29) { value = toInt(value); mom._d["set" + (mom._isUTC ? "UTC" : "") + unit]( value, mom.month(), daysInMonth(value, mom.month()) ); } else { mom._d["set" + (mom._isUTC ? "UTC" : "") + unit](value); } } } function stringGet(units) { units = normalizeUnits(units); if (isFunction2(this[units])) { return this[units](); } return this; } function stringSet(units, value) { if (typeof units === "object") { units = normalizeObjectUnits(units); var prioritized = getPrioritizedUnits(units), i, prioritizedLen = prioritized.length; for (i = 0; i < prioritizedLen; i++) { this[prioritized[i].unit](units[prioritized[i].unit]); } } else { units = normalizeUnits(units); if (isFunction2(this[units])) { return this[units](value); } } return this; } var match1 = /\d/, match2 = /\d\d/, match3 = /\d{3}/, match4 = /\d{4}/, match6 = /[+-]?\d{6}/, match1to2 = /\d\d?/, match3to4 = /\d\d\d\d?/, match5to6 = /\d\d\d\d\d\d?/, match1to3 = /\d{1,3}/, match1to4 = /\d{1,4}/, match1to6 = /[+-]?\d{1,6}/, matchUnsigned = /\d+/, matchSigned = /[+-]?\d+/, matchOffset = /Z|[+-]\d\d:?\d\d/gi, matchShortOffset = /Z|[+-]\d\d(?::?\d\d)?/gi, matchTimestamp = /[+-]?\d+(\.\d{1,3})?/, matchWord = /[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i, regexes; regexes = {}; function addRegexToken(token2, regex, strictRegex) { regexes[token2] = isFunction2(regex) ? regex : function(isStrict, localeData2) { return isStrict && strictRegex ? strictRegex : regex; }; } function getParseRegexForToken(token2, config) { if (!hasOwnProp(regexes, token2)) { return new RegExp(unescapeFormat(token2)); } return regexes[token2](config._strict, config._locale); } function unescapeFormat(s) { return regexEscape( s.replace("\\", "").replace( /\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g, function(matched, p1, p2, p3, p4) { return p1 || p2 || p3 || p4; } ) ); } function regexEscape(s) { return s.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); } var tokens = {}; function addParseToken(token2, callback) { var i, func = callback, tokenLen; if (typeof token2 === "string") { token2 = [token2]; } if (isNumber2(callback)) { func = function(input, array) { array[callback] = toInt(input); }; } tokenLen = token2.length; for (i = 0; i < tokenLen; i++) { tokens[token2[i]] = func; } } function addWeekParseToken(token2, callback) { addParseToken(token2, function(input, array, config, token3) { config._w = config._w || {}; callback(input, config._w, config, token3); }); } function addTimeToArrayFromToken(token2, input, config) { if (input != null && hasOwnProp(tokens, token2)) { tokens[token2](input, config._a, config, token2); } } var YEAR = 0, MONTH = 1, DATE = 2, HOUR = 3, MINUTE = 4, SECOND = 5, MILLISECOND = 6, WEEK = 7, WEEKDAY = 8; function mod(n, x) { return (n % x + x) % x; } var indexOf; if (Array.prototype.indexOf) { indexOf = Array.prototype.indexOf; } else { indexOf = function(o) { var i; for (i = 0; i < this.length; ++i) { if (this[i] === o) { return i; } } return -1; }; } function daysInMonth(year, month) { if (isNaN(year) || isNaN(month)) { return NaN; } var modMonth = mod(month, 12); year += (month - modMonth) / 12; return modMonth === 1 ? isLeapYear(year) ? 29 : 28 : 31 - modMonth % 7 % 2; } addFormatToken("M", ["MM", 2], "Mo", function() { return this.month() + 1; }); addFormatToken("MMM", 0, 0, function(format2) { return this.localeData().monthsShort(this, format2); }); addFormatToken("MMMM", 0, 0, function(format2) { return this.localeData().months(this, format2); }); addUnitAlias("month", "M"); addUnitPriority("month", 8); addRegexToken("M", match1to2); addRegexToken("MM", match1to2, match2); addRegexToken("MMM", function(isStrict, locale2) { return locale2.monthsShortRegex(isStrict); }); addRegexToken("MMMM", function(isStrict, locale2) { return locale2.monthsRegex(isStrict); }); addParseToken(["M", "MM"], function(input, array) { array[MONTH] = toInt(input) - 1; }); addParseToken(["MMM", "MMMM"], function(input, array, config, token2) { var month = config._locale.monthsParse(input, token2, config._strict); if (month != null) { array[MONTH] = month; } else { getParsingFlags(config).invalidMonth = input; } }); var defaultLocaleMonths = "January_February_March_April_May_June_July_August_September_October_November_December".split( "_" ), defaultLocaleMonthsShort = "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), MONTHS_IN_FORMAT = /D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/, defaultMonthsShortRegex = matchWord, defaultMonthsRegex = matchWord; function localeMonths(m, format2) { if (!m) { return isArray4(this._months) ? this._months : this._months["standalone"]; } return isArray4(this._months) ? this._months[m.month()] : this._months[(this._months.isFormat || MONTHS_IN_FORMAT).test(format2) ? "format" : "standalone"][m.month()]; } function localeMonthsShort(m, format2) { if (!m) { return isArray4(this._monthsShort) ? this._monthsShort : this._monthsShort["standalone"]; } return isArray4(this._monthsShort) ? this._monthsShort[m.month()] : this._monthsShort[MONTHS_IN_FORMAT.test(format2) ? "format" : "standalone"][m.month()]; } function handleStrictParse(monthName, format2, strict) { var i, ii, mom, llc = monthName.toLocaleLowerCase(); if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; for (i = 0; i < 12; ++i) { mom = createUTC([2e3, i]); this._shortMonthsParse[i] = this.monthsShort( mom, "" ).toLocaleLowerCase(); this._longMonthsParse[i] = this.months(mom, "").toLocaleLowerCase(); } } if (strict) { if (format2 === "MMM") { ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } } else { if (format2 === "MMM") { ii = indexOf.call(this._shortMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._longMonthsParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._longMonthsParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortMonthsParse, llc); return ii !== -1 ? ii : null; } } } function localeMonthsParse(monthName, format2, strict) { var i, mom, regex; if (this._monthsParseExact) { return handleStrictParse.call(this, monthName, format2, strict); } if (!this._monthsParse) { this._monthsParse = []; this._longMonthsParse = []; this._shortMonthsParse = []; } for (i = 0; i < 12; i++) { mom = createUTC([2e3, i]); if (strict && !this._longMonthsParse[i]) { this._longMonthsParse[i] = new RegExp( "^" + this.months(mom, "").replace(".", "") + "$", "i" ); this._shortMonthsParse[i] = new RegExp( "^" + this.monthsShort(mom, "").replace(".", "") + "$", "i" ); } if (!strict && !this._monthsParse[i]) { regex = "^" + this.months(mom, "") + "|^" + this.monthsShort(mom, ""); this._monthsParse[i] = new RegExp(regex.replace(".", ""), "i"); } if (strict && format2 === "MMMM" && this._longMonthsParse[i].test(monthName)) { return i; } else if (strict && format2 === "MMM" && this._shortMonthsParse[i].test(monthName)) { return i; } else if (!strict && this._monthsParse[i].test(monthName)) { return i; } } } function setMonth(mom, value) { var dayOfMonth; if (!mom.isValid()) { return mom; } if (typeof value === "string") { if (/^\d+$/.test(value)) { value = toInt(value); } else { value = mom.localeData().monthsParse(value); if (!isNumber2(value)) { return mom; } } } dayOfMonth = Math.min(mom.date(), daysInMonth(mom.year(), value)); mom._d["set" + (mom._isUTC ? "UTC" : "") + "Month"](value, dayOfMonth); return mom; } function getSetMonth(value) { if (value != null) { setMonth(this, value); hooks.updateOffset(this, true); return this; } else { return get(this, "Month"); } } function getDaysInMonth() { return daysInMonth(this.year(), this.month()); } function monthsShortRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, "_monthsRegex")) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsShortStrictRegex; } else { return this._monthsShortRegex; } } else { if (!hasOwnProp(this, "_monthsShortRegex")) { this._monthsShortRegex = defaultMonthsShortRegex; } return this._monthsShortStrictRegex && isStrict ? this._monthsShortStrictRegex : this._monthsShortRegex; } } function monthsRegex(isStrict) { if (this._monthsParseExact) { if (!hasOwnProp(this, "_monthsRegex")) { computeMonthsParse.call(this); } if (isStrict) { return this._monthsStrictRegex; } else { return this._monthsRegex; } } else { if (!hasOwnProp(this, "_monthsRegex")) { this._monthsRegex = defaultMonthsRegex; } return this._monthsStrictRegex && isStrict ? this._monthsStrictRegex : this._monthsRegex; } } function computeMonthsParse() { function cmpLenRev(a2, b) { return b.length - a2.length; } var shortPieces = [], longPieces = [], mixedPieces = [], i, mom; for (i = 0; i < 12; i++) { mom = createUTC([2e3, i]); shortPieces.push(this.monthsShort(mom, "")); longPieces.push(this.months(mom, "")); mixedPieces.push(this.months(mom, "")); mixedPieces.push(this.monthsShort(mom, "")); } shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); for (i = 0; i < 12; i++) { shortPieces[i] = regexEscape(shortPieces[i]); longPieces[i] = regexEscape(longPieces[i]); } for (i = 0; i < 24; i++) { mixedPieces[i] = regexEscape(mixedPieces[i]); } this._monthsRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); this._monthsShortRegex = this._monthsRegex; this._monthsStrictRegex = new RegExp( "^(" + longPieces.join("|") + ")", "i" ); this._monthsShortStrictRegex = new RegExp( "^(" + shortPieces.join("|") + ")", "i" ); } addFormatToken("Y", 0, 0, function() { var y = this.year(); return y <= 9999 ? zeroFill(y, 4) : "+" + y; }); addFormatToken(0, ["YY", 2], 0, function() { return this.year() % 100; }); addFormatToken(0, ["YYYY", 4], 0, "year"); addFormatToken(0, ["YYYYY", 5], 0, "year"); addFormatToken(0, ["YYYYYY", 6, true], 0, "year"); addUnitAlias("year", "y"); addUnitPriority("year", 1); addRegexToken("Y", matchSigned); addRegexToken("YY", match1to2, match2); addRegexToken("YYYY", match1to4, match4); addRegexToken("YYYYY", match1to6, match6); addRegexToken("YYYYYY", match1to6, match6); addParseToken(["YYYYY", "YYYYYY"], YEAR); addParseToken("YYYY", function(input, array) { array[YEAR] = input.length === 2 ? hooks.parseTwoDigitYear(input) : toInt(input); }); addParseToken("YY", function(input, array) { array[YEAR] = hooks.parseTwoDigitYear(input); }); addParseToken("Y", function(input, array) { array[YEAR] = parseInt(input, 10); }); function daysInYear(year) { return isLeapYear(year) ? 366 : 365; } hooks.parseTwoDigitYear = function(input) { return toInt(input) + (toInt(input) > 68 ? 1900 : 2e3); }; var getSetYear = makeGetSet("FullYear", true); function getIsLeapYear() { return isLeapYear(this.year()); } function createDate(y, m, d, h2, M, s, ms) { var date; if (y < 100 && y >= 0) { date = new Date(y + 400, m, d, h2, M, s, ms); if (isFinite(date.getFullYear())) { date.setFullYear(y); } } else { date = new Date(y, m, d, h2, M, s, ms); } return date; } function createUTCDate(y) { var date, args; if (y < 100 && y >= 0) { args = Array.prototype.slice.call(arguments); args[0] = y + 400; date = new Date(Date.UTC.apply(null, args)); if (isFinite(date.getUTCFullYear())) { date.setUTCFullYear(y); } } else { date = new Date(Date.UTC.apply(null, arguments)); } return date; } function firstWeekOffset(year, dow, doy) { var fwd = 7 + dow - doy, fwdlw = (7 + createUTCDate(year, 0, fwd).getUTCDay() - dow) % 7; return -fwdlw + fwd - 1; } function dayOfYearFromWeeks(year, week, weekday, dow, doy) { var localWeekday = (7 + weekday - dow) % 7, weekOffset = firstWeekOffset(year, dow, doy), dayOfYear = 1 + 7 * (week - 1) + localWeekday + weekOffset, resYear, resDayOfYear; if (dayOfYear <= 0) { resYear = year - 1; resDayOfYear = daysInYear(resYear) + dayOfYear; } else if (dayOfYear > daysInYear(year)) { resYear = year + 1; resDayOfYear = dayOfYear - daysInYear(year); } else { resYear = year; resDayOfYear = dayOfYear; } return { year: resYear, dayOfYear: resDayOfYear }; } function weekOfYear(mom, dow, doy) { var weekOffset = firstWeekOffset(mom.year(), dow, doy), week = Math.floor((mom.dayOfYear() - weekOffset - 1) / 7) + 1, resWeek, resYear; if (week < 1) { resYear = mom.year() - 1; resWeek = week + weeksInYear(resYear, dow, doy); } else if (week > weeksInYear(mom.year(), dow, doy)) { resWeek = week - weeksInYear(mom.year(), dow, doy); resYear = mom.year() + 1; } else { resYear = mom.year(); resWeek = week; } return { week: resWeek, year: resYear }; } function weeksInYear(year, dow, doy) { var weekOffset = firstWeekOffset(year, dow, doy), weekOffsetNext = firstWeekOffset(year + 1, dow, doy); return (daysInYear(year) - weekOffset + weekOffsetNext) / 7; } addFormatToken("w", ["ww", 2], "wo", "week"); addFormatToken("W", ["WW", 2], "Wo", "isoWeek"); addUnitAlias("week", "w"); addUnitAlias("isoWeek", "W"); addUnitPriority("week", 5); addUnitPriority("isoWeek", 5); addRegexToken("w", match1to2); addRegexToken("ww", match1to2, match2); addRegexToken("W", match1to2); addRegexToken("WW", match1to2, match2); addWeekParseToken( ["w", "ww", "W", "WW"], function(input, week, config, token2) { week[token2.substr(0, 1)] = toInt(input); } ); function localeWeek(mom) { return weekOfYear(mom, this._week.dow, this._week.doy).week; } var defaultLocaleWeek = { dow: 0, // Sunday is the first day of the week. doy: 6 // The week that contains Jan 6th is the first week of the year. }; function localeFirstDayOfWeek() { return this._week.dow; } function localeFirstDayOfYear() { return this._week.doy; } function getSetWeek(input) { var week = this.localeData().week(this); return input == null ? week : this.add((input - week) * 7, "d"); } function getSetISOWeek(input) { var week = weekOfYear(this, 1, 4).week; return input == null ? week : this.add((input - week) * 7, "d"); } addFormatToken("d", 0, "do", "day"); addFormatToken("dd", 0, 0, function(format2) { return this.localeData().weekdaysMin(this, format2); }); addFormatToken("ddd", 0, 0, function(format2) { return this.localeData().weekdaysShort(this, format2); }); addFormatToken("dddd", 0, 0, function(format2) { return this.localeData().weekdays(this, format2); }); addFormatToken("e", 0, 0, "weekday"); addFormatToken("E", 0, 0, "isoWeekday"); addUnitAlias("day", "d"); addUnitAlias("weekday", "e"); addUnitAlias("isoWeekday", "E"); addUnitPriority("day", 11); addUnitPriority("weekday", 11); addUnitPriority("isoWeekday", 11); addRegexToken("d", match1to2); addRegexToken("e", match1to2); addRegexToken("E", match1to2); addRegexToken("dd", function(isStrict, locale2) { return locale2.weekdaysMinRegex(isStrict); }); addRegexToken("ddd", function(isStrict, locale2) { return locale2.weekdaysShortRegex(isStrict); }); addRegexToken("dddd", function(isStrict, locale2) { return locale2.weekdaysRegex(isStrict); }); addWeekParseToken(["dd", "ddd", "dddd"], function(input, week, config, token2) { var weekday = config._locale.weekdaysParse(input, token2, config._strict); if (weekday != null) { week.d = weekday; } else { getParsingFlags(config).invalidWeekday = input; } }); addWeekParseToken(["d", "e", "E"], function(input, week, config, token2) { week[token2] = toInt(input); }); function parseWeekday(input, locale2) { if (typeof input !== "string") { return input; } if (!isNaN(input)) { return parseInt(input, 10); } input = locale2.weekdaysParse(input); if (typeof input === "number") { return input; } return null; } function parseIsoWeekday(input, locale2) { if (typeof input === "string") { return locale2.weekdaysParse(input) % 7 || 7; } return isNaN(input) ? null : input; } function shiftWeekdays(ws, n) { return ws.slice(n, 7).concat(ws.slice(0, n)); } var defaultLocaleWeekdays = "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), defaultLocaleWeekdaysShort = "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), defaultLocaleWeekdaysMin = "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), defaultWeekdaysRegex = matchWord, defaultWeekdaysShortRegex = matchWord, defaultWeekdaysMinRegex = matchWord; function localeWeekdays(m, format2) { var weekdays = isArray4(this._weekdays) ? this._weekdays : this._weekdays[m && m !== true && this._weekdays.isFormat.test(format2) ? "format" : "standalone"]; return m === true ? shiftWeekdays(weekdays, this._week.dow) : m ? weekdays[m.day()] : weekdays; } function localeWeekdaysShort(m) { return m === true ? shiftWeekdays(this._weekdaysShort, this._week.dow) : m ? this._weekdaysShort[m.day()] : this._weekdaysShort; } function localeWeekdaysMin(m) { return m === true ? shiftWeekdays(this._weekdaysMin, this._week.dow) : m ? this._weekdaysMin[m.day()] : this._weekdaysMin; } function handleStrictParse$1(weekdayName, format2, strict) { var i, ii, mom, llc = weekdayName.toLocaleLowerCase(); if (!this._weekdaysParse) { this._weekdaysParse = []; this._shortWeekdaysParse = []; this._minWeekdaysParse = []; for (i = 0; i < 7; ++i) { mom = createUTC([2e3, 1]).day(i); this._minWeekdaysParse[i] = this.weekdaysMin( mom, "" ).toLocaleLowerCase(); this._shortWeekdaysParse[i] = this.weekdaysShort( mom, "" ).toLocaleLowerCase(); this._weekdaysParse[i] = this.weekdays(mom, "").toLocaleLowerCase(); } } if (strict) { if (format2 === "dddd") { ii = indexOf.call(this._weekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format2 === "ddd") { ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } } else { if (format2 === "dddd") { ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else if (format2 === "ddd") { ii = indexOf.call(this._shortWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._minWeekdaysParse, llc); return ii !== -1 ? ii : null; } else { ii = indexOf.call(this._minWeekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._weekdaysParse, llc); if (ii !== -1) { return ii; } ii = indexOf.call(this._shortWeekdaysParse, llc); return ii !== -1 ? ii : null; } } } function localeWeekdaysParse(weekdayName, format2, strict) { var i, mom, regex; if (this._weekdaysParseExact) { return handleStrictParse$1.call(this, weekdayName, format2, strict); } if (!this._weekdaysParse) { this._weekdaysParse = []; this._minWeekdaysParse = []; this._shortWeekdaysParse = []; this._fullWeekdaysParse = []; } for (i = 0; i < 7; i++) { mom = createUTC([2e3, 1]).day(i); if (strict && !this._fullWeekdaysParse[i]) { this._fullWeekdaysParse[i] = new RegExp( "^" + this.weekdays(mom, "").replace(".", "\\.?") + "$", "i" ); this._shortWeekdaysParse[i] = new RegExp( "^" + this.weekdaysShort(mom, "").replace(".", "\\.?") + "$", "i" ); this._minWeekdaysParse[i] = new RegExp( "^" + this.weekdaysMin(mom, "").replace(".", "\\.?") + "$", "i" ); } if (!this._weekdaysParse[i]) { regex = "^" + this.weekdays(mom, "") + "|^" + this.weekdaysShort(mom, "") + "|^" + this.weekdaysMin(mom, ""); this._weekdaysParse[i] = new RegExp(regex.replace(".", ""), "i"); } if (strict && format2 === "dddd" && this._fullWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format2 === "ddd" && this._shortWeekdaysParse[i].test(weekdayName)) { return i; } else if (strict && format2 === "dd" && this._minWeekdaysParse[i].test(weekdayName)) { return i; } else if (!strict && this._weekdaysParse[i].test(weekdayName)) { return i; } } } function getSetDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var day = this._isUTC ? this._d.getUTCDay() : this._d.getDay(); if (input != null) { input = parseWeekday(input, this.localeData()); return this.add(input - day, "d"); } else { return day; } } function getSetLocaleDayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } var weekday = (this.day() + 7 - this.localeData()._week.dow) % 7; return input == null ? weekday : this.add(input - weekday, "d"); } function getSetISODayOfWeek(input) { if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { var weekday = parseIsoWeekday(input, this.localeData()); return this.day(this.day() % 7 ? weekday : weekday - 7); } else { return this.day() || 7; } } function weekdaysRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, "_weekdaysRegex")) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysStrictRegex; } else { return this._weekdaysRegex; } } else { if (!hasOwnProp(this, "_weekdaysRegex")) { this._weekdaysRegex = defaultWeekdaysRegex; } return this._weekdaysStrictRegex && isStrict ? this._weekdaysStrictRegex : this._weekdaysRegex; } } function weekdaysShortRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, "_weekdaysRegex")) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysShortStrictRegex; } else { return this._weekdaysShortRegex; } } else { if (!hasOwnProp(this, "_weekdaysShortRegex")) { this._weekdaysShortRegex = defaultWeekdaysShortRegex; } return this._weekdaysShortStrictRegex && isStrict ? this._weekdaysShortStrictRegex : this._weekdaysShortRegex; } } function weekdaysMinRegex(isStrict) { if (this._weekdaysParseExact) { if (!hasOwnProp(this, "_weekdaysRegex")) { computeWeekdaysParse.call(this); } if (isStrict) { return this._weekdaysMinStrictRegex; } else { return this._weekdaysMinRegex; } } else { if (!hasOwnProp(this, "_weekdaysMinRegex")) { this._weekdaysMinRegex = defaultWeekdaysMinRegex; } return this._weekdaysMinStrictRegex && isStrict ? this._weekdaysMinStrictRegex : this._weekdaysMinRegex; } } function computeWeekdaysParse() { function cmpLenRev(a2, b) { return b.length - a2.length; } var minPieces = [], shortPieces = [], longPieces = [], mixedPieces = [], i, mom, minp, shortp, longp; for (i = 0; i < 7; i++) { mom = createUTC([2e3, 1]).day(i); minp = regexEscape(this.weekdaysMin(mom, "")); shortp = regexEscape(this.weekdaysShort(mom, "")); longp = regexEscape(this.weekdays(mom, "")); minPieces.push(minp); shortPieces.push(shortp); longPieces.push(longp); mixedPieces.push(minp); mixedPieces.push(shortp); mixedPieces.push(longp); } minPieces.sort(cmpLenRev); shortPieces.sort(cmpLenRev); longPieces.sort(cmpLenRev); mixedPieces.sort(cmpLenRev); this._weekdaysRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); this._weekdaysShortRegex = this._weekdaysRegex; this._weekdaysMinRegex = this._weekdaysRegex; this._weekdaysStrictRegex = new RegExp( "^(" + longPieces.join("|") + ")", "i" ); this._weekdaysShortStrictRegex = new RegExp( "^(" + shortPieces.join("|") + ")", "i" ); this._weekdaysMinStrictRegex = new RegExp( "^(" + minPieces.join("|") + ")", "i" ); } function hFormat() { return this.hours() % 12 || 12; } function kFormat() { return this.hours() || 24; } addFormatToken("H", ["HH", 2], 0, "hour"); addFormatToken("h", ["hh", 2], 0, hFormat); addFormatToken("k", ["kk", 2], 0, kFormat); addFormatToken("hmm", 0, 0, function() { return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2); }); addFormatToken("hmmss", 0, 0, function() { return "" + hFormat.apply(this) + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); addFormatToken("Hmm", 0, 0, function() { return "" + this.hours() + zeroFill(this.minutes(), 2); }); addFormatToken("Hmmss", 0, 0, function() { return "" + this.hours() + zeroFill(this.minutes(), 2) + zeroFill(this.seconds(), 2); }); function meridiem(token2, lowercase) { addFormatToken(token2, 0, 0, function() { return this.localeData().meridiem( this.hours(), this.minutes(), lowercase ); }); } meridiem("a", true); meridiem("A", false); addUnitAlias("hour", "h"); addUnitPriority("hour", 13); function matchMeridiem(isStrict, locale2) { return locale2._meridiemParse; } addRegexToken("a", matchMeridiem); addRegexToken("A", matchMeridiem); addRegexToken("H", match1to2); addRegexToken("h", match1to2); addRegexToken("k", match1to2); addRegexToken("HH", match1to2, match2); addRegexToken("hh", match1to2, match2); addRegexToken("kk", match1to2, match2); addRegexToken("hmm", match3to4); addRegexToken("hmmss", match5to6); addRegexToken("Hmm", match3to4); addRegexToken("Hmmss", match5to6); addParseToken(["H", "HH"], HOUR); addParseToken(["k", "kk"], function(input, array, config) { var kInput = toInt(input); array[HOUR] = kInput === 24 ? 0 : kInput; }); addParseToken(["a", "A"], function(input, array, config) { config._isPm = config._locale.isPM(input); config._meridiem = input; }); addParseToken(["h", "hh"], function(input, array, config) { array[HOUR] = toInt(input); getParsingFlags(config).bigHour = true; }); addParseToken("hmm", function(input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); getParsingFlags(config).bigHour = true; }); addParseToken("hmmss", function(input, array, config) { var pos1 = input.length - 4, pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); getParsingFlags(config).bigHour = true; }); addParseToken("Hmm", function(input, array, config) { var pos = input.length - 2; array[HOUR] = toInt(input.substr(0, pos)); array[MINUTE] = toInt(input.substr(pos)); }); addParseToken("Hmmss", function(input, array, config) { var pos1 = input.length - 4, pos2 = input.length - 2; array[HOUR] = toInt(input.substr(0, pos1)); array[MINUTE] = toInt(input.substr(pos1, 2)); array[SECOND] = toInt(input.substr(pos2)); }); function localeIsPM(input) { return (input + "").toLowerCase().charAt(0) === "p"; } var defaultLocaleMeridiemParse = /[ap]\.?m?\.?/i, getSetHour = makeGetSet("Hours", true); function localeMeridiem(hours2, minutes2, isLower) { if (hours2 > 11) { return isLower ? "pm" : "PM"; } else { return isLower ? "am" : "AM"; } } var baseConfig = { calendar: defaultCalendar, longDateFormat: defaultLongDateFormat, invalidDate: defaultInvalidDate, ordinal: defaultOrdinal, dayOfMonthOrdinalParse: defaultDayOfMonthOrdinalParse, relativeTime: defaultRelativeTime, months: defaultLocaleMonths, monthsShort: defaultLocaleMonthsShort, week: defaultLocaleWeek, weekdays: defaultLocaleWeekdays, weekdaysMin: defaultLocaleWeekdaysMin, weekdaysShort: defaultLocaleWeekdaysShort, meridiemParse: defaultLocaleMeridiemParse }; var locales = {}, localeFamilies = {}, globalLocale; function commonPrefix(arr1, arr2) { var i, minl = Math.min(arr1.length, arr2.length); for (i = 0; i < minl; i += 1) { if (arr1[i] !== arr2[i]) { return i; } } return minl; } function normalizeLocale(key) { return key ? key.toLowerCase().replace("_", "-") : key; } function chooseLocale(names) { var i = 0, j, next, locale2, split; while (i < names.length) { split = normalizeLocale(names[i]).split("-"); j = split.length; next = normalizeLocale(names[i + 1]); next = next ? next.split("-") : null; while (j > 0) { locale2 = loadLocale(split.slice(0, j).join("-")); if (locale2) { return locale2; } if (next && next.length >= j && commonPrefix(split, next) >= j - 1) { break; } j--; } i++; } return globalLocale; } function isLocaleNameSane(name) { return name.match("^[^/\\\\]*$") != null; } function loadLocale(name) { var oldLocale = null, aliasedRequire; if (locales[name] === void 0 && typeof module2 !== "undefined" && module2 && module2.exports && isLocaleNameSane(name)) { try { oldLocale = globalLocale._abbr; aliasedRequire = require; aliasedRequire("./locale/" + name); getSetGlobalLocale(oldLocale); } catch (e) { locales[name] = null; } } return locales[name]; } function getSetGlobalLocale(key, values) { var data; if (key) { if (isUndefined3(values)) { data = getLocale(key); } else { data = defineLocale(key, values); } if (data) { globalLocale = data; } else { if (typeof console !== "undefined" && console.warn) { console.warn( "Locale " + key + " not found. Did you forget to load it?" ); } } } return globalLocale._abbr; } function defineLocale(name, config) { if (config !== null) { var locale2, parentConfig = baseConfig; config.abbr = name; if (locales[name] != null) { deprecateSimple( "defineLocaleOverride", "use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info." ); parentConfig = locales[name]._config; } else if (config.parentLocale != null) { if (locales[config.parentLocale] != null) { parentConfig = locales[config.parentLocale]._config; } else { locale2 = loadLocale(config.parentLocale); if (locale2 != null) { parentConfig = locale2._config; } else { if (!localeFamilies[config.parentLocale]) { localeFamilies[config.parentLocale] = []; } localeFamilies[config.parentLocale].push({ name, config }); return null; } } } locales[name] = new Locale(mergeConfigs(parentConfig, config)); if (localeFamilies[name]) { localeFamilies[name].forEach(function(x) { defineLocale(x.name, x.config); }); } getSetGlobalLocale(name); return locales[name]; } else { delete locales[name]; return null; } } function updateLocale(name, config) { if (config != null) { var locale2, tmpLocale, parentConfig = baseConfig; if (locales[name] != null && locales[name].parentLocale != null) { locales[name].set(mergeConfigs(locales[name]._config, config)); } else { tmpLocale = loadLocale(name); if (tmpLocale != null) { parentConfig = tmpLocale._config; } config = mergeConfigs(parentConfig, config); if (tmpLocale == null) { config.abbr = name; } locale2 = new Locale(config); locale2.parentLocale = locales[name]; locales[name] = locale2; } getSetGlobalLocale(name); } else { if (locales[name] != null) { if (locales[name].parentLocale != null) { locales[name] = locales[name].parentLocale; if (name === getSetGlobalLocale()) { getSetGlobalLocale(name); } } else if (locales[name] != null) { delete locales[name]; } } } return locales[name]; } function getLocale(key) { var locale2; if (key && key._locale && key._locale._abbr) { key = key._locale._abbr; } if (!key) { return globalLocale; } if (!isArray4(key)) { locale2 = loadLocale(key); if (locale2) { return locale2; } key = [key]; } return chooseLocale(key); } function listLocales() { return keys3(locales); } function checkOverflow(m) { var overflow, a2 = m._a; if (a2 && getParsingFlags(m).overflow === -2) { overflow = a2[MONTH] < 0 || a2[MONTH] > 11 ? MONTH : a2[DATE] < 1 || a2[DATE] > daysInMonth(a2[YEAR], a2[MONTH]) ? DATE : a2[HOUR] < 0 || a2[HOUR] > 24 || a2[HOUR] === 24 && (a2[MINUTE] !== 0 || a2[SECOND] !== 0 || a2[MILLISECOND] !== 0) ? HOUR : a2[MINUTE] < 0 || a2[MINUTE] > 59 ? MINUTE : a2[SECOND] < 0 || a2[SECOND] > 59 ? SECOND : a2[MILLISECOND] < 0 || a2[MILLISECOND] > 999 ? MILLISECOND : -1; if (getParsingFlags(m)._overflowDayOfYear && (overflow < YEAR || overflow > DATE)) { overflow = DATE; } if (getParsingFlags(m)._overflowWeeks && overflow === -1) { overflow = WEEK; } if (getParsingFlags(m)._overflowWeekday && overflow === -1) { overflow = WEEKDAY; } getParsingFlags(m).overflow = overflow; } return m; } var extendedIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, basicIsoRegex = /^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/, tzRegex = /Z|[+-]\d\d(?::?\d\d)?/, isoDates = [ ["YYYYYY-MM-DD", /[+-]\d{6}-\d\d-\d\d/], ["YYYY-MM-DD", /\d{4}-\d\d-\d\d/], ["GGGG-[W]WW-E", /\d{4}-W\d\d-\d/], ["GGGG-[W]WW", /\d{4}-W\d\d/, false], ["YYYY-DDD", /\d{4}-\d{3}/], ["YYYY-MM", /\d{4}-\d\d/, false], ["YYYYYYMMDD", /[+-]\d{10}/], ["YYYYMMDD", /\d{8}/], ["GGGG[W]WWE", /\d{4}W\d{3}/], ["GGGG[W]WW", /\d{4}W\d{2}/, false], ["YYYYDDD", /\d{7}/], ["YYYYMM", /\d{6}/, false], ["YYYY", /\d{4}/, false] ], isoTimes = [ ["HH:mm:ss.SSSS", /\d\d:\d\d:\d\d\.\d+/], ["HH:mm:ss,SSSS", /\d\d:\d\d:\d\d,\d+/], ["HH:mm:ss", /\d\d:\d\d:\d\d/], ["HH:mm", /\d\d:\d\d/], ["HHmmss.SSSS", /\d\d\d\d\d\d\.\d+/], ["HHmmss,SSSS", /\d\d\d\d\d\d,\d+/], ["HHmmss", /\d\d\d\d\d\d/], ["HHmm", /\d\d\d\d/], ["HH", /\d\d/] ], aspNetJsonRegex = /^\/?Date\((-?\d+)/i, rfc2822 = /^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/, obsOffsets = { UT: 0, GMT: 0, EDT: -4 * 60, EST: -5 * 60, CDT: -5 * 60, CST: -6 * 60, MDT: -6 * 60, MST: -7 * 60, PDT: -7 * 60, PST: -8 * 60 }; function configFromISO(config) { var i, l, string3 = config._i, match5 = extendedIsoRegex.exec(string3) || basicIsoRegex.exec(string3), allowTime, dateFormat, timeFormat, tzFormat, isoDatesLen = isoDates.length, isoTimesLen = isoTimes.length; if (match5) { getParsingFlags(config).iso = true; for (i = 0, l = isoDatesLen; i < l; i++) { if (isoDates[i][1].exec(match5[1])) { dateFormat = isoDates[i][0]; allowTime = isoDates[i][2] !== false; break; } } if (dateFormat == null) { config._isValid = false; return; } if (match5[3]) { for (i = 0, l = isoTimesLen; i < l; i++) { if (isoTimes[i][1].exec(match5[3])) { timeFormat = (match5[2] || " ") + isoTimes[i][0]; break; } } if (timeFormat == null) { config._isValid = false; return; } } if (!allowTime && timeFormat != null) { config._isValid = false; return; } if (match5[4]) { if (tzRegex.exec(match5[4])) { tzFormat = "Z"; } else { config._isValid = false; return; } } config._f = dateFormat + (timeFormat || "") + (tzFormat || ""); configFromStringAndFormat(config); } else { config._isValid = false; } } function extractFromRFC2822Strings(yearStr, monthStr, dayStr, hourStr, minuteStr, secondStr) { var result = [ untruncateYear(yearStr), defaultLocaleMonthsShort.indexOf(monthStr), parseInt(dayStr, 10), parseInt(hourStr, 10), parseInt(minuteStr, 10) ]; if (secondStr) { result.push(parseInt(secondStr, 10)); } return result; } function untruncateYear(yearStr) { var year = parseInt(yearStr, 10); if (year <= 49) { return 2e3 + year; } else if (year <= 999) { return 1900 + year; } return year; } function preprocessRFC2822(s) { return s.replace(/\([^()]*\)|[\n\t]/g, " ").replace(/(\s\s+)/g, " ").replace(/^\s\s*/, "").replace(/\s\s*$/, ""); } function checkWeekday(weekdayStr, parsedInput, config) { if (weekdayStr) { var weekdayProvided = defaultLocaleWeekdaysShort.indexOf(weekdayStr), weekdayActual = new Date( parsedInput[0], parsedInput[1], parsedInput[2] ).getDay(); if (weekdayProvided !== weekdayActual) { getParsingFlags(config).weekdayMismatch = true; config._isValid = false; return false; } } return true; } function calculateOffset(obsOffset, militaryOffset, numOffset) { if (obsOffset) { return obsOffsets[obsOffset]; } else if (militaryOffset) { return 0; } else { var hm = parseInt(numOffset, 10), m = hm % 100, h2 = (hm - m) / 100; return h2 * 60 + m; } } function configFromRFC2822(config) { var match5 = rfc2822.exec(preprocessRFC2822(config._i)), parsedArray; if (match5) { parsedArray = extractFromRFC2822Strings( match5[4], match5[3], match5[2], match5[5], match5[6], match5[7] ); if (!checkWeekday(match5[1], parsedArray, config)) { return; } config._a = parsedArray; config._tzm = calculateOffset(match5[8], match5[9], match5[10]); config._d = createUTCDate.apply(null, config._a); config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); getParsingFlags(config).rfc2822 = true; } else { config._isValid = false; } } function configFromString(config) { var matched = aspNetJsonRegex.exec(config._i); if (matched !== null) { config._d = new Date(+matched[1]); return; } configFromISO(config); if (config._isValid === false) { delete config._isValid; } else { return; } configFromRFC2822(config); if (config._isValid === false) { delete config._isValid; } else { return; } if (config._strict) { config._isValid = false; } else { hooks.createFromInputFallback(config); } } hooks.createFromInputFallback = deprecate( "value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.", function(config) { config._d = new Date(config._i + (config._useUTC ? " UTC" : "")); } ); function defaults2(a2, b, c) { if (a2 != null) { return a2; } if (b != null) { return b; } return c; } function currentDateArray(config) { var nowValue = new Date(hooks.now()); if (config._useUTC) { return [ nowValue.getUTCFullYear(), nowValue.getUTCMonth(), nowValue.getUTCDate() ]; } return [nowValue.getFullYear(), nowValue.getMonth(), nowValue.getDate()]; } function configFromArray(config) { var i, date, input = [], currentDate, expectedWeekday, yearToUse; if (config._d) { return; } currentDate = currentDateArray(config); if (config._w && config._a[DATE] == null && config._a[MONTH] == null) { dayOfYearFromWeekInfo(config); } if (config._dayOfYear != null) { yearToUse = defaults2(config._a[YEAR], currentDate[YEAR]); if (config._dayOfYear > daysInYear(yearToUse) || config._dayOfYear === 0) { getParsingFlags(config)._overflowDayOfYear = true; } date = createUTCDate(yearToUse, 0, config._dayOfYear); config._a[MONTH] = date.getUTCMonth(); config._a[DATE] = date.getUTCDate(); } for (i = 0; i < 3 && config._a[i] == null; ++i) { config._a[i] = input[i] = currentDate[i]; } for (; i < 7; i++) { config._a[i] = input[i] = config._a[i] == null ? i === 2 ? 1 : 0 : config._a[i]; } if (config._a[HOUR] === 24 && config._a[MINUTE] === 0 && config._a[SECOND] === 0 && config._a[MILLISECOND] === 0) { config._nextDay = true; config._a[HOUR] = 0; } config._d = (config._useUTC ? createUTCDate : createDate).apply( null, input ); expectedWeekday = config._useUTC ? config._d.getUTCDay() : config._d.getDay(); if (config._tzm != null) { config._d.setUTCMinutes(config._d.getUTCMinutes() - config._tzm); } if (config._nextDay) { config._a[HOUR] = 24; } if (config._w && typeof config._w.d !== "undefined" && config._w.d !== expectedWeekday) { getParsingFlags(config).weekdayMismatch = true; } } function dayOfYearFromWeekInfo(config) { var w, weekYear, week, weekday, dow, doy, temp, weekdayOverflow, curWeek; w = config._w; if (w.GG != null || w.W != null || w.E != null) { dow = 1; doy = 4; weekYear = defaults2( w.GG, config._a[YEAR], weekOfYear(createLocal(), 1, 4).year ); week = defaults2(w.W, 1); weekday = defaults2(w.E, 1); if (weekday < 1 || weekday > 7) { weekdayOverflow = true; } } else { dow = config._locale._week.dow; doy = config._locale._week.doy; curWeek = weekOfYear(createLocal(), dow, doy); weekYear = defaults2(w.gg, config._a[YEAR], curWeek.year); week = defaults2(w.w, curWeek.week); if (w.d != null) { weekday = w.d; if (weekday < 0 || weekday > 6) { weekdayOverflow = true; } } else if (w.e != null) { weekday = w.e + dow; if (w.e < 0 || w.e > 6) { weekdayOverflow = true; } } else { weekday = dow; } } if (week < 1 || week > weeksInYear(weekYear, dow, doy)) { getParsingFlags(config)._overflowWeeks = true; } else if (weekdayOverflow != null) { getParsingFlags(config)._overflowWeekday = true; } else { temp = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy); config._a[YEAR] = temp.year; config._dayOfYear = temp.dayOfYear; } } hooks.ISO_8601 = function() { }; hooks.RFC_2822 = function() { }; function configFromStringAndFormat(config) { if (config._f === hooks.ISO_8601) { configFromISO(config); return; } if (config._f === hooks.RFC_2822) { configFromRFC2822(config); return; } config._a = []; getParsingFlags(config).empty = true; var string3 = "" + config._i, i, parsedInput, tokens2, token2, skipped, stringLength = string3.length, totalParsedInputLength = 0, era, tokenLen; tokens2 = expandFormat(config._f, config._locale).match(formattingTokens) || []; tokenLen = tokens2.length; for (i = 0; i < tokenLen; i++) { token2 = tokens2[i]; parsedInput = (string3.match(getParseRegexForToken(token2, config)) || [])[0]; if (parsedInput) { skipped = string3.substr(0, string3.indexOf(parsedInput)); if (skipped.length > 0) { getParsingFlags(config).unusedInput.push(skipped); } string3 = string3.slice( string3.indexOf(parsedInput) + parsedInput.length ); totalParsedInputLength += parsedInput.length; } if (formatTokenFunctions[token2]) { if (parsedInput) { getParsingFlags(config).empty = false; } else { getParsingFlags(config).unusedTokens.push(token2); } addTimeToArrayFromToken(token2, parsedInput, config); } else if (config._strict && !parsedInput) { getParsingFlags(config).unusedTokens.push(token2); } } getParsingFlags(config).charsLeftOver = stringLength - totalParsedInputLength; if (string3.length > 0) { getParsingFlags(config).unusedInput.push(string3); } if (config._a[HOUR] <= 12 && getParsingFlags(config).bigHour === true && config._a[HOUR] > 0) { getParsingFlags(config).bigHour = void 0; } getParsingFlags(config).parsedDateParts = config._a.slice(0); getParsingFlags(config).meridiem = config._meridiem; config._a[HOUR] = meridiemFixWrap( config._locale, config._a[HOUR], config._meridiem ); era = getParsingFlags(config).era; if (era !== null) { config._a[YEAR] = config._locale.erasConvertYear(era, config._a[YEAR]); } configFromArray(config); checkOverflow(config); } function meridiemFixWrap(locale2, hour, meridiem2) { var isPm; if (meridiem2 == null) { return hour; } if (locale2.meridiemHour != null) { return locale2.meridiemHour(hour, meridiem2); } else if (locale2.isPM != null) { isPm = locale2.isPM(meridiem2); if (isPm && hour < 12) { hour += 12; } if (!isPm && hour === 12) { hour = 0; } return hour; } else { return hour; } } function configFromStringAndArray(config) { var tempConfig, bestMoment, scoreToBeat, i, currentScore, validFormatFound, bestFormatIsValid = false, configfLen = config._f.length; if (configfLen === 0) { getParsingFlags(config).invalidFormat = true; config._d = new Date(NaN); return; } for (i = 0; i < configfLen; i++) { currentScore = 0; validFormatFound = false; tempConfig = copyConfig({}, config); if (config._useUTC != null) { tempConfig._useUTC = config._useUTC; } tempConfig._f = config._f[i]; configFromStringAndFormat(tempConfig); if (isValid(tempConfig)) { validFormatFound = true; } currentScore += getParsingFlags(tempConfig).charsLeftOver; currentScore += getParsingFlags(tempConfig).unusedTokens.length * 10; getParsingFlags(tempConfig).score = currentScore; if (!bestFormatIsValid) { if (scoreToBeat == null || currentScore < scoreToBeat || validFormatFound) { scoreToBeat = currentScore; bestMoment = tempConfig; if (validFormatFound) { bestFormatIsValid = true; } } } else { if (currentScore < scoreToBeat) { scoreToBeat = currentScore; bestMoment = tempConfig; } } } extend5(config, bestMoment || tempConfig); } function configFromObject(config) { if (config._d) { return; } var i = normalizeObjectUnits(config._i), dayOrDate = i.day === void 0 ? i.date : i.day; config._a = map2( [i.year, i.month, dayOrDate, i.hour, i.minute, i.second, i.millisecond], function(obj) { return obj && parseInt(obj, 10); } ); configFromArray(config); } function createFromConfig(config) { var res = new Moment(checkOverflow(prepareConfig(config))); if (res._nextDay) { res.add(1, "d"); res._nextDay = void 0; } return res; } function prepareConfig(config) { var input = config._i, format2 = config._f; config._locale = config._locale || getLocale(config._l); if (input === null || format2 === void 0 && input === "") { return createInvalid({ nullInput: true }); } if (typeof input === "string") { config._i = input = config._locale.preparse(input); } if (isMoment(input)) { return new Moment(checkOverflow(input)); } else if (isDate3(input)) { config._d = input; } else if (isArray4(format2)) { configFromStringAndArray(config); } else if (format2) { configFromStringAndFormat(config); } else { configFromInput(config); } if (!isValid(config)) { config._d = null; } return config; } function configFromInput(config) { var input = config._i; if (isUndefined3(input)) { config._d = new Date(hooks.now()); } else if (isDate3(input)) { config._d = new Date(input.valueOf()); } else if (typeof input === "string") { configFromString(config); } else if (isArray4(input)) { config._a = map2(input.slice(0), function(obj) { return parseInt(obj, 10); }); configFromArray(config); } else if (isObject4(input)) { configFromObject(config); } else if (isNumber2(input)) { config._d = new Date(input); } else { hooks.createFromInputFallback(config); } } function createLocalOrUTC(input, format2, locale2, strict, isUTC) { var c = {}; if (format2 === true || format2 === false) { strict = format2; format2 = void 0; } if (locale2 === true || locale2 === false) { strict = locale2; locale2 = void 0; } if (isObject4(input) && isObjectEmpty(input) || isArray4(input) && input.length === 0) { input = void 0; } c._isAMomentObject = true; c._useUTC = c._isUTC = isUTC; c._l = locale2; c._i = input; c._f = format2; c._strict = strict; return createFromConfig(c); } function createLocal(input, format2, locale2, strict) { return createLocalOrUTC(input, format2, locale2, strict, false); } var prototypeMin = deprecate( "moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/", function() { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other < this ? this : other; } else { return createInvalid(); } } ), prototypeMax = deprecate( "moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/", function() { var other = createLocal.apply(null, arguments); if (this.isValid() && other.isValid()) { return other > this ? this : other; } else { return createInvalid(); } } ); function pickBy(fn, moments) { var res, i; if (moments.length === 1 && isArray4(moments[0])) { moments = moments[0]; } if (!moments.length) { return createLocal(); } res = moments[0]; for (i = 1; i < moments.length; ++i) { if (!moments[i].isValid() || moments[i][fn](res)) { res = moments[i]; } } return res; } function min() { var args = [].slice.call(arguments, 0); return pickBy("isBefore", args); } function max() { var args = [].slice.call(arguments, 0); return pickBy("isAfter", args); } var now = function() { return Date.now ? Date.now() : +new Date(); }; var ordering = [ "year", "quarter", "month", "week", "day", "hour", "minute", "second", "millisecond" ]; function isDurationValid(m) { var key, unitHasDecimal = false, i, orderLen = ordering.length; for (key in m) { if (hasOwnProp(m, key) && !(indexOf.call(ordering, key) !== -1 && (m[key] == null || !isNaN(m[key])))) { return false; } } for (i = 0; i < orderLen; ++i) { if (m[ordering[i]]) { if (unitHasDecimal) { return false; } if (parseFloat(m[ordering[i]]) !== toInt(m[ordering[i]])) { unitHasDecimal = true; } } } return true; } function isValid$1() { return this._isValid; } function createInvalid$1() { return createDuration(NaN); } function Duration(duration) { var normalizedInput = normalizeObjectUnits(duration), years2 = normalizedInput.year || 0, quarters = normalizedInput.quarter || 0, months2 = normalizedInput.month || 0, weeks2 = normalizedInput.week || normalizedInput.isoWeek || 0, days2 = normalizedInput.day || 0, hours2 = normalizedInput.hour || 0, minutes2 = normalizedInput.minute || 0, seconds2 = normalizedInput.second || 0, milliseconds2 = normalizedInput.millisecond || 0; this._isValid = isDurationValid(normalizedInput); this._milliseconds = +milliseconds2 + seconds2 * 1e3 + // 1000 minutes2 * 6e4 + // 1000 * 60 hours2 * 1e3 * 60 * 60; this._days = +days2 + weeks2 * 7; this._months = +months2 + quarters * 3 + years2 * 12; this._data = {}; this._locale = getLocale(); this._bubble(); } function isDuration(obj) { return obj instanceof Duration; } function absRound(number2) { if (number2 < 0) { return Math.round(-1 * number2) * -1; } else { return Math.round(number2); } } function compareArrays(array1, array2, dontConvert) { var len = Math.min(array1.length, array2.length), lengthDiff = Math.abs(array1.length - array2.length), diffs = 0, i; for (i = 0; i < len; i++) { if (dontConvert && array1[i] !== array2[i] || !dontConvert && toInt(array1[i]) !== toInt(array2[i])) { diffs++; } } return diffs + lengthDiff; } function offset(token2, separator) { addFormatToken(token2, 0, 0, function() { var offset2 = this.utcOffset(), sign2 = "+"; if (offset2 < 0) { offset2 = -offset2; sign2 = "-"; } return sign2 + zeroFill(~~(offset2 / 60), 2) + separator + zeroFill(~~offset2 % 60, 2); }); } offset("Z", ":"); offset("ZZ", ""); addRegexToken("Z", matchShortOffset); addRegexToken("ZZ", matchShortOffset); addParseToken(["Z", "ZZ"], function(input, array, config) { config._useUTC = true; config._tzm = offsetFromString(matchShortOffset, input); }); var chunkOffset = /([\+\-]|\d\d)/gi; function offsetFromString(matcher, string3) { var matches = (string3 || "").match(matcher), chunk, parts, minutes2; if (matches === null) { return null; } chunk = matches[matches.length - 1] || []; parts = (chunk + "").match(chunkOffset) || ["-", 0, 0]; minutes2 = +(parts[1] * 60) + toInt(parts[2]); return minutes2 === 0 ? 0 : parts[0] === "+" ? minutes2 : -minutes2; } function cloneWithOffset(input, model) { var res, diff2; if (model._isUTC) { res = model.clone(); diff2 = (isMoment(input) || isDate3(input) ? input.valueOf() : createLocal(input).valueOf()) - res.valueOf(); res._d.setTime(res._d.valueOf() + diff2); hooks.updateOffset(res, false); return res; } else { return createLocal(input).local(); } } function getDateOffset(m) { return -Math.round(m._d.getTimezoneOffset()); } hooks.updateOffset = function() { }; function getSetOffset(input, keepLocalTime, keepMinutes) { var offset2 = this._offset || 0, localAdjust; if (!this.isValid()) { return input != null ? this : NaN; } if (input != null) { if (typeof input === "string") { input = offsetFromString(matchShortOffset, input); if (input === null) { return this; } } else if (Math.abs(input) < 16 && !keepMinutes) { input = input * 60; } if (!this._isUTC && keepLocalTime) { localAdjust = getDateOffset(this); } this._offset = input; this._isUTC = true; if (localAdjust != null) { this.add(localAdjust, "m"); } if (offset2 !== input) { if (!keepLocalTime || this._changeInProgress) { addSubtract( this, createDuration(input - offset2, "m"), 1, false ); } else if (!this._changeInProgress) { this._changeInProgress = true; hooks.updateOffset(this, true); this._changeInProgress = null; } } return this; } else { return this._isUTC ? offset2 : getDateOffset(this); } } function getSetZone(input, keepLocalTime) { if (input != null) { if (typeof input !== "string") { input = -input; } this.utcOffset(input, keepLocalTime); return this; } else { return -this.utcOffset(); } } function setOffsetToUTC(keepLocalTime) { return this.utcOffset(0, keepLocalTime); } function setOffsetToLocal(keepLocalTime) { if (this._isUTC) { this.utcOffset(0, keepLocalTime); this._isUTC = false; if (keepLocalTime) { this.subtract(getDateOffset(this), "m"); } } return this; } function setOffsetToParsedOffset() { if (this._tzm != null) { this.utcOffset(this._tzm, false, true); } else if (typeof this._i === "string") { var tZone = offsetFromString(matchOffset, this._i); if (tZone != null) { this.utcOffset(tZone); } else { this.utcOffset(0, true); } } return this; } function hasAlignedHourOffset(input) { if (!this.isValid()) { return false; } input = input ? createLocal(input).utcOffset() : 0; return (this.utcOffset() - input) % 60 === 0; } function isDaylightSavingTime() { return this.utcOffset() > this.clone().month(0).utcOffset() || this.utcOffset() > this.clone().month(5).utcOffset(); } function isDaylightSavingTimeShifted() { if (!isUndefined3(this._isDSTShifted)) { return this._isDSTShifted; } var c = {}, other; copyConfig(c, this); c = prepareConfig(c); if (c._a) { other = c._isUTC ? createUTC(c._a) : createLocal(c._a); this._isDSTShifted = this.isValid() && compareArrays(c._a, other.toArray()) > 0; } else { this._isDSTShifted = false; } return this._isDSTShifted; } function isLocal() { return this.isValid() ? !this._isUTC : false; } function isUtcOffset() { return this.isValid() ? this._isUTC : false; } function isUtc() { return this.isValid() ? this._isUTC && this._offset === 0 : false; } var aspNetRegex = /^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/, isoRegex = /^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/; function createDuration(input, key) { var duration = input, match5 = null, sign2, ret, diffRes; if (isDuration(input)) { duration = { ms: input._milliseconds, d: input._days, M: input._months }; } else if (isNumber2(input) || !isNaN(+input)) { duration = {}; if (key) { duration[key] = +input; } else { duration.milliseconds = +input; } } else if (match5 = aspNetRegex.exec(input)) { sign2 = match5[1] === "-" ? -1 : 1; duration = { y: 0, d: toInt(match5[DATE]) * sign2, h: toInt(match5[HOUR]) * sign2, m: toInt(match5[MINUTE]) * sign2, s: toInt(match5[SECOND]) * sign2, ms: toInt(absRound(match5[MILLISECOND] * 1e3)) * sign2 // the millisecond decimal point is included in the match }; } else if (match5 = isoRegex.exec(input)) { sign2 = match5[1] === "-" ? -1 : 1; duration = { y: parseIso(match5[2], sign2), M: parseIso(match5[3], sign2), w: parseIso(match5[4], sign2), d: parseIso(match5[5], sign2), h: parseIso(match5[6], sign2), m: parseIso(match5[7], sign2), s: parseIso(match5[8], sign2) }; } else if (duration == null) { duration = {}; } else if (typeof duration === "object" && ("from" in duration || "to" in duration)) { diffRes = momentsDifference( createLocal(duration.from), createLocal(duration.to) ); duration = {}; duration.ms = diffRes.milliseconds; duration.M = diffRes.months; } ret = new Duration(duration); if (isDuration(input) && hasOwnProp(input, "_locale")) { ret._locale = input._locale; } if (isDuration(input) && hasOwnProp(input, "_isValid")) { ret._isValid = input._isValid; } return ret; } createDuration.fn = Duration.prototype; createDuration.invalid = createInvalid$1; function parseIso(inp, sign2) { var res = inp && parseFloat(inp.replace(",", ".")); return (isNaN(res) ? 0 : res) * sign2; } function positiveMomentsDifference(base2, other) { var res = {}; res.months = other.month() - base2.month() + (other.year() - base2.year()) * 12; if (base2.clone().add(res.months, "M").isAfter(other)) { --res.months; } res.milliseconds = +other - +base2.clone().add(res.months, "M"); return res; } function momentsDifference(base2, other) { var res; if (!(base2.isValid() && other.isValid())) { return { milliseconds: 0, months: 0 }; } other = cloneWithOffset(other, base2); if (base2.isBefore(other)) { res = positiveMomentsDifference(base2, other); } else { res = positiveMomentsDifference(other, base2); res.milliseconds = -res.milliseconds; res.months = -res.months; } return res; } function createAdder(direction, name) { return function(val, period) { var dur, tmp; if (period !== null && !isNaN(+period)) { deprecateSimple( name, "moment()." + name + "(period, number) is deprecated. Please use moment()." + name + "(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info." ); tmp = val; val = period; period = tmp; } dur = createDuration(val, period); addSubtract(this, dur, direction); return this; }; } function addSubtract(mom, duration, isAdding, updateOffset) { var milliseconds2 = duration._milliseconds, days2 = absRound(duration._days), months2 = absRound(duration._months); if (!mom.isValid()) { return; } updateOffset = updateOffset == null ? true : updateOffset; if (months2) { setMonth(mom, get(mom, "Month") + months2 * isAdding); } if (days2) { set$1(mom, "Date", get(mom, "Date") + days2 * isAdding); } if (milliseconds2) { mom._d.setTime(mom._d.valueOf() + milliseconds2 * isAdding); } if (updateOffset) { hooks.updateOffset(mom, days2 || months2); } } var add = createAdder(1, "add"), subtract = createAdder(-1, "subtract"); function isString2(input) { return typeof input === "string" || input instanceof String; } function isMomentInput(input) { return isMoment(input) || isDate3(input) || isString2(input) || isNumber2(input) || isNumberOrStringArray(input) || isMomentInputObject(input) || input === null || input === void 0; } function isMomentInputObject(input) { var objectTest = isObject4(input) && !isObjectEmpty(input), propertyTest = false, properties = [ "years", "year", "y", "months", "month", "M", "days", "day", "d", "dates", "date", "D", "hours", "hour", "h", "minutes", "minute", "m", "seconds", "second", "s", "milliseconds", "millisecond", "ms" ], i, property, propertyLen = properties.length; for (i = 0; i < propertyLen; i += 1) { property = properties[i]; propertyTest = propertyTest || hasOwnProp(input, property); } return objectTest && propertyTest; } function isNumberOrStringArray(input) { var arrayTest = isArray4(input), dataTypeTest = false; if (arrayTest) { dataTypeTest = input.filter(function(item) { return !isNumber2(item) && isString2(input); }).length === 0; } return arrayTest && dataTypeTest; } function isCalendarSpec(input) { var objectTest = isObject4(input) && !isObjectEmpty(input), propertyTest = false, properties = [ "sameDay", "nextDay", "lastDay", "nextWeek", "lastWeek", "sameElse" ], i, property; for (i = 0; i < properties.length; i += 1) { property = properties[i]; propertyTest = propertyTest || hasOwnProp(input, property); } return objectTest && propertyTest; } function getCalendarFormat(myMoment, now2) { var diff2 = myMoment.diff(now2, "days", true); return diff2 < -6 ? "sameElse" : diff2 < -1 ? "lastWeek" : diff2 < 0 ? "lastDay" : diff2 < 1 ? "sameDay" : diff2 < 2 ? "nextDay" : diff2 < 7 ? "nextWeek" : "sameElse"; } function calendar$1(time, formats) { if (arguments.length === 1) { if (!arguments[0]) { time = void 0; formats = void 0; } else if (isMomentInput(arguments[0])) { time = arguments[0]; formats = void 0; } else if (isCalendarSpec(arguments[0])) { formats = arguments[0]; time = void 0; } } var now2 = time || createLocal(), sod = cloneWithOffset(now2, this).startOf("day"), format2 = hooks.calendarFormat(this, sod) || "sameElse", output = formats && (isFunction2(formats[format2]) ? formats[format2].call(this, now2) : formats[format2]); return this.format( output || this.localeData().calendar(format2, this, createLocal(now2)) ); } function clone2() { return new Moment(this); } function isAfter(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || "millisecond"; if (units === "millisecond") { return this.valueOf() > localInput.valueOf(); } else { return localInput.valueOf() < this.clone().startOf(units).valueOf(); } } function isBefore(input, units) { var localInput = isMoment(input) ? input : createLocal(input); if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || "millisecond"; if (units === "millisecond") { return this.valueOf() < localInput.valueOf(); } else { return this.clone().endOf(units).valueOf() < localInput.valueOf(); } } function isBetween(from2, to2, units, inclusivity) { var localFrom = isMoment(from2) ? from2 : createLocal(from2), localTo = isMoment(to2) ? to2 : createLocal(to2); if (!(this.isValid() && localFrom.isValid() && localTo.isValid())) { return false; } inclusivity = inclusivity || "()"; return (inclusivity[0] === "(" ? this.isAfter(localFrom, units) : !this.isBefore(localFrom, units)) && (inclusivity[1] === ")" ? this.isBefore(localTo, units) : !this.isAfter(localTo, units)); } function isSame(input, units) { var localInput = isMoment(input) ? input : createLocal(input), inputMs; if (!(this.isValid() && localInput.isValid())) { return false; } units = normalizeUnits(units) || "millisecond"; if (units === "millisecond") { return this.valueOf() === localInput.valueOf(); } else { inputMs = localInput.valueOf(); return this.clone().startOf(units).valueOf() <= inputMs && inputMs <= this.clone().endOf(units).valueOf(); } } function isSameOrAfter(input, units) { return this.isSame(input, units) || this.isAfter(input, units); } function isSameOrBefore(input, units) { return this.isSame(input, units) || this.isBefore(input, units); } function diff(input, units, asFloat) { var that, zoneDelta, output; if (!this.isValid()) { return NaN; } that = cloneWithOffset(input, this); if (!that.isValid()) { return NaN; } zoneDelta = (that.utcOffset() - this.utcOffset()) * 6e4; units = normalizeUnits(units); switch (units) { case "year": output = monthDiff(this, that) / 12; break; case "month": output = monthDiff(this, that); break; case "quarter": output = monthDiff(this, that) / 3; break; case "second": output = (this - that) / 1e3; break; case "minute": output = (this - that) / 6e4; break; case "hour": output = (this - that) / 36e5; break; case "day": output = (this - that - zoneDelta) / 864e5; break; case "week": output = (this - that - zoneDelta) / 6048e5; break; default: output = this - that; } return asFloat ? output : absFloor(output); } function monthDiff(a2, b) { if (a2.date() < b.date()) { return -monthDiff(b, a2); } var wholeMonthDiff = (b.year() - a2.year()) * 12 + (b.month() - a2.month()), anchor = a2.clone().add(wholeMonthDiff, "months"), anchor2, adjust; if (b - anchor < 0) { anchor2 = a2.clone().add(wholeMonthDiff - 1, "months"); adjust = (b - anchor) / (anchor - anchor2); } else { anchor2 = a2.clone().add(wholeMonthDiff + 1, "months"); adjust = (b - anchor) / (anchor2 - anchor); } return -(wholeMonthDiff + adjust) || 0; } hooks.defaultFormat = "YYYY-MM-DDTHH:mm:ssZ"; hooks.defaultFormatUtc = "YYYY-MM-DDTHH:mm:ss[Z]"; function toString7() { return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ"); } function toISOString(keepOffset) { if (!this.isValid()) { return null; } var utc = keepOffset !== true, m = utc ? this.clone().utc() : this; if (m.year() < 0 || m.year() > 9999) { return formatMoment( m, utc ? "YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYYYY-MM-DD[T]HH:mm:ss.SSSZ" ); } if (isFunction2(Date.prototype.toISOString)) { if (utc) { return this.toDate().toISOString(); } else { return new Date(this.valueOf() + this.utcOffset() * 60 * 1e3).toISOString().replace("Z", formatMoment(m, "Z")); } } return formatMoment( m, utc ? "YYYY-MM-DD[T]HH:mm:ss.SSS[Z]" : "YYYY-MM-DD[T]HH:mm:ss.SSSZ" ); } function inspect() { if (!this.isValid()) { return "moment.invalid(/* " + this._i + " */)"; } var func = "moment", zone = "", prefix, year, datetime, suffix; if (!this.isLocal()) { func = this.utcOffset() === 0 ? "moment.utc" : "moment.parseZone"; zone = "Z"; } prefix = "[" + func + '("]'; year = 0 <= this.year() && this.year() <= 9999 ? "YYYY" : "YYYYYY"; datetime = "-MM-DD[T]HH:mm:ss.SSS"; suffix = zone + '[")]'; return this.format(prefix + year + datetime + suffix); } function format(inputString) { if (!inputString) { inputString = this.isUtc() ? hooks.defaultFormatUtc : hooks.defaultFormat; } var output = formatMoment(this, inputString); return this.localeData().postformat(output); } function from(time, withoutSuffix) { if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { return createDuration({ to: this, from: time }).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function fromNow(withoutSuffix) { return this.from(createLocal(), withoutSuffix); } function to(time, withoutSuffix) { if (this.isValid() && (isMoment(time) && time.isValid() || createLocal(time).isValid())) { return createDuration({ from: this, to: time }).locale(this.locale()).humanize(!withoutSuffix); } else { return this.localeData().invalidDate(); } } function toNow(withoutSuffix) { return this.to(createLocal(), withoutSuffix); } function locale(key) { var newLocaleData; if (key === void 0) { return this._locale._abbr; } else { newLocaleData = getLocale(key); if (newLocaleData != null) { this._locale = newLocaleData; } return this; } } var lang = deprecate( "moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.", function(key) { if (key === void 0) { return this.localeData(); } else { return this.locale(key); } } ); function localeData() { return this._locale; } var MS_PER_SECOND = 1e3, MS_PER_MINUTE = 60 * MS_PER_SECOND, MS_PER_HOUR = 60 * MS_PER_MINUTE, MS_PER_400_YEARS = (365 * 400 + 97) * 24 * MS_PER_HOUR; function mod$1(dividend, divisor) { return (dividend % divisor + divisor) % divisor; } function localStartOfDate(y, m, d) { if (y < 100 && y >= 0) { return new Date(y + 400, m, d) - MS_PER_400_YEARS; } else { return new Date(y, m, d).valueOf(); } } function utcStartOfDate(y, m, d) { if (y < 100 && y >= 0) { return Date.UTC(y + 400, m, d) - MS_PER_400_YEARS; } else { return Date.UTC(y, m, d); } } function startOf(units) { var time, startOfDate; units = normalizeUnits(units); if (units === void 0 || units === "millisecond" || !this.isValid()) { return this; } startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case "year": time = startOfDate(this.year(), 0, 1); break; case "quarter": time = startOfDate( this.year(), this.month() - this.month() % 3, 1 ); break; case "month": time = startOfDate(this.year(), this.month(), 1); break; case "week": time = startOfDate( this.year(), this.month(), this.date() - this.weekday() ); break; case "isoWeek": time = startOfDate( this.year(), this.month(), this.date() - (this.isoWeekday() - 1) ); break; case "day": case "date": time = startOfDate(this.year(), this.month(), this.date()); break; case "hour": time = this._d.valueOf(); time -= mod$1( time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR ); break; case "minute": time = this._d.valueOf(); time -= mod$1(time, MS_PER_MINUTE); break; case "second": time = this._d.valueOf(); time -= mod$1(time, MS_PER_SECOND); break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function endOf(units) { var time, startOfDate; units = normalizeUnits(units); if (units === void 0 || units === "millisecond" || !this.isValid()) { return this; } startOfDate = this._isUTC ? utcStartOfDate : localStartOfDate; switch (units) { case "year": time = startOfDate(this.year() + 1, 0, 1) - 1; break; case "quarter": time = startOfDate( this.year(), this.month() - this.month() % 3 + 3, 1 ) - 1; break; case "month": time = startOfDate(this.year(), this.month() + 1, 1) - 1; break; case "week": time = startOfDate( this.year(), this.month(), this.date() - this.weekday() + 7 ) - 1; break; case "isoWeek": time = startOfDate( this.year(), this.month(), this.date() - (this.isoWeekday() - 1) + 7 ) - 1; break; case "day": case "date": time = startOfDate(this.year(), this.month(), this.date() + 1) - 1; break; case "hour": time = this._d.valueOf(); time += MS_PER_HOUR - mod$1( time + (this._isUTC ? 0 : this.utcOffset() * MS_PER_MINUTE), MS_PER_HOUR ) - 1; break; case "minute": time = this._d.valueOf(); time += MS_PER_MINUTE - mod$1(time, MS_PER_MINUTE) - 1; break; case "second": time = this._d.valueOf(); time += MS_PER_SECOND - mod$1(time, MS_PER_SECOND) - 1; break; } this._d.setTime(time); hooks.updateOffset(this, true); return this; } function valueOf() { return this._d.valueOf() - (this._offset || 0) * 6e4; } function unix() { return Math.floor(this.valueOf() / 1e3); } function toDate() { return new Date(this.valueOf()); } function toArray4() { var m = this; return [ m.year(), m.month(), m.date(), m.hour(), m.minute(), m.second(), m.millisecond() ]; } function toObject2() { var m = this; return { years: m.year(), months: m.month(), date: m.date(), hours: m.hours(), minutes: m.minutes(), seconds: m.seconds(), milliseconds: m.milliseconds() }; } function toJSON3() { return this.isValid() ? this.toISOString() : null; } function isValid$2() { return isValid(this); } function parsingFlags() { return extend5({}, getParsingFlags(this)); } function invalidAt() { return getParsingFlags(this).overflow; } function creationData() { return { input: this._i, format: this._f, locale: this._locale, isUTC: this._isUTC, strict: this._strict }; } addFormatToken("N", 0, 0, "eraAbbr"); addFormatToken("NN", 0, 0, "eraAbbr"); addFormatToken("NNN", 0, 0, "eraAbbr"); addFormatToken("NNNN", 0, 0, "eraName"); addFormatToken("NNNNN", 0, 0, "eraNarrow"); addFormatToken("y", ["y", 1], "yo", "eraYear"); addFormatToken("y", ["yy", 2], 0, "eraYear"); addFormatToken("y", ["yyy", 3], 0, "eraYear"); addFormatToken("y", ["yyyy", 4], 0, "eraYear"); addRegexToken("N", matchEraAbbr); addRegexToken("NN", matchEraAbbr); addRegexToken("NNN", matchEraAbbr); addRegexToken("NNNN", matchEraName); addRegexToken("NNNNN", matchEraNarrow); addParseToken( ["N", "NN", "NNN", "NNNN", "NNNNN"], function(input, array, config, token2) { var era = config._locale.erasParse(input, token2, config._strict); if (era) { getParsingFlags(config).era = era; } else { getParsingFlags(config).invalidEra = input; } } ); addRegexToken("y", matchUnsigned); addRegexToken("yy", matchUnsigned); addRegexToken("yyy", matchUnsigned); addRegexToken("yyyy", matchUnsigned); addRegexToken("yo", matchEraYearOrdinal); addParseToken(["y", "yy", "yyy", "yyyy"], YEAR); addParseToken(["yo"], function(input, array, config, token2) { var match5; if (config._locale._eraYearOrdinalRegex) { match5 = input.match(config._locale._eraYearOrdinalRegex); } if (config._locale.eraYearOrdinalParse) { array[YEAR] = config._locale.eraYearOrdinalParse(input, match5); } else { array[YEAR] = parseInt(input, 10); } }); function localeEras(m, format2) { var i, l, date, eras = this._eras || getLocale("en")._eras; for (i = 0, l = eras.length; i < l; ++i) { switch (typeof eras[i].since) { case "string": date = hooks(eras[i].since).startOf("day"); eras[i].since = date.valueOf(); break; } switch (typeof eras[i].until) { case "undefined": eras[i].until = Infinity; break; case "string": date = hooks(eras[i].until).startOf("day").valueOf(); eras[i].until = date.valueOf(); break; } } return eras; } function localeErasParse(eraName, format2, strict) { var i, l, eras = this.eras(), name, abbr, narrow; eraName = eraName.toUpperCase(); for (i = 0, l = eras.length; i < l; ++i) { name = eras[i].name.toUpperCase(); abbr = eras[i].abbr.toUpperCase(); narrow = eras[i].narrow.toUpperCase(); if (strict) { switch (format2) { case "N": case "NN": case "NNN": if (abbr === eraName) { return eras[i]; } break; case "NNNN": if (name === eraName) { return eras[i]; } break; case "NNNNN": if (narrow === eraName) { return eras[i]; } break; } } else if ([name, abbr, narrow].indexOf(eraName) >= 0) { return eras[i]; } } } function localeErasConvertYear(era, year) { var dir = era.since <= era.until ? 1 : -1; if (year === void 0) { return hooks(era.since).year(); } else { return hooks(era.since).year() + (year - era.offset) * dir; } } function getEraName() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { val = this.clone().startOf("day").valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].name; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].name; } } return ""; } function getEraNarrow() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { val = this.clone().startOf("day").valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].narrow; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].narrow; } } return ""; } function getEraAbbr() { var i, l, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { val = this.clone().startOf("day").valueOf(); if (eras[i].since <= val && val <= eras[i].until) { return eras[i].abbr; } if (eras[i].until <= val && val <= eras[i].since) { return eras[i].abbr; } } return ""; } function getEraYear() { var i, l, dir, val, eras = this.localeData().eras(); for (i = 0, l = eras.length; i < l; ++i) { dir = eras[i].since <= eras[i].until ? 1 : -1; val = this.clone().startOf("day").valueOf(); if (eras[i].since <= val && val <= eras[i].until || eras[i].until <= val && val <= eras[i].since) { return (this.year() - hooks(eras[i].since).year()) * dir + eras[i].offset; } } return this.year(); } function erasNameRegex(isStrict) { if (!hasOwnProp(this, "_erasNameRegex")) { computeErasParse.call(this); } return isStrict ? this._erasNameRegex : this._erasRegex; } function erasAbbrRegex(isStrict) { if (!hasOwnProp(this, "_erasAbbrRegex")) { computeErasParse.call(this); } return isStrict ? this._erasAbbrRegex : this._erasRegex; } function erasNarrowRegex(isStrict) { if (!hasOwnProp(this, "_erasNarrowRegex")) { computeErasParse.call(this); } return isStrict ? this._erasNarrowRegex : this._erasRegex; } function matchEraAbbr(isStrict, locale2) { return locale2.erasAbbrRegex(isStrict); } function matchEraName(isStrict, locale2) { return locale2.erasNameRegex(isStrict); } function matchEraNarrow(isStrict, locale2) { return locale2.erasNarrowRegex(isStrict); } function matchEraYearOrdinal(isStrict, locale2) { return locale2._eraYearOrdinalRegex || matchUnsigned; } function computeErasParse() { var abbrPieces = [], namePieces = [], narrowPieces = [], mixedPieces = [], i, l, eras = this.eras(); for (i = 0, l = eras.length; i < l; ++i) { namePieces.push(regexEscape(eras[i].name)); abbrPieces.push(regexEscape(eras[i].abbr)); narrowPieces.push(regexEscape(eras[i].narrow)); mixedPieces.push(regexEscape(eras[i].name)); mixedPieces.push(regexEscape(eras[i].abbr)); mixedPieces.push(regexEscape(eras[i].narrow)); } this._erasRegex = new RegExp("^(" + mixedPieces.join("|") + ")", "i"); this._erasNameRegex = new RegExp("^(" + namePieces.join("|") + ")", "i"); this._erasAbbrRegex = new RegExp("^(" + abbrPieces.join("|") + ")", "i"); this._erasNarrowRegex = new RegExp( "^(" + narrowPieces.join("|") + ")", "i" ); } addFormatToken(0, ["gg", 2], 0, function() { return this.weekYear() % 100; }); addFormatToken(0, ["GG", 2], 0, function() { return this.isoWeekYear() % 100; }); function addWeekYearFormatToken(token2, getter) { addFormatToken(0, [token2, token2.length], 0, getter); } addWeekYearFormatToken("gggg", "weekYear"); addWeekYearFormatToken("ggggg", "weekYear"); addWeekYearFormatToken("GGGG", "isoWeekYear"); addWeekYearFormatToken("GGGGG", "isoWeekYear"); addUnitAlias("weekYear", "gg"); addUnitAlias("isoWeekYear", "GG"); addUnitPriority("weekYear", 1); addUnitPriority("isoWeekYear", 1); addRegexToken("G", matchSigned); addRegexToken("g", matchSigned); addRegexToken("GG", match1to2, match2); addRegexToken("gg", match1to2, match2); addRegexToken("GGGG", match1to4, match4); addRegexToken("gggg", match1to4, match4); addRegexToken("GGGGG", match1to6, match6); addRegexToken("ggggg", match1to6, match6); addWeekParseToken( ["gggg", "ggggg", "GGGG", "GGGGG"], function(input, week, config, token2) { week[token2.substr(0, 2)] = toInt(input); } ); addWeekParseToken(["gg", "GG"], function(input, week, config, token2) { week[token2] = hooks.parseTwoDigitYear(input); }); function getSetWeekYear(input) { return getSetWeekYearHelper.call( this, input, this.week(), this.weekday(), this.localeData()._week.dow, this.localeData()._week.doy ); } function getSetISOWeekYear(input) { return getSetWeekYearHelper.call( this, input, this.isoWeek(), this.isoWeekday(), 1, 4 ); } function getISOWeeksInYear() { return weeksInYear(this.year(), 1, 4); } function getISOWeeksInISOWeekYear() { return weeksInYear(this.isoWeekYear(), 1, 4); } function getWeeksInYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.year(), weekInfo.dow, weekInfo.doy); } function getWeeksInWeekYear() { var weekInfo = this.localeData()._week; return weeksInYear(this.weekYear(), weekInfo.dow, weekInfo.doy); } function getSetWeekYearHelper(input, week, weekday, dow, doy) { var weeksTarget; if (input == null) { return weekOfYear(this, dow, doy).year; } else { weeksTarget = weeksInYear(input, dow, doy); if (week > weeksTarget) { week = weeksTarget; } return setWeekAll.call(this, input, week, weekday, dow, doy); } } function setWeekAll(weekYear, week, weekday, dow, doy) { var dayOfYearData = dayOfYearFromWeeks(weekYear, week, weekday, dow, doy), date = createUTCDate(dayOfYearData.year, 0, dayOfYearData.dayOfYear); this.year(date.getUTCFullYear()); this.month(date.getUTCMonth()); this.date(date.getUTCDate()); return this; } addFormatToken("Q", 0, "Qo", "quarter"); addUnitAlias("quarter", "Q"); addUnitPriority("quarter", 7); addRegexToken("Q", match1); addParseToken("Q", function(input, array) { array[MONTH] = (toInt(input) - 1) * 3; }); function getSetQuarter(input) { return input == null ? Math.ceil((this.month() + 1) / 3) : this.month((input - 1) * 3 + this.month() % 3); } addFormatToken("D", ["DD", 2], "Do", "date"); addUnitAlias("date", "D"); addUnitPriority("date", 9); addRegexToken("D", match1to2); addRegexToken("DD", match1to2, match2); addRegexToken("Do", function(isStrict, locale2) { return isStrict ? locale2._dayOfMonthOrdinalParse || locale2._ordinalParse : locale2._dayOfMonthOrdinalParseLenient; }); addParseToken(["D", "DD"], DATE); addParseToken("Do", function(input, array) { array[DATE] = toInt(input.match(match1to2)[0]); }); var getSetDayOfMonth = makeGetSet("Date", true); addFormatToken("DDD", ["DDDD", 3], "DDDo", "dayOfYear"); addUnitAlias("dayOfYear", "DDD"); addUnitPriority("dayOfYear", 4); addRegexToken("DDD", match1to3); addRegexToken("DDDD", match3); addParseToken(["DDD", "DDDD"], function(input, array, config) { config._dayOfYear = toInt(input); }); function getSetDayOfYear(input) { var dayOfYear = Math.round( (this.clone().startOf("day") - this.clone().startOf("year")) / 864e5 ) + 1; return input == null ? dayOfYear : this.add(input - dayOfYear, "d"); } addFormatToken("m", ["mm", 2], 0, "minute"); addUnitAlias("minute", "m"); addUnitPriority("minute", 14); addRegexToken("m", match1to2); addRegexToken("mm", match1to2, match2); addParseToken(["m", "mm"], MINUTE); var getSetMinute = makeGetSet("Minutes", false); addFormatToken("s", ["ss", 2], 0, "second"); addUnitAlias("second", "s"); addUnitPriority("second", 15); addRegexToken("s", match1to2); addRegexToken("ss", match1to2, match2); addParseToken(["s", "ss"], SECOND); var getSetSecond = makeGetSet("Seconds", false); addFormatToken("S", 0, 0, function() { return ~~(this.millisecond() / 100); }); addFormatToken(0, ["SS", 2], 0, function() { return ~~(this.millisecond() / 10); }); addFormatToken(0, ["SSS", 3], 0, "millisecond"); addFormatToken(0, ["SSSS", 4], 0, function() { return this.millisecond() * 10; }); addFormatToken(0, ["SSSSS", 5], 0, function() { return this.millisecond() * 100; }); addFormatToken(0, ["SSSSSS", 6], 0, function() { return this.millisecond() * 1e3; }); addFormatToken(0, ["SSSSSSS", 7], 0, function() { return this.millisecond() * 1e4; }); addFormatToken(0, ["SSSSSSSS", 8], 0, function() { return this.millisecond() * 1e5; }); addFormatToken(0, ["SSSSSSSSS", 9], 0, function() { return this.millisecond() * 1e6; }); addUnitAlias("millisecond", "ms"); addUnitPriority("millisecond", 16); addRegexToken("S", match1to3, match1); addRegexToken("SS", match1to3, match2); addRegexToken("SSS", match1to3, match3); var token, getSetMillisecond; for (token = "SSSS"; token.length <= 9; token += "S") { addRegexToken(token, matchUnsigned); } function parseMs(input, array) { array[MILLISECOND] = toInt(("0." + input) * 1e3); } for (token = "S"; token.length <= 9; token += "S") { addParseToken(token, parseMs); } getSetMillisecond = makeGetSet("Milliseconds", false); addFormatToken("z", 0, 0, "zoneAbbr"); addFormatToken("zz", 0, 0, "zoneName"); function getZoneAbbr() { return this._isUTC ? "UTC" : ""; } function getZoneName() { return this._isUTC ? "Coordinated Universal Time" : ""; } var proto = Moment.prototype; proto.add = add; proto.calendar = calendar$1; proto.clone = clone2; proto.diff = diff; proto.endOf = endOf; proto.format = format; proto.from = from; proto.fromNow = fromNow; proto.to = to; proto.toNow = toNow; proto.get = stringGet; proto.invalidAt = invalidAt; proto.isAfter = isAfter; proto.isBefore = isBefore; proto.isBetween = isBetween; proto.isSame = isSame; proto.isSameOrAfter = isSameOrAfter; proto.isSameOrBefore = isSameOrBefore; proto.isValid = isValid$2; proto.lang = lang; proto.locale = locale; proto.localeData = localeData; proto.max = prototypeMax; proto.min = prototypeMin; proto.parsingFlags = parsingFlags; proto.set = stringSet; proto.startOf = startOf; proto.subtract = subtract; proto.toArray = toArray4; proto.toObject = toObject2; proto.toDate = toDate; proto.toISOString = toISOString; proto.inspect = inspect; if (typeof Symbol !== "undefined" && Symbol.for != null) { proto[Symbol.for("nodejs.util.inspect.custom")] = function() { return "Moment<" + this.format() + ">"; }; } proto.toJSON = toJSON3; proto.toString = toString7; proto.unix = unix; proto.valueOf = valueOf; proto.creationData = creationData; proto.eraName = getEraName; proto.eraNarrow = getEraNarrow; proto.eraAbbr = getEraAbbr; proto.eraYear = getEraYear; proto.year = getSetYear; proto.isLeapYear = getIsLeapYear; proto.weekYear = getSetWeekYear; proto.isoWeekYear = getSetISOWeekYear; proto.quarter = proto.quarters = getSetQuarter; proto.month = getSetMonth; proto.daysInMonth = getDaysInMonth; proto.week = proto.weeks = getSetWeek; proto.isoWeek = proto.isoWeeks = getSetISOWeek; proto.weeksInYear = getWeeksInYear; proto.weeksInWeekYear = getWeeksInWeekYear; proto.isoWeeksInYear = getISOWeeksInYear; proto.isoWeeksInISOWeekYear = getISOWeeksInISOWeekYear; proto.date = getSetDayOfMonth; proto.day = proto.days = getSetDayOfWeek; proto.weekday = getSetLocaleDayOfWeek; proto.isoWeekday = getSetISODayOfWeek; proto.dayOfYear = getSetDayOfYear; proto.hour = proto.hours = getSetHour; proto.minute = proto.minutes = getSetMinute; proto.second = proto.seconds = getSetSecond; proto.millisecond = proto.milliseconds = getSetMillisecond; proto.utcOffset = getSetOffset; proto.utc = setOffsetToUTC; proto.local = setOffsetToLocal; proto.parseZone = setOffsetToParsedOffset; proto.hasAlignedHourOffset = hasAlignedHourOffset; proto.isDST = isDaylightSavingTime; proto.isLocal = isLocal; proto.isUtcOffset = isUtcOffset; proto.isUtc = isUtc; proto.isUTC = isUtc; proto.zoneAbbr = getZoneAbbr; proto.zoneName = getZoneName; proto.dates = deprecate( "dates accessor is deprecated. Use date instead.", getSetDayOfMonth ); proto.months = deprecate( "months accessor is deprecated. Use month instead", getSetMonth ); proto.years = deprecate( "years accessor is deprecated. Use year instead", getSetYear ); proto.zone = deprecate( "moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/", getSetZone ); proto.isDSTShifted = deprecate( "isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information", isDaylightSavingTimeShifted ); function createUnix(input) { return createLocal(input * 1e3); } function createInZone() { return createLocal.apply(null, arguments).parseZone(); } function preParsePostFormat(string3) { return string3; } var proto$1 = Locale.prototype; proto$1.calendar = calendar; proto$1.longDateFormat = longDateFormat; proto$1.invalidDate = invalidDate; proto$1.ordinal = ordinal; proto$1.preparse = preParsePostFormat; proto$1.postformat = preParsePostFormat; proto$1.relativeTime = relativeTime; proto$1.pastFuture = pastFuture; proto$1.set = set2; proto$1.eras = localeEras; proto$1.erasParse = localeErasParse; proto$1.erasConvertYear = localeErasConvertYear; proto$1.erasAbbrRegex = erasAbbrRegex; proto$1.erasNameRegex = erasNameRegex; proto$1.erasNarrowRegex = erasNarrowRegex; proto$1.months = localeMonths; proto$1.monthsShort = localeMonthsShort; proto$1.monthsParse = localeMonthsParse; proto$1.monthsRegex = monthsRegex; proto$1.monthsShortRegex = monthsShortRegex; proto$1.week = localeWeek; proto$1.firstDayOfYear = localeFirstDayOfYear; proto$1.firstDayOfWeek = localeFirstDayOfWeek; proto$1.weekdays = localeWeekdays; proto$1.weekdaysMin = localeWeekdaysMin; proto$1.weekdaysShort = localeWeekdaysShort; proto$1.weekdaysParse = localeWeekdaysParse; proto$1.weekdaysRegex = weekdaysRegex; proto$1.weekdaysShortRegex = weekdaysShortRegex; proto$1.weekdaysMinRegex = weekdaysMinRegex; proto$1.isPM = localeIsPM; proto$1.meridiem = localeMeridiem; function get$1(format2, index2, field, setter) { var locale2 = getLocale(), utc = createUTC().set(setter, index2); return locale2[field](utc, format2); } function listMonthsImpl(format2, index2, field) { if (isNumber2(format2)) { index2 = format2; format2 = void 0; } format2 = format2 || ""; if (index2 != null) { return get$1(format2, index2, field, "month"); } var i, out = []; for (i = 0; i < 12; i++) { out[i] = get$1(format2, i, field, "month"); } return out; } function listWeekdaysImpl(localeSorted, format2, index2, field) { if (typeof localeSorted === "boolean") { if (isNumber2(format2)) { index2 = format2; format2 = void 0; } format2 = format2 || ""; } else { format2 = localeSorted; index2 = format2; localeSorted = false; if (isNumber2(format2)) { index2 = format2; format2 = void 0; } format2 = format2 || ""; } var locale2 = getLocale(), shift = localeSorted ? locale2._week.dow : 0, i, out = []; if (index2 != null) { return get$1(format2, (index2 + shift) % 7, field, "day"); } for (i = 0; i < 7; i++) { out[i] = get$1(format2, (i + shift) % 7, field, "day"); } return out; } function listMonths(format2, index2) { return listMonthsImpl(format2, index2, "months"); } function listMonthsShort(format2, index2) { return listMonthsImpl(format2, index2, "monthsShort"); } function listWeekdays(localeSorted, format2, index2) { return listWeekdaysImpl(localeSorted, format2, index2, "weekdays"); } function listWeekdaysShort(localeSorted, format2, index2) { return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysShort"); } function listWeekdaysMin(localeSorted, format2, index2) { return listWeekdaysImpl(localeSorted, format2, index2, "weekdaysMin"); } getSetGlobalLocale("en", { eras: [ { since: "0001-01-01", until: Infinity, offset: 1, name: "Anno Domini", narrow: "AD", abbr: "AD" }, { since: "0000-12-31", until: -Infinity, offset: 1, name: "Before Christ", narrow: "BC", abbr: "BC" } ], dayOfMonthOrdinalParse: /\d{1,2}(th|st|nd|rd)/, ordinal: function(number2) { var b = number2 % 10, output = toInt(number2 % 100 / 10) === 1 ? "th" : b === 1 ? "st" : b === 2 ? "nd" : b === 3 ? "rd" : "th"; return number2 + output; } }); hooks.lang = deprecate( "moment.lang is deprecated. Use moment.locale instead.", getSetGlobalLocale ); hooks.langData = deprecate( "moment.langData is deprecated. Use moment.localeData instead.", getLocale ); var mathAbs = Math.abs; function abs() { var data = this._data; this._milliseconds = mathAbs(this._milliseconds); this._days = mathAbs(this._days); this._months = mathAbs(this._months); data.milliseconds = mathAbs(data.milliseconds); data.seconds = mathAbs(data.seconds); data.minutes = mathAbs(data.minutes); data.hours = mathAbs(data.hours); data.months = mathAbs(data.months); data.years = mathAbs(data.years); return this; } function addSubtract$1(duration, input, value, direction) { var other = createDuration(input, value); duration._milliseconds += direction * other._milliseconds; duration._days += direction * other._days; duration._months += direction * other._months; return duration._bubble(); } function add$1(input, value) { return addSubtract$1(this, input, value, 1); } function subtract$1(input, value) { return addSubtract$1(this, input, value, -1); } function absCeil(number2) { if (number2 < 0) { return Math.floor(number2); } else { return Math.ceil(number2); } } function bubble() { var milliseconds2 = this._milliseconds, days2 = this._days, months2 = this._months, data = this._data, seconds2, minutes2, hours2, years2, monthsFromDays; if (!(milliseconds2 >= 0 && days2 >= 0 && months2 >= 0 || milliseconds2 <= 0 && days2 <= 0 && months2 <= 0)) { milliseconds2 += absCeil(monthsToDays(months2) + days2) * 864e5; days2 = 0; months2 = 0; } data.milliseconds = milliseconds2 % 1e3; seconds2 = absFloor(milliseconds2 / 1e3); data.seconds = seconds2 % 60; minutes2 = absFloor(seconds2 / 60); data.minutes = minutes2 % 60; hours2 = absFloor(minutes2 / 60); data.hours = hours2 % 24; days2 += absFloor(hours2 / 24); monthsFromDays = absFloor(daysToMonths(days2)); months2 += monthsFromDays; days2 -= absCeil(monthsToDays(monthsFromDays)); years2 = absFloor(months2 / 12); months2 %= 12; data.days = days2; data.months = months2; data.years = years2; return this; } function daysToMonths(days2) { return days2 * 4800 / 146097; } function monthsToDays(months2) { return months2 * 146097 / 4800; } function as(units) { if (!this.isValid()) { return NaN; } var days2, months2, milliseconds2 = this._milliseconds; units = normalizeUnits(units); if (units === "month" || units === "quarter" || units === "year") { days2 = this._days + milliseconds2 / 864e5; months2 = this._months + daysToMonths(days2); switch (units) { case "month": return months2; case "quarter": return months2 / 3; case "year": return months2 / 12; } } else { days2 = this._days + Math.round(monthsToDays(this._months)); switch (units) { case "week": return days2 / 7 + milliseconds2 / 6048e5; case "day": return days2 + milliseconds2 / 864e5; case "hour": return days2 * 24 + milliseconds2 / 36e5; case "minute": return days2 * 1440 + milliseconds2 / 6e4; case "second": return days2 * 86400 + milliseconds2 / 1e3; case "millisecond": return Math.floor(days2 * 864e5) + milliseconds2; default: throw new Error("Unknown unit " + units); } } } function valueOf$1() { if (!this.isValid()) { return NaN; } return this._milliseconds + this._days * 864e5 + this._months % 12 * 2592e6 + toInt(this._months / 12) * 31536e6; } function makeAs(alias) { return function() { return this.as(alias); }; } var asMilliseconds = makeAs("ms"), asSeconds = makeAs("s"), asMinutes = makeAs("m"), asHours = makeAs("h"), asDays = makeAs("d"), asWeeks = makeAs("w"), asMonths = makeAs("M"), asQuarters = makeAs("Q"), asYears = makeAs("y"); function clone$1() { return createDuration(this); } function get$2(units) { units = normalizeUnits(units); return this.isValid() ? this[units + "s"]() : NaN; } function makeGetter(name) { return function() { return this.isValid() ? this._data[name] : NaN; }; } var milliseconds = makeGetter("milliseconds"), seconds = makeGetter("seconds"), minutes = makeGetter("minutes"), hours = makeGetter("hours"), days = makeGetter("days"), months = makeGetter("months"), years = makeGetter("years"); function weeks() { return absFloor(this.days() / 7); } var round = Math.round, thresholds = { ss: 44, // a few seconds to seconds s: 45, // seconds to minute m: 45, // minutes to hour h: 22, // hours to day d: 26, // days to month/week w: null, // weeks to month M: 11 // months to year }; function substituteTimeAgo(string3, number2, withoutSuffix, isFuture, locale2) { return locale2.relativeTime(number2 || 1, !!withoutSuffix, string3, isFuture); } function relativeTime$1(posNegDuration, withoutSuffix, thresholds2, locale2) { var duration = createDuration(posNegDuration).abs(), seconds2 = round(duration.as("s")), minutes2 = round(duration.as("m")), hours2 = round(duration.as("h")), days2 = round(duration.as("d")), months2 = round(duration.as("M")), weeks2 = round(duration.as("w")), years2 = round(duration.as("y")), a2 = seconds2 <= thresholds2.ss && ["s", seconds2] || seconds2 < thresholds2.s && ["ss", seconds2] || minutes2 <= 1 && ["m"] || minutes2 < thresholds2.m && ["mm", minutes2] || hours2 <= 1 && ["h"] || hours2 < thresholds2.h && ["hh", hours2] || days2 <= 1 && ["d"] || days2 < thresholds2.d && ["dd", days2]; if (thresholds2.w != null) { a2 = a2 || weeks2 <= 1 && ["w"] || weeks2 < thresholds2.w && ["ww", weeks2]; } a2 = a2 || months2 <= 1 && ["M"] || months2 < thresholds2.M && ["MM", months2] || years2 <= 1 && ["y"] || ["yy", years2]; a2[2] = withoutSuffix; a2[3] = +posNegDuration > 0; a2[4] = locale2; return substituteTimeAgo.apply(null, a2); } function getSetRelativeTimeRounding(roundingFunction) { if (roundingFunction === void 0) { return round; } if (typeof roundingFunction === "function") { round = roundingFunction; return true; } return false; } function getSetRelativeTimeThreshold(threshold, limit) { if (thresholds[threshold] === void 0) { return false; } if (limit === void 0) { return thresholds[threshold]; } thresholds[threshold] = limit; if (threshold === "s") { thresholds.ss = limit - 1; } return true; } function humanize(argWithSuffix, argThresholds) { if (!this.isValid()) { return this.localeData().invalidDate(); } var withSuffix = false, th = thresholds, locale2, output; if (typeof argWithSuffix === "object") { argThresholds = argWithSuffix; argWithSuffix = false; } if (typeof argWithSuffix === "boolean") { withSuffix = argWithSuffix; } if (typeof argThresholds === "object") { th = Object.assign({}, thresholds, argThresholds); if (argThresholds.s != null && argThresholds.ss == null) { th.ss = argThresholds.s - 1; } } locale2 = this.localeData(); output = relativeTime$1(this, !withSuffix, th, locale2); if (withSuffix) { output = locale2.pastFuture(+this, output); } return locale2.postformat(output); } var abs$1 = Math.abs; function sign(x) { return (x > 0) - (x < 0) || +x; } function toISOString$1() { if (!this.isValid()) { return this.localeData().invalidDate(); } var seconds2 = abs$1(this._milliseconds) / 1e3, days2 = abs$1(this._days), months2 = abs$1(this._months), minutes2, hours2, years2, s, total = this.asSeconds(), totalSign, ymSign, daysSign, hmsSign; if (!total) { return "P0D"; } minutes2 = absFloor(seconds2 / 60); hours2 = absFloor(minutes2 / 60); seconds2 %= 60; minutes2 %= 60; years2 = absFloor(months2 / 12); months2 %= 12; s = seconds2 ? seconds2.toFixed(3).replace(/\.?0+$/, "") : ""; totalSign = total < 0 ? "-" : ""; ymSign = sign(this._months) !== sign(total) ? "-" : ""; daysSign = sign(this._days) !== sign(total) ? "-" : ""; hmsSign = sign(this._milliseconds) !== sign(total) ? "-" : ""; return totalSign + "P" + (years2 ? ymSign + years2 + "Y" : "") + (months2 ? ymSign + months2 + "M" : "") + (days2 ? daysSign + days2 + "D" : "") + (hours2 || minutes2 || seconds2 ? "T" : "") + (hours2 ? hmsSign + hours2 + "H" : "") + (minutes2 ? hmsSign + minutes2 + "M" : "") + (seconds2 ? hmsSign + s + "S" : ""); } var proto$2 = Duration.prototype; proto$2.isValid = isValid$1; proto$2.abs = abs; proto$2.add = add$1; proto$2.subtract = subtract$1; proto$2.as = as; proto$2.asMilliseconds = asMilliseconds; proto$2.asSeconds = asSeconds; proto$2.asMinutes = asMinutes; proto$2.asHours = asHours; proto$2.asDays = asDays; proto$2.asWeeks = asWeeks; proto$2.asMonths = asMonths; proto$2.asQuarters = asQuarters; proto$2.asYears = asYears; proto$2.valueOf = valueOf$1; proto$2._bubble = bubble; proto$2.clone = clone$1; proto$2.get = get$2; proto$2.milliseconds = milliseconds; proto$2.seconds = seconds; proto$2.minutes = minutes; proto$2.hours = hours; proto$2.days = days; proto$2.weeks = weeks; proto$2.months = months; proto$2.years = years; proto$2.humanize = humanize; proto$2.toISOString = toISOString$1; proto$2.toString = toISOString$1; proto$2.toJSON = toISOString$1; proto$2.locale = locale; proto$2.localeData = localeData; proto$2.toIsoString = deprecate( "toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)", toISOString$1 ); proto$2.lang = lang; addFormatToken("X", 0, 0, "unix"); addFormatToken("x", 0, 0, "valueOf"); addRegexToken("x", matchSigned); addRegexToken("X", matchTimestamp); addParseToken("X", function(input, array, config) { config._d = new Date(parseFloat(input) * 1e3); }); addParseToken("x", function(input, array, config) { config._d = new Date(toInt(input)); }); hooks.version = "2.29.4"; setHookCallback(createLocal); hooks.fn = proto; hooks.min = min; hooks.max = max; hooks.now = now; hooks.utc = createUTC; hooks.unix = createUnix; hooks.months = listMonths; hooks.isDate = isDate3; hooks.locale = getSetGlobalLocale; hooks.invalid = createInvalid; hooks.duration = createDuration; hooks.isMoment = isMoment; hooks.weekdays = listWeekdays; hooks.parseZone = createInZone; hooks.localeData = getLocale; hooks.isDuration = isDuration; hooks.monthsShort = listMonthsShort; hooks.weekdaysMin = listWeekdaysMin; hooks.defineLocale = defineLocale; hooks.updateLocale = updateLocale; hooks.locales = listLocales; hooks.weekdaysShort = listWeekdaysShort; hooks.normalizeUnits = normalizeUnits; hooks.relativeTimeRounding = getSetRelativeTimeRounding; hooks.relativeTimeThreshold = getSetRelativeTimeThreshold; hooks.calendarFormat = getCalendarFormat; hooks.prototype = proto; hooks.HTML5_FMT = { DATETIME_LOCAL: "YYYY-MM-DDTHH:mm", // DATETIME_LOCAL_SECONDS: "YYYY-MM-DDTHH:mm:ss", // DATETIME_LOCAL_MS: "YYYY-MM-DDTHH:mm:ss.SSS", // DATE: "YYYY-MM-DD", // TIME: "HH:mm", // TIME_SECONDS: "HH:mm:ss", // TIME_MS: "HH:mm:ss.SSS", // WEEK: "GGGG-[W]WW", // MONTH: "YYYY-MM" // }; return hooks; }); } }); // node_modules/@fortaine/fetch-event-source/lib/cjs/parse.cjs var require_parse = __commonJS({ "node_modules/@fortaine/fetch-event-source/lib/cjs/parse.cjs"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.getMessages = exports.getLines = exports.getBytes = void 0; async function getBytes2(stream, onChunk) { const reader = stream.getReader(); let result; while (!(result = await reader.read()).done) { onChunk(result.value); } } exports.getBytes = getBytes2; function getLines3(onLine) { let buffer2; let position3; let fieldLength; let discardTrailingNewline = false; return function onChunk(arr) { if (buffer2 === void 0) { buffer2 = arr; position3 = 0; fieldLength = -1; } else { buffer2 = concat3(buffer2, arr); } const bufLength = buffer2.length; let lineStart = 0; while (position3 < bufLength) { if (discardTrailingNewline) { if (buffer2[position3] === 10) { lineStart = ++position3; } discardTrailingNewline = false; } let lineEnd = -1; for (; position3 < bufLength && lineEnd === -1; ++position3) { switch (buffer2[position3]) { case 58: if (fieldLength === -1) { fieldLength = position3 - lineStart; } break; case 13: discardTrailingNewline = true; case 10: lineEnd = position3; break; } } if (lineEnd === -1) { break; } onLine(buffer2.subarray(lineStart, lineEnd), fieldLength); lineStart = position3; fieldLength = -1; } if (lineStart === bufLength) { buffer2 = void 0; } else if (lineStart !== 0) { buffer2 = buffer2.subarray(lineStart); position3 -= lineStart; } }; } exports.getLines = getLines3; function getMessages3(onMessage, onId, onRetry) { let message = newMessage3(); const decoder = new TextDecoder(); return function onLine(line, fieldLength) { if (line.length === 0) { onMessage === null || onMessage === void 0 ? void 0 : onMessage(message); message = newMessage3(); } else if (fieldLength > 0) { const field = decoder.decode(line.subarray(0, fieldLength)); const valueOffset = fieldLength + (line[fieldLength + 1] === 32 ? 2 : 1); const value = decoder.decode(line.subarray(valueOffset)); switch (field) { case "data": message.data = message.data ? message.data + "\n" + value : value; break; case "event": message.event = value; break; case "id": onId === null || onId === void 0 ? void 0 : onId(message.id = value); break; case "retry": const retry = parseInt(value, 10); if (!isNaN(retry)) { onRetry === null || onRetry === void 0 ? void 0 : onRetry(message.retry = retry); } break; } } }; } exports.getMessages = getMessages3; function concat3(a2, b) { const res = new Uint8Array(a2.length + b.length); res.set(a2); res.set(b, a2.length); return res; } function newMessage3() { return { data: "", event: "", id: "", retry: void 0 }; } } }); // node_modules/@fortaine/fetch-event-source/lib/cjs/fetch.cjs var require_fetch = __commonJS({ "node_modules/@fortaine/fetch-event-source/lib/cjs/fetch.cjs"(exports) { "use strict"; var __rest = exports && exports.__rest || function(s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.fetchEventSource = exports.EventStreamContentType = void 0; var parse_js_1 = require_parse(); exports.EventStreamContentType = "text/event-stream"; var DefaultRetryInterval = 1e3; var LastEventId = "last-event-id"; function fetchEventSource(input, _a) { var { signal: inputSignal, headers: inputHeaders, onopen: inputOnOpen, onmessage, onclose, onerror, openWhenHidden, fetch: inputFetch } = _a, rest = __rest(_a, ["signal", "headers", "onopen", "onmessage", "onclose", "onerror", "openWhenHidden", "fetch"]); return new Promise((resolve, reject) => { const headers = Object.assign({}, inputHeaders); if (!headers.accept) { headers.accept = exports.EventStreamContentType; } let curRequestController; function onVisibilityChange() { curRequestController.abort(); if (!document.hidden) { create2(); } } if (typeof document !== "undefined" && !openWhenHidden) { document.addEventListener("visibilitychange", onVisibilityChange); } let retryInterval = DefaultRetryInterval; let retryTimer = 0; function dispose() { if (typeof document !== "undefined" && !openWhenHidden) { document.removeEventListener("visibilitychange", onVisibilityChange); } clearTimeout(retryTimer); curRequestController.abort(); } inputSignal === null || inputSignal === void 0 ? void 0 : inputSignal.addEventListener("abort", () => { dispose(); resolve(); }); const fetchFn = inputFetch !== null && inputFetch !== void 0 ? inputFetch : fetch; const onopen = inputOnOpen !== null && inputOnOpen !== void 0 ? inputOnOpen : defaultOnOpen; async function create2() { var _a2; curRequestController = new AbortController(); try { const response = await fetchFn(input, Object.assign(Object.assign({}, rest), { headers, signal: curRequestController.signal })); await onopen(response); await (0, parse_js_1.getBytes)(response.body, (0, parse_js_1.getLines)((0, parse_js_1.getMessages)(onmessage, (id) => { if (id) { headers[LastEventId] = id; } else { delete headers[LastEventId]; } }, (retry) => { retryInterval = retry; }))); onclose === null || onclose === void 0 ? void 0 : onclose(); dispose(); resolve(); } catch (err) { if (!curRequestController.signal.aborted) { try { const interval = (_a2 = onerror === null || onerror === void 0 ? void 0 : onerror(err)) !== null && _a2 !== void 0 ? _a2 : retryInterval; clearTimeout(retryTimer); retryTimer = setTimeout(create2, interval); } catch (innerErr) { dispose(); reject(innerErr); } } } } create2(); }); } exports.fetchEventSource = fetchEventSource; function defaultOnOpen(response) { const contentType = response.headers.get("content-type"); if (!(contentType === null || contentType === void 0 ? void 0 : contentType.startsWith(exports.EventStreamContentType))) { throw new Error(`Expected content-type to be ${exports.EventStreamContentType}, Actual: ${contentType}`); } } } }); // node_modules/@fortaine/fetch-event-source/lib/cjs/index.cjs var require_cjs = __commonJS({ "node_modules/@fortaine/fetch-event-source/lib/cjs/index.cjs"(exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.EventStreamContentType = exports.fetchEventSource = void 0; var fetch_js_1 = require_fetch(); Object.defineProperty(exports, "fetchEventSource", { enumerable: true, get: function() { return fetch_js_1.fetchEventSource; } }); Object.defineProperty(exports, "EventStreamContentType", { enumerable: true, get: function() { return fetch_js_1.EventStreamContentType; } }); } }); // node_modules/cross-fetch/dist/browser-ponyfill.js var require_browser_ponyfill = __commonJS({ "node_modules/cross-fetch/dist/browser-ponyfill.js"(exports, module2) { var global2 = typeof self !== "undefined" ? self : exports; var __self__ = function() { function F() { this.fetch = false; this.DOMException = global2.DOMException; } F.prototype = global2; return new F(); }(); (function(self2) { var irrelevant = function(exports2) { var support = { searchParams: "URLSearchParams" in self2, iterable: "Symbol" in self2 && "iterator" in Symbol, blob: "FileReader" in self2 && "Blob" in self2 && function() { try { new Blob(); return true; } catch (e) { return false; } }(), formData: "FormData" in self2, arrayBuffer: "ArrayBuffer" in self2 }; function isDataView(obj) { return obj && DataView.prototype.isPrototypeOf(obj); } if (support.arrayBuffer) { var viewClasses = [ "[object Int8Array]", "[object Uint8Array]", "[object Uint8ClampedArray]", "[object Int16Array]", "[object Uint16Array]", "[object Int32Array]", "[object Uint32Array]", "[object Float32Array]", "[object Float64Array]" ]; var isArrayBufferView2 = ArrayBuffer.isView || function(obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1; }; } function normalizeName(name) { if (typeof name !== "string") { name = String(name); } if (/[^a-z0-9\-#$%&'*+.^_`|~]/i.test(name)) { throw new TypeError("Invalid character in header field name"); } return name.toLowerCase(); } function normalizeValue2(value) { if (typeof value !== "string") { value = String(value); } return value; } function iteratorFor(items) { var iterator = { next: function() { var value = items.shift(); return { done: value === void 0, value }; } }; if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator; }; } return iterator; } function Headers2(headers) { this.map = {}; if (headers instanceof Headers2) { headers.forEach(function(value, name) { this.append(name, value); }, this); } else if (Array.isArray(headers)) { headers.forEach(function(header) { this.append(header[0], header[1]); }, this); } else if (headers) { Object.getOwnPropertyNames(headers).forEach(function(name) { this.append(name, headers[name]); }, this); } } Headers2.prototype.append = function(name, value) { name = normalizeName(name); value = normalizeValue2(value); var oldValue = this.map[name]; this.map[name] = oldValue ? oldValue + ", " + value : value; }; Headers2.prototype["delete"] = function(name) { delete this.map[normalizeName(name)]; }; Headers2.prototype.get = function(name) { name = normalizeName(name); return this.has(name) ? this.map[name] : null; }; Headers2.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)); }; Headers2.prototype.set = function(name, value) { this.map[normalizeName(name)] = normalizeValue2(value); }; Headers2.prototype.forEach = function(callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { callback.call(thisArg, this.map[name], name, this); } } }; Headers2.prototype.keys = function() { var items = []; this.forEach(function(value, name) { items.push(name); }); return iteratorFor(items); }; Headers2.prototype.values = function() { var items = []; this.forEach(function(value) { items.push(value); }); return iteratorFor(items); }; Headers2.prototype.entries = function() { var items = []; this.forEach(function(value, name) { items.push([name, value]); }); return iteratorFor(items); }; if (support.iterable) { Headers2.prototype[Symbol.iterator] = Headers2.prototype.entries; } function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError("Already read")); } body.bodyUsed = true; } function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { resolve(reader.result); }; reader.onerror = function() { reject(reader.error); }; }); } function readBlobAsArrayBuffer(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsArrayBuffer(blob); return promise; } function readBlobAsText(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsText(blob); return promise; } function readArrayBufferAsText(buf) { var view = new Uint8Array(buf); var chars = new Array(view.length); for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]); } return chars.join(""); } function bufferClone(buf) { if (buf.slice) { return buf.slice(0); } else { var view = new Uint8Array(buf.byteLength); view.set(new Uint8Array(buf)); return view.buffer; } } function Body() { this.bodyUsed = false; this._initBody = function(body) { this._bodyInit = body; if (!body) { this._bodyText = ""; } else if (typeof body === "string") { this._bodyText = body; } else if (support.blob && Blob.prototype.isPrototypeOf(body)) { this._bodyBlob = body; } else if (support.formData && FormData.prototype.isPrototypeOf(body)) { this._bodyFormData = body; } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this._bodyText = body.toString(); } else if (support.arrayBuffer && support.blob && isDataView(body)) { this._bodyArrayBuffer = bufferClone(body.buffer); this._bodyInit = new Blob([this._bodyArrayBuffer]); } else if (support.arrayBuffer && (ArrayBuffer.prototype.isPrototypeOf(body) || isArrayBufferView2(body))) { this._bodyArrayBuffer = bufferClone(body); } else { this._bodyText = body = Object.prototype.toString.call(body); } if (!this.headers.get("content-type")) { if (typeof body === "string") { this.headers.set("content-type", "text/plain;charset=UTF-8"); } else if (this._bodyBlob && this._bodyBlob.type) { this.headers.set("content-type", this._bodyBlob.type); } else if (support.searchParams && URLSearchParams.prototype.isPrototypeOf(body)) { this.headers.set("content-type", "application/x-www-form-urlencoded;charset=UTF-8"); } } }; if (support.blob) { this.blob = function() { var rejected = consumed(this); if (rejected) { return rejected; } if (this._bodyBlob) { return Promise.resolve(this._bodyBlob); } else if (this._bodyArrayBuffer) { return Promise.resolve(new Blob([this._bodyArrayBuffer])); } else if (this._bodyFormData) { throw new Error("could not read FormData body as blob"); } else { return Promise.resolve(new Blob([this._bodyText])); } }; this.arrayBuffer = function() { if (this._bodyArrayBuffer) { return consumed(this) || Promise.resolve(this._bodyArrayBuffer); } else { return this.blob().then(readBlobAsArrayBuffer); } }; } this.text = function() { var rejected = consumed(this); if (rejected) { return rejected; } if (this._bodyBlob) { return readBlobAsText(this._bodyBlob); } else if (this._bodyArrayBuffer) { return Promise.resolve(readArrayBufferAsText(this._bodyArrayBuffer)); } else if (this._bodyFormData) { throw new Error("could not read FormData body as text"); } else { return Promise.resolve(this._bodyText); } }; if (support.formData) { this.formData = function() { return this.text().then(decode2); }; } this.json = function() { return this.text().then(JSON.parse); }; return this; } var methods = ["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]; function normalizeMethod(method) { var upcased = method.toUpperCase(); return methods.indexOf(upcased) > -1 ? upcased : method; } function Request2(input, options) { options = options || {}; var body = options.body; if (input instanceof Request2) { if (input.bodyUsed) { throw new TypeError("Already read"); } this.url = input.url; this.credentials = input.credentials; if (!options.headers) { this.headers = new Headers2(input.headers); } this.method = input.method; this.mode = input.mode; this.signal = input.signal; if (!body && input._bodyInit != null) { body = input._bodyInit; input.bodyUsed = true; } } else { this.url = String(input); } this.credentials = options.credentials || this.credentials || "same-origin"; if (options.headers || !this.headers) { this.headers = new Headers2(options.headers); } this.method = normalizeMethod(options.method || this.method || "GET"); this.mode = options.mode || this.mode || null; this.signal = options.signal || this.signal; this.referrer = null; if ((this.method === "GET" || this.method === "HEAD") && body) { throw new TypeError("Body not allowed for GET or HEAD requests"); } this._initBody(body); } Request2.prototype.clone = function() { return new Request2(this, { body: this._bodyInit }); }; function decode2(body) { var form = new FormData(); body.trim().split("&").forEach(function(bytes) { if (bytes) { var split = bytes.split("="); var name = split.shift().replace(/\+/g, " "); var value = split.join("=").replace(/\+/g, " "); form.append(decodeURIComponent(name), decodeURIComponent(value)); } }); return form; } function parseHeaders(rawHeaders) { var headers = new Headers2(); var preProcessedHeaders = rawHeaders.replace(/\r?\n[\t ]+/g, " "); preProcessedHeaders.split(/\r?\n/).forEach(function(line) { var parts = line.split(":"); var key = parts.shift().trim(); if (key) { var value = parts.join(":").trim(); headers.append(key, value); } }); return headers; } Body.call(Request2.prototype); function Response(bodyInit, options) { if (!options) { options = {}; } this.type = "default"; this.status = options.status === void 0 ? 200 : options.status; this.ok = this.status >= 200 && this.status < 300; this.statusText = "statusText" in options ? options.statusText : "OK"; this.headers = new Headers2(options.headers); this.url = options.url || ""; this._initBody(bodyInit); } Body.call(Response.prototype); Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, statusText: this.statusText, headers: new Headers2(this.headers), url: this.url }); }; Response.error = function() { var response = new Response(null, { status: 0, statusText: "" }); response.type = "error"; return response; }; var redirectStatuses = [301, 302, 303, 307, 308]; Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError("Invalid status code"); } return new Response(null, { status, headers: { location: url } }); }; exports2.DOMException = self2.DOMException; try { new exports2.DOMException(); } catch (err) { exports2.DOMException = function(message, name) { this.message = message; this.name = name; var error = Error(message); this.stack = error.stack; }; exports2.DOMException.prototype = Object.create(Error.prototype); exports2.DOMException.prototype.constructor = exports2.DOMException; } function fetch2(input, init2) { return new Promise(function(resolve, reject) { var request = new Request2(input, init2); if (request.signal && request.signal.aborted) { return reject(new exports2.DOMException("Aborted", "AbortError")); } var xhr = new XMLHttpRequest(); function abortXhr() { xhr.abort(); } xhr.onload = function() { var options = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || "") }; options.url = "responseURL" in xhr ? xhr.responseURL : options.headers.get("X-Request-URL"); var body = "response" in xhr ? xhr.response : xhr.responseText; resolve(new Response(body, options)); }; xhr.onerror = function() { reject(new TypeError("Network request failed")); }; xhr.ontimeout = function() { reject(new TypeError("Network request failed")); }; xhr.onabort = function() { reject(new exports2.DOMException("Aborted", "AbortError")); }; xhr.open(request.method, request.url, true); if (request.credentials === "include") { xhr.withCredentials = true; } else if (request.credentials === "omit") { xhr.withCredentials = false; } if ("responseType" in xhr && support.blob) { xhr.responseType = "blob"; } request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value); }); if (request.signal) { request.signal.addEventListener("abort", abortXhr); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { request.signal.removeEventListener("abort", abortXhr); } }; } xhr.send(typeof request._bodyInit === "undefined" ? null : request._bodyInit); }); } fetch2.polyfill = true; if (!self2.fetch) { self2.fetch = fetch2; self2.Headers = Headers2; self2.Request = Request2; self2.Response = Response; } exports2.Headers = Headers2; exports2.Request = Request2; exports2.Response = Response; exports2.fetch = fetch2; Object.defineProperty(exports2, "__esModule", { value: true }); return exports2; }({}); })(__self__); __self__.fetch.ponyfill = true; delete __self__.fetch.polyfill; var ctx = __self__; exports = ctx.fetch; exports.default = ctx.fetch; exports.fetch = ctx.fetch; exports.Headers = ctx.Headers; exports.Request = ctx.Request; exports.Response = ctx.Response; module2.exports = exports; } }); // node_modules/@anthropic-ai/sdk/build/src/index.js var require_src = __commonJS({ "node_modules/@anthropic-ai/sdk/build/src/index.js"(exports) { "use strict"; var __awaiter = exports && exports.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __importDefault = exports && exports.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.Client = exports.AI_PROMPT = exports.HUMAN_PROMPT = void 0; var fetch_event_source_1 = require_cjs(); var cross_fetch_1 = __importDefault(require_browser_ponyfill()); exports.HUMAN_PROMPT = "\n\nHuman:"; exports.AI_PROMPT = "\n\nAssistant:"; var CLIENT_ID = "anthropic-typescript/0.4.3"; var DEFAULT_API_URL = "https://api.anthropic.com"; var Event; (function(Event2) { Event2["Ping"] = "ping"; })(Event || (Event = {})); var DONE_MESSAGE = "[DONE]"; var Client2 = class { constructor(apiKey, options) { var _a; this.apiKey = apiKey; this.apiUrl = (_a = options === null || options === void 0 ? void 0 : options.apiUrl) !== null && _a !== void 0 ? _a : DEFAULT_API_URL; } complete(params, options) { return __awaiter(this, void 0, void 0, function* () { const response = yield (0, cross_fetch_1.default)(`${this.apiUrl}/v1/complete`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", Client: CLIENT_ID, "X-API-Key": this.apiKey }, body: JSON.stringify(Object.assign(Object.assign({}, params), { stream: false })), signal: options === null || options === void 0 ? void 0 : options.signal }); if (!response.ok) { const error = new Error(`Sampling error: ${response.status} ${response.statusText}`); console.error(error); throw error; } const completion = yield response.json(); return completion; }); } completeStream(params, { onOpen, onUpdate, signal }) { const abortController = new AbortController(); return new Promise((resolve, reject) => { signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", (event) => { abortController.abort(event); reject({ name: "AbortError", message: "Caller aborted completeStream" }); }); (0, fetch_event_source_1.fetchEventSource)(`${this.apiUrl}/v1/complete`, { method: "POST", headers: { Accept: "application/json", "Content-Type": "application/json", Client: CLIENT_ID, "X-API-Key": this.apiKey }, body: JSON.stringify(Object.assign(Object.assign({}, params), { stream: true })), signal: abortController.signal, onopen: (response) => __awaiter(this, void 0, void 0, function* () { if (!response.ok) { abortController.abort(); return reject(Error(`Failed to open sampling stream, HTTP status code ${response.status}: ${response.statusText}`)); } if (onOpen) { yield Promise.resolve(onOpen(response)); } }), onmessage: (ev) => { if (ev.event === Event.Ping) { return; } if (ev.data === DONE_MESSAGE) { console.error("Unexpected done message before stop_reason has been issued"); return; } const completion = JSON.parse(ev.data); if (onUpdate) { Promise.resolve(onUpdate(completion)).catch((error) => { abortController.abort(); reject(error); }); } if (completion.stop_reason !== null) { abortController.abort(); return resolve(completion); } }, onerror: (error) => { console.error("Sampling error:", error); abortController.abort(); return reject(error); } }); }); } }; exports.Client = Client2; } }); // node_modules/cohere-ai/dist/cohere.js var require_cohere = __commonJS({ "node_modules/cohere-ai/dist/cohere.js"(exports, module2) { (function webpackUniversalModuleDefinition(root2, factory) { if (typeof exports === "object" && typeof module2 === "object") module2.exports = factory(); else if (typeof define === "function" && define.amd) define([], factory); else if (typeof exports === "object") exports["cohere"] = factory(); else root2["cohere"] = factory(); })(global, () => { return ( /******/ (() => { "use strict"; var __webpack_modules__ = { /***/ 828: ( /***/ function(module3, __unused_webpack_exports, __webpack_require__2) { var __assign = this && this.__assign || function() { __assign = Object.assign || function(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; var __importDefault = this && this.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; var api_service_1 = __importDefault(__webpack_require__2(836)); var ENDPOINT; (function(ENDPOINT2) { ENDPOINT2["GENERATE"] = "/generate"; ENDPOINT2["EMBED"] = "/embed"; ENDPOINT2["CLASSIFY"] = "/classify"; ENDPOINT2["TOKENIZE"] = "/tokenize"; ENDPOINT2["DETOKENIZE"] = "/detokenize"; ENDPOINT2["DETECT_LANGUAGE"] = "/detect-language"; ENDPOINT2["SUMMARIZE"] = "/summarize"; })(ENDPOINT || (ENDPOINT = {})); var COHERE_EMBED_BATCH_SIZE = 5; var Cohere = ( /** @class */ function() { function Cohere2() { } Cohere2.prototype.init = function(key, version2) { api_service_1.default.init(key, version2); }; Cohere2.prototype.makeRequest = function(endpoint, data) { return api_service_1.default.post(endpoint, data); }; Cohere2.prototype.generate = function(config) { return this.makeRequest(ENDPOINT.GENERATE, config); }; Cohere2.prototype.tokenize = function(_a) { var text4 = _a.text; return this.makeRequest(ENDPOINT.TOKENIZE, { text: text4 }); }; Cohere2.prototype.detokenize = function(_a) { var tokens = _a.tokens; return this.makeRequest(ENDPOINT.DETOKENIZE, { tokens }); }; Cohere2.prototype.embed = function(config) { var _this = this; var createBatches = function(array) { var result = []; for (var _i = 0, array_1 = array; _i < array_1.length; _i++) { var value = array_1[_i]; var lastArray = result[result.length - 1]; if (!lastArray || lastArray.length === COHERE_EMBED_BATCH_SIZE) { result.push([value]); } else { lastArray.push(value); } } return result; }; return Promise.all(createBatches(config.texts).map(function(texts) { return _this.makeRequest(ENDPOINT.EMBED, __assign(__assign({}, config), { texts })); })).then(function(results) { var embeddings = []; results.forEach(function(result) { embeddings = embeddings.concat(result.body.embeddings); }); var response = { statusCode: results[0].statusCode, body: { embeddings } }; return response; }); }; Cohere2.prototype.classify = function(config) { return this.makeRequest(ENDPOINT.CLASSIFY, config); }; Cohere2.prototype.detectLanguage = function(config) { return this.makeRequest(ENDPOINT.DETECT_LANGUAGE, config); }; Cohere2.prototype.summarize = function(config) { return this.makeRequest(ENDPOINT.SUMMARIZE, config); }; return Cohere2; }() ); var cohere = new Cohere(); module3.exports = cohere; } ), /***/ 836: ( /***/ function(module3, __unused_webpack_exports, __webpack_require__2) { var __awaiter = this && this.__awaiter || function(thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function(resolve) { resolve(value); }); } return new (P || (P = Promise))(function(resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; var __generator = this && this.__generator || function(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function(v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (g && (g = 0, op[0] && (_ = 0)), _) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } }; var __importDefault = this && this.__importDefault || function(mod) { return mod && mod.__esModule ? mod : { "default": mod }; }; var https = __webpack_require__2(687); var error_service_1 = __importDefault(__webpack_require__2(959)); var URL2; (function(URL3) { URL3["COHERE_API"] = "api.cohere.ai"; })(URL2 || (URL2 = {})); var APIImpl = ( /** @class */ function() { function APIImpl2() { this.COHERE_API_KEY = ""; this.COHERE_VERSION = ""; } APIImpl2.prototype.init = function(key, version2) { this.COHERE_API_KEY = key; if (version2 === void 0) { this.COHERE_VERSION = "2022-12-06"; } else { this.COHERE_VERSION = version2; } }; APIImpl2.prototype.post = function(endpoint, data) { return __awaiter(this, void 0, void 0, function() { var _this = this; return __generator(this, function(_a) { return [2, new Promise(function(resolve, reject) { try { data = JSON.parse("".concat(data)); } catch (e) { } var reqData = JSON.stringify(data); var req = https.request({ hostname: URL2.COHERE_API, path: endpoint, method: "POST", headers: { "Content-Type": "application/json; charset=utf-8", "Content-Length": Buffer.byteLength(reqData, "utf8"), "Cohere-Version": _this.COHERE_VERSION, Authorization: "Bearer ".concat(_this.COHERE_API_KEY), "Request-Source": "node-sdk" }, timeout: 5e3 }, function(res) { var data2 = []; res.on("data", function(chunk) { return data2.push(chunk); }); res.on("end", function() { if ("x-api-warning" in res.headers) { var warnHeader = res.headers["x-api-warning"]; if (typeof warnHeader === "string") { console.warn("\x1B[33mWarning: %s\x1B[0m", warnHeader); } else { for (var warning in warnHeader) { console.warn("\x1B[33mWarning: %s\x1B[0m", warning); } } } resolve({ statusCode: res.statusCode, body: JSON.parse(Buffer.concat(data2).toString()) }); }); }); req.on("error", function(error) { return reject(error_service_1.default.handleError(error)); }); req.write(reqData, "utf8"); req.end(); })]; }); }); }; return APIImpl2; }() ); var API = new APIImpl(); module3.exports = API; } ), /***/ 959: ( /***/ (module3) => { var errorImpl = ( /** @class */ function() { function errorImpl2() { } errorImpl2.prototype.handleError = function(error) { var _a, _b, _c; var status = ((_a = error.response) === null || _a === void 0 ? void 0 : _a.status) || 500; var message = ((_c = (_b = error.response) === null || _b === void 0 ? void 0 : _b.data) === null || _c === void 0 ? void 0 : _c.message) || error.message; return { statusCode: status, body: { message } }; }; return errorImpl2; }() ); var errors = new errorImpl(); module3.exports = errors; } ), /***/ 687: ( /***/ (module3) => { module3.exports = require("https"); } ) /******/ }; var __webpack_module_cache__ = {}; function __webpack_require__(moduleId) { var cachedModule = __webpack_module_cache__[moduleId]; if (cachedModule !== void 0) { return cachedModule.exports; } var module3 = __webpack_module_cache__[moduleId] = { /******/ // no module.id needed /******/ // no module.loaded needed /******/ exports: {} /******/ }; __webpack_modules__[moduleId].call(module3.exports, module3, module3.exports, __webpack_require__); return module3.exports; } var __webpack_exports__ = __webpack_require__(828); return __webpack_exports__; })() ); }); } }); // node_modules/cohere-ai/index.js var require_cohere_ai = __commonJS({ "node_modules/cohere-ai/index.js"(exports, module2) { module2.exports = require_cohere(); } }); // node_modules/binary-search/index.js var require_binary_search = __commonJS({ "node_modules/binary-search/index.js"(exports, module2) { module2.exports = function(haystack, needle, comparator, low, high) { var mid, cmp; if (low === void 0) low = 0; else { low = low | 0; if (low < 0 || low >= haystack.length) throw new RangeError("invalid lower bound"); } if (high === void 0) high = haystack.length - 1; else { high = high | 0; if (high < low || high >= haystack.length) throw new RangeError("invalid upper bound"); } while (low <= high) { mid = low + (high - low >>> 1); cmp = +comparator(haystack[mid], needle, mid, haystack); if (cmp < 0) low = mid + 1; else if (cmp > 0) high = mid - 1; else return mid; } return ~low; }; } }); // node_modules/num-sort/index.js var require_num_sort = __commonJS({ "node_modules/num-sort/index.js"(exports) { "use strict"; function assertNumber(number2) { if (typeof number2 !== "number") { throw new TypeError("Expected a number"); } } exports.ascending = (left, right) => { assertNumber(left); assertNumber(right); if (Number.isNaN(left)) { return -1; } if (Number.isNaN(right)) { return 1; } return left - right; }; exports.descending = (left, right) => { assertNumber(left); assertNumber(right); if (Number.isNaN(left)) { return 1; } if (Number.isNaN(right)) { return -1; } return right - left; }; } }); // node_modules/react/cjs/react.development.js var require_react_development = __commonJS({ "node_modules/react/cjs/react.development.js"(exports, module2) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var ReactVersion = "18.2.0"; var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var ReactCurrentDispatcher = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactCurrentBatchConfig = { transition: null }; var ReactCurrentActQueue = { current: null, // Used to reproduce behavior of `batchedUpdates` in legacy mode. isBatchingLegacy: false, didScheduleLegacyUpdate: false }; var ReactCurrentOwner = { /** * @internal * @type {ReactComponent} */ current: null }; var ReactDebugCurrentFrame = {}; var currentExtraStackFrame = null; function setExtraStackFrame(stack) { { currentExtraStackFrame = stack; } } { ReactDebugCurrentFrame.setExtraStackFrame = function(stack) { { currentExtraStackFrame = stack; } }; ReactDebugCurrentFrame.getCurrentStack = null; ReactDebugCurrentFrame.getStackAddendum = function() { var stack = ""; if (currentExtraStackFrame) { stack += currentExtraStackFrame; } var impl = ReactDebugCurrentFrame.getCurrentStack; if (impl) { stack += impl() || ""; } return stack; }; } var enableScopeAPI = false; var enableCacheElement = false; var enableTransitionTracing = false; var enableLegacyHidden = false; var enableDebugTracing = false; var ReactSharedInternals = { ReactCurrentDispatcher, ReactCurrentBatchConfig, ReactCurrentOwner }; { ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; } function warn(format) { { { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning("warn", format, args); } } } function error(format) { { { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var didWarnStateUpdateForUnmountedComponent = {}; function warnNoop(publicInstance, callerName) { { var _constructor = publicInstance.constructor; var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; var warningKey = componentName + "." + callerName; if (didWarnStateUpdateForUnmountedComponent[warningKey]) { return; } error("Can't call %s on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to `this.state` directly or define a `state = {};` class property with the desired state in the %s component.", callerName, componentName); didWarnStateUpdateForUnmountedComponent[warningKey] = true; } } var ReactNoopUpdateQueue = { /** * Checks whether or not this composite component is mounted. * @param {ReactClass} publicInstance The instance we want to test. * @return {boolean} True if mounted, false otherwise. * @protected * @final */ isMounted: function(publicInstance) { return false; }, /** * Forces an update. This should only be invoked when it is known with * certainty that we are **not** in a DOM transaction. * * You may want to call this when you know that some deeper aspect of the * component's state has changed but `setState` was not called. * * This will not invoke `shouldComponentUpdate`, but it will invoke * `componentWillUpdate` and `componentDidUpdate`. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueForceUpdate: function(publicInstance, callback, callerName) { warnNoop(publicInstance, "forceUpdate"); }, /** * Replaces all of the state. Always use this or `setState` to mutate state. * You should treat `this.state` as immutable. * * There is no guarantee that `this.state` will be immediately updated, so * accessing `this.state` after calling this method may return the old value. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} completeState Next state. * @param {?function} callback Called after component is updated. * @param {?string} callerName name of the calling function in the public API. * @internal */ enqueueReplaceState: function(publicInstance, completeState, callback, callerName) { warnNoop(publicInstance, "replaceState"); }, /** * Sets a subset of the state. This only exists because _pendingState is * internal. This provides a merging strategy that is not available to deep * properties which is confusing. TODO: Expose pendingState or don't use it * during the merge. * * @param {ReactClass} publicInstance The instance that should rerender. * @param {object} partialState Next partial state to be merged with state. * @param {?function} callback Called after component is updated. * @param {?string} Name of the calling function in the public API. * @internal */ enqueueSetState: function(publicInstance, partialState, callback, callerName) { warnNoop(publicInstance, "setState"); } }; var assign2 = Object.assign; var emptyObject = {}; { Object.freeze(emptyObject); } function Component(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } Component.prototype.isReactComponent = {}; Component.prototype.setState = function(partialState, callback) { if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { throw new Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables."); } this.updater.enqueueSetState(this, partialState, callback, "setState"); }; Component.prototype.forceUpdate = function(callback) { this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); }; { var deprecatedAPIs = { isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in componentWillUnmount to prevent memory leaks."], replaceState: ["replaceState", "Refactor your code to use setState instead (see https://github.com/facebook/react/issues/3236)."] }; var defineDeprecationWarning = function(methodName, info) { Object.defineProperty(Component.prototype, methodName, { get: function() { warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); return void 0; } }); }; for (var fnName in deprecatedAPIs) { if (deprecatedAPIs.hasOwnProperty(fnName)) { defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); } } } function ComponentDummy() { } ComponentDummy.prototype = Component.prototype; function PureComponent(props, context, updater) { this.props = props; this.context = context; this.refs = emptyObject; this.updater = updater || ReactNoopUpdateQueue; } var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); pureComponentPrototype.constructor = PureComponent; assign2(pureComponentPrototype, Component.prototype); pureComponentPrototype.isPureReactComponent = true; function createRef() { var refObject = { current: null }; { Object.seal(refObject); } return refObject; } var isArrayImpl = Array.isArray; function isArray4(a2) { return isArrayImpl(a2); } function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type2; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type2) { return type2.displayName || "Context"; } function getComponentNameFromType(type2) { if (type2 == null) { return null; } { if (typeof type2.tag === "number") { error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type2 === "function") { return type2.displayName || type2.name || null; } if (typeof type2 === "string") { return type2; } switch (type2) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_CONTEXT_TYPE: var context = type2; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type2; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type2, type2.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type2.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type2.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return getComponentNameFromType(init2(payload)); } catch (x) { return null; } } } } return null; } var hasOwnProperty3 = Object.prototype.hasOwnProperty; var RESERVED_PROPS = { key: true, ref: true, __self: true, __source: true }; var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; { didWarnAboutStringRefs = {}; } function hasValidRef(config) { { if (hasOwnProperty3.call(config, "ref")) { var getter = Object.getOwnPropertyDescriptor(config, "ref").get; if (getter && getter.isReactWarning) { return false; } } } return config.ref !== void 0; } function hasValidKey(config) { { if (hasOwnProperty3.call(config, "key")) { var getter = Object.getOwnPropertyDescriptor(config, "key").get; if (getter && getter.isReactWarning) { return false; } } } return config.key !== void 0; } function defineKeyPropWarningGetter(props, displayName) { var warnAboutAccessingKey = function() { { if (!specialPropKeyWarningShown) { specialPropKeyWarningShown = true; error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingKey.isReactWarning = true; Object.defineProperty(props, "key", { get: warnAboutAccessingKey, configurable: true }); } function defineRefPropWarningGetter(props, displayName) { var warnAboutAccessingRef = function() { { if (!specialPropRefWarningShown) { specialPropRefWarningShown = true; error("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", displayName); } } }; warnAboutAccessingRef.isReactWarning = true; Object.defineProperty(props, "ref", { get: warnAboutAccessingRef, configurable: true }); } function warnIfStringRefCannotBeAutoConverted(config) { { if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); if (!didWarnAboutStringRefs[componentName]) { error('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', componentName, config.ref); didWarnAboutStringRefs[componentName] = true; } } } } var ReactElement = function(type2, key, ref, self2, source, owner, props) { var element2 = { // This tag allows us to uniquely identify this as a React Element $$typeof: REACT_ELEMENT_TYPE, // Built-in properties that belong on the element type: type2, key, ref, props, // Record the component responsible for creating this element. _owner: owner }; { element2._store = {}; Object.defineProperty(element2._store, "validated", { configurable: false, enumerable: false, writable: true, value: false }); Object.defineProperty(element2, "_self", { configurable: false, enumerable: false, writable: false, value: self2 }); Object.defineProperty(element2, "_source", { configurable: false, enumerable: false, writable: false, value: source }); if (Object.freeze) { Object.freeze(element2.props); Object.freeze(element2); } } return element2; }; function createElement2(type2, config, children) { var propName; var props = {}; var key = null; var ref = null; var self2 = null; var source = null; if (config != null) { if (hasValidRef(config)) { ref = config.ref; { warnIfStringRefCannotBeAutoConverted(config); } } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } self2 = config.__self === void 0 ? null : config.__self; source = config.__source === void 0 ? null : config.__source; for (propName in config) { if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { props[propName] = config[propName]; } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } { if (Object.freeze) { Object.freeze(childArray); } } props.children = childArray; } if (type2 && type2.defaultProps) { var defaultProps = type2.defaultProps; for (propName in defaultProps) { if (props[propName] === void 0) { props[propName] = defaultProps[propName]; } } } { if (key || ref) { var displayName = typeof type2 === "function" ? type2.displayName || type2.name || "Unknown" : type2; if (key) { defineKeyPropWarningGetter(props, displayName); } if (ref) { defineRefPropWarningGetter(props, displayName); } } } return ReactElement(type2, key, ref, self2, source, ReactCurrentOwner.current, props); } function cloneAndReplaceKey(oldElement, newKey) { var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); return newElement; } function cloneElement(element2, config, children) { if (element2 === null || element2 === void 0) { throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element2 + "."); } var propName; var props = assign2({}, element2.props); var key = element2.key; var ref = element2.ref; var self2 = element2._self; var source = element2._source; var owner = element2._owner; if (config != null) { if (hasValidRef(config)) { ref = config.ref; owner = ReactCurrentOwner.current; } if (hasValidKey(config)) { { checkKeyStringCoercion(config.key); } key = "" + config.key; } var defaultProps; if (element2.type && element2.type.defaultProps) { defaultProps = element2.type.defaultProps; } for (propName in config) { if (hasOwnProperty3.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { if (config[propName] === void 0 && defaultProps !== void 0) { props[propName] = defaultProps[propName]; } else { props[propName] = config[propName]; } } } } var childrenLength = arguments.length - 2; if (childrenLength === 1) { props.children = children; } else if (childrenLength > 1) { var childArray = Array(childrenLength); for (var i = 0; i < childrenLength; i++) { childArray[i] = arguments[i + 2]; } props.children = childArray; } return ReactElement(element2.type, key, ref, self2, source, owner, props); } function isValidElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } var SEPARATOR = "."; var SUBSEPARATOR = ":"; function escape2(key) { var escapeRegex2 = /[=:]/g; var escaperLookup = { "=": "=0", ":": "=2" }; var escapedString = key.replace(escapeRegex2, function(match2) { return escaperLookup[match2]; }); return "$" + escapedString; } var didWarnAboutMaps = false; var userProvidedKeyEscapeRegex = /\/+/g; function escapeUserProvidedKey(text4) { return text4.replace(userProvidedKeyEscapeRegex, "$&/"); } function getElementKey(element2, index2) { if (typeof element2 === "object" && element2 !== null && element2.key != null) { { checkKeyStringCoercion(element2.key); } return escape2("" + element2.key); } return index2.toString(36); } function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { var type2 = typeof children; if (type2 === "undefined" || type2 === "boolean") { children = null; } var invokeCallback = false; if (children === null) { invokeCallback = true; } else { switch (type2) { case "string": case "number": invokeCallback = true; break; case "object": switch (children.$$typeof) { case REACT_ELEMENT_TYPE: case REACT_PORTAL_TYPE: invokeCallback = true; } } } if (invokeCallback) { var _child = children; var mappedChild = callback(_child); var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; if (isArray4(mappedChild)) { var escapedChildKey = ""; if (childKey != null) { escapedChildKey = escapeUserProvidedKey(childKey) + "/"; } mapIntoArray(mappedChild, array, escapedChildKey, "", function(c) { return c; }); } else if (mappedChild != null) { if (isValidElement(mappedChild)) { { if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { checkKeyStringCoercion(mappedChild.key); } } mappedChild = cloneAndReplaceKey( mappedChild, // Keep both the (mapped) and old keys if they differ, just as // traverseAllChildren used to do for objects as children escapedPrefix + // $FlowFixMe Flow incorrectly thinks React.Portal doesn't have a key (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? ( // $FlowFixMe Flow incorrectly thinks existing element's key can be a number // eslint-disable-next-line react-internal/safe-string-coercion escapeUserProvidedKey("" + mappedChild.key) + "/" ) : "") + childKey ); } array.push(mappedChild); } return 1; } var child; var nextName; var subtreeCount = 0; var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; if (isArray4(children)) { for (var i = 0; i < children.length; i++) { child = children[i]; nextName = nextNamePrefix + getElementKey(child, i); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else { var iteratorFn = getIteratorFn(children); if (typeof iteratorFn === "function") { var iterableChildren = children; { if (iteratorFn === iterableChildren.entries) { if (!didWarnAboutMaps) { warn("Using Maps as children is not supported. Use an array of keyed ReactElements instead."); } didWarnAboutMaps = true; } } var iterator = iteratorFn.call(iterableChildren); var step; var ii = 0; while (!(step = iterator.next()).done) { child = step.value; nextName = nextNamePrefix + getElementKey(child, ii++); subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); } } else if (type2 === "object") { var childrenString = String(children); throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). If you meant to render a collection of children, use an array instead."); } } return subtreeCount; } function mapChildren(children, func, context) { if (children == null) { return children; } var result = []; var count = 0; mapIntoArray(children, result, "", "", function(child) { return func.call(context, child, count++); }); return result; } function countChildren(children) { var n = 0; mapChildren(children, function() { n++; }); return n; } function forEachChildren(children, forEachFunc, forEachContext) { mapChildren(children, function() { forEachFunc.apply(this, arguments); }, forEachContext); } function toArray4(children) { return mapChildren(children, function(child) { return child; }) || []; } function onlyChild(children) { if (!isValidElement(children)) { throw new Error("React.Children.only expected to receive a single React element child."); } return children; } function createContext2(defaultValue) { var context = { $$typeof: REACT_CONTEXT_TYPE, // As a workaround to support multiple concurrent renderers, we categorize // some renderers as primary and others as secondary. We only expect // there to be two concurrent renderers at most: React Native (primary) and // Fabric (secondary); React DOM (primary) and React ART (secondary). // Secondary renderers store their context values on separate fields. _currentValue: defaultValue, _currentValue2: defaultValue, // Used to track how many concurrent renderers this context currently // supports within in a single renderer. Such as parallel server rendering. _threadCount: 0, // These are circular Provider: null, Consumer: null, // Add these to use same hidden class in VM as ServerContext _defaultValue: null, _globalName: null }; context.Provider = { $$typeof: REACT_PROVIDER_TYPE, _context: context }; var hasWarnedAboutUsingNestedContextConsumers = false; var hasWarnedAboutUsingConsumerProvider = false; var hasWarnedAboutDisplayNameOnConsumer = false; { var Consumer = { $$typeof: REACT_CONTEXT_TYPE, _context: context }; Object.defineProperties(Consumer, { Provider: { get: function() { if (!hasWarnedAboutUsingConsumerProvider) { hasWarnedAboutUsingConsumerProvider = true; error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Provider; }, set: function(_Provider) { context.Provider = _Provider; } }, _currentValue: { get: function() { return context._currentValue; }, set: function(_currentValue) { context._currentValue = _currentValue; } }, _currentValue2: { get: function() { return context._currentValue2; }, set: function(_currentValue2) { context._currentValue2 = _currentValue2; } }, _threadCount: { get: function() { return context._threadCount; }, set: function(_threadCount) { context._threadCount = _threadCount; } }, Consumer: { get: function() { if (!hasWarnedAboutUsingNestedContextConsumers) { hasWarnedAboutUsingNestedContextConsumers = true; error("Rendering is not supported and will be removed in a future major release. Did you mean to render instead?"); } return context.Consumer; } }, displayName: { get: function() { return context.displayName; }, set: function(displayName) { if (!hasWarnedAboutDisplayNameOnConsumer) { warn("Setting `displayName` on Context.Consumer has no effect. You should set it directly on the context with Context.displayName = '%s'.", displayName); hasWarnedAboutDisplayNameOnConsumer = true; } } } }); context.Consumer = Consumer; } { context._currentRenderer = null; context._currentRenderer2 = null; } return context; } var Uninitialized = -1; var Pending = 0; var Resolved = 1; var Rejected = 2; function lazyInitializer(payload) { if (payload._status === Uninitialized) { var ctor = payload._result; var thenable = ctor(); thenable.then(function(moduleObject2) { if (payload._status === Pending || payload._status === Uninitialized) { var resolved = payload; resolved._status = Resolved; resolved._result = moduleObject2; } }, function(error2) { if (payload._status === Pending || payload._status === Uninitialized) { var rejected = payload; rejected._status = Rejected; rejected._result = error2; } }); if (payload._status === Uninitialized) { var pending = payload; pending._status = Pending; pending._result = thenable; } } if (payload._status === Resolved) { var moduleObject = payload._result; { if (moduleObject === void 0) { error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))\n\nDid you accidentally put curly braces around the import?", moduleObject); } } { if (!("default" in moduleObject)) { error("lazy: Expected the result of a dynamic import() call. Instead received: %s\n\nYour code should look like: \n const MyComponent = lazy(() => import('./MyComponent'))", moduleObject); } } return moduleObject.default; } else { throw payload._result; } } function lazy(ctor) { var payload = { // We use these fields to store the result. _status: Uninitialized, _result: ctor }; var lazyType = { $$typeof: REACT_LAZY_TYPE, _payload: payload, _init: lazyInitializer }; { var defaultProps; var propTypes; Object.defineProperties(lazyType, { defaultProps: { configurable: true, get: function() { return defaultProps; }, set: function(newDefaultProps) { error("React.lazy(...): It is not supported to assign `defaultProps` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); defaultProps = newDefaultProps; Object.defineProperty(lazyType, "defaultProps", { enumerable: true }); } }, propTypes: { configurable: true, get: function() { return propTypes; }, set: function(newPropTypes) { error("React.lazy(...): It is not supported to assign `propTypes` to a lazy component import. Either specify them where the component is defined, or create a wrapping component around it."); propTypes = newPropTypes; Object.defineProperty(lazyType, "propTypes", { enumerable: true }); } } }); } return lazyType; } function forwardRef(render) { { if (render != null && render.$$typeof === REACT_MEMO_TYPE) { error("forwardRef requires a render function but received a `memo` component. Instead of forwardRef(memo(...)), use memo(forwardRef(...))."); } else if (typeof render !== "function") { error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); } else { if (render.length !== 0 && render.length !== 2) { error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); } } if (render != null) { if (render.defaultProps != null || render.propTypes != null) { error("forwardRef render functions do not support propTypes or defaultProps. Did you accidentally pass a React component?"); } } } var elementType = { $$typeof: REACT_FORWARD_REF_TYPE, render }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name) { ownName = name; if (!render.name && !render.displayName) { render.displayName = name; } } }); } return elementType; } var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); } function isValidElementType(type2) { if (typeof type2 === "string" || typeof type2 === "function") { return true; } if (type2 === REACT_FRAGMENT_TYPE || type2 === REACT_PROFILER_TYPE || enableDebugTracing || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type2 === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { return true; } if (typeof type2 === "object" && type2 !== null) { if (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type2.$$typeof === REACT_MODULE_REFERENCE || type2.getModuleId !== void 0) { return true; } } return false; } function memo2(type2, compare2) { { if (!isValidElementType(type2)) { error("memo: The first argument must be a component. Instead received: %s", type2 === null ? "null" : typeof type2); } } var elementType = { $$typeof: REACT_MEMO_TYPE, type: type2, compare: compare2 === void 0 ? null : compare2 }; { var ownName; Object.defineProperty(elementType, "displayName", { enumerable: false, configurable: true, get: function() { return ownName; }, set: function(name) { ownName = name; if (!type2.name && !type2.displayName) { type2.displayName = name; } } }); } return elementType; } function resolveDispatcher() { var dispatcher = ReactCurrentDispatcher.current; { if (dispatcher === null) { error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:\n1. You might have mismatching versions of React and the renderer (such as React DOM)\n2. You might be breaking the Rules of Hooks\n3. You might have more than one copy of React in the same app\nSee https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); } } return dispatcher; } function useContext2(Context) { var dispatcher = resolveDispatcher(); { if (Context._context !== void 0) { var realContext = Context._context; if (realContext.Consumer === Context) { error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be removed in a future major release. Did you mean to call useContext(Context) instead?"); } else if (realContext.Provider === Context) { error("Calling useContext(Context.Provider) is not supported. Did you mean to call useContext(Context) instead?"); } } } return dispatcher.useContext(Context); } function useState7(initialState) { var dispatcher = resolveDispatcher(); return dispatcher.useState(initialState); } function useReducer(reducer2, initialArg, init2) { var dispatcher = resolveDispatcher(); return dispatcher.useReducer(reducer2, initialArg, init2); } function useRef2(initialValue) { var dispatcher = resolveDispatcher(); return dispatcher.useRef(initialValue); } function useEffect6(create2, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useEffect(create2, deps); } function useInsertionEffect(create2, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useInsertionEffect(create2, deps); } function useLayoutEffect(create2, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useLayoutEffect(create2, deps); } function useCallback(callback, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useCallback(callback, deps); } function useMemo(create2, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useMemo(create2, deps); } function useImperativeHandle(ref, create2, deps) { var dispatcher = resolveDispatcher(); return dispatcher.useImperativeHandle(ref, create2, deps); } function useDebugValue(value, formatterFn) { { var dispatcher = resolveDispatcher(); return dispatcher.useDebugValue(value, formatterFn); } } function useTransition() { var dispatcher = resolveDispatcher(); return dispatcher.useTransition(); } function useDeferredValue(value) { var dispatcher = resolveDispatcher(); return dispatcher.useDeferredValue(value); } function useId() { var dispatcher = resolveDispatcher(); return dispatcher.useId(); } function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { var dispatcher = resolveDispatcher(); return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); } var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign2({}, props, { value: prevLog }), info: assign2({}, props, { value: prevInfo }), warn: assign2({}, props, { value: prevWarn }), error: assign2({}, props, { value: prevError }), group: assign2({}, props, { value: prevGroup }), groupCollapsed: assign2({}, props, { value: prevGroupCollapsed }), groupEnd: assign2({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x) { var match2 = x.stack.trim().match(/\n( *(at )?)/); prefix = match2 && match2[1] || ""; } } return "\n" + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher$1.current; ReactCurrentDispatcher$1.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { c--; } for (; s >= 1 && c >= 0; s--, c--) { if (sampleLines[s] !== controlLines[c]) { if (s !== 1 || c !== 1) { do { s--; c--; if (c < 0 || sampleLines[s] !== controlLines[c]) { var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher$1.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component2) { var prototype3 = Component2.prototype; return !!(prototype3 && prototype3.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) { if (type2 == null) { return ""; } if (typeof type2 === "function") { { return describeNativeComponentFrame(type2, shouldConstruct(type2)); } } if (typeof type2 === "string") { return describeBuiltInComponentFrame(type2); } switch (type2) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type2.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn); } catch (x) { } } } } return ""; } var loggedTypeFailures = {}; var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; function setCurrentlyValidatingElement(element2) { { if (element2) { var owner = element2._owner; var stack = describeUnknownElementTypeFrameInDEV(element2.type, element2._source, owner ? owner.type : null); ReactDebugCurrentFrame$1.setExtraStackFrame(stack); } else { ReactDebugCurrentFrame$1.setExtraStackFrame(null); } } } function checkPropTypes(typeSpecs, values, location, componentName, element2) { { var has = Function.call.bind(hasOwnProperty3); for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error$1 = void 0; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); err.name = "Invariant Violation"; throw err; } error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (ex) { error$1 = ex; } if (error$1 && !(error$1 instanceof Error)) { setCurrentlyValidatingElement(element2); error("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); setCurrentlyValidatingElement(null); } if (error$1 instanceof Error && !(error$1.message in loggedTypeFailures)) { loggedTypeFailures[error$1.message] = true; setCurrentlyValidatingElement(element2); error("Failed %s type: %s", location, error$1.message); setCurrentlyValidatingElement(null); } } } } } function setCurrentlyValidatingElement$1(element2) { { if (element2) { var owner = element2._owner; var stack = describeUnknownElementTypeFrameInDEV(element2.type, element2._source, owner ? owner.type : null); setExtraStackFrame(stack); } else { setExtraStackFrame(null); } } } var propTypesMisspellWarningShown; { propTypesMisspellWarningShown = false; } function getDeclarationErrorAddendum() { if (ReactCurrentOwner.current) { var name = getComponentNameFromType(ReactCurrentOwner.current.type); if (name) { return "\n\nCheck the render method of `" + name + "`."; } } return ""; } function getSourceInfoErrorAddendum(source) { if (source !== void 0) { var fileName = source.fileName.replace(/^.*[\\\/]/, ""); var lineNumber = source.lineNumber; return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; } return ""; } function getSourceInfoErrorAddendumForProps(elementProps) { if (elementProps !== null && elementProps !== void 0) { return getSourceInfoErrorAddendum(elementProps.__source); } return ""; } var ownerHasKeyUseWarning = {}; function getCurrentComponentErrorInfo(parentType) { var info = getDeclarationErrorAddendum(); if (!info) { var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; if (parentName) { info = "\n\nCheck the top-level render call using <" + parentName + ">."; } } return info; } function validateExplicitKey(element2, parentType) { if (!element2._store || element2._store.validated || element2.key != null) { return; } element2._store.validated = true; var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { return; } ownerHasKeyUseWarning[currentComponentErrorInfo] = true; var childOwner = ""; if (element2 && element2._owner && element2._owner !== ReactCurrentOwner.current) { childOwner = " It was passed a child from " + getComponentNameFromType(element2._owner.type) + "."; } { setCurrentlyValidatingElement$1(element2); error('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', currentComponentErrorInfo, childOwner); setCurrentlyValidatingElement$1(null); } } function validateChildKeys(node2, parentType) { if (typeof node2 !== "object") { return; } if (isArray4(node2)) { for (var i = 0; i < node2.length; i++) { var child = node2[i]; if (isValidElement(child)) { validateExplicitKey(child, parentType); } } } else if (isValidElement(node2)) { if (node2._store) { node2._store.validated = true; } } else if (node2) { var iteratorFn = getIteratorFn(node2); if (typeof iteratorFn === "function") { if (iteratorFn !== node2.entries) { var iterator = iteratorFn.call(node2); var step; while (!(step = iterator.next()).done) { if (isValidElement(step.value)) { validateExplicitKey(step.value, parentType); } } } } } } function validatePropTypes(element2) { { var type2 = element2.type; if (type2 === null || type2 === void 0 || typeof type2 === "string") { return; } var propTypes; if (typeof type2 === "function") { propTypes = type2.propTypes; } else if (typeof type2 === "object" && (type2.$$typeof === REACT_FORWARD_REF_TYPE || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. type2.$$typeof === REACT_MEMO_TYPE)) { propTypes = type2.propTypes; } else { return; } if (propTypes) { var name = getComponentNameFromType(type2); checkPropTypes(propTypes, element2.props, "prop", name, element2); } else if (type2.PropTypes !== void 0 && !propTypesMisspellWarningShown) { propTypesMisspellWarningShown = true; var _name = getComponentNameFromType(type2); error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); } if (typeof type2.getDefaultProps === "function" && !type2.getDefaultProps.isReactClassApproved) { error("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } } function validateFragmentProps(fragment) { { var keys3 = Object.keys(fragment.props); for (var i = 0; i < keys3.length; i++) { var key = keys3[i]; if (key !== "children" && key !== "key") { setCurrentlyValidatingElement$1(fragment); error("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", key); setCurrentlyValidatingElement$1(null); break; } } if (fragment.ref !== null) { setCurrentlyValidatingElement$1(fragment); error("Invalid attribute `ref` supplied to `React.Fragment`."); setCurrentlyValidatingElement$1(null); } } } function createElementWithValidation(type2, props, children) { var validType = isValidElementType(type2); if (!validType) { var info = ""; if (type2 === void 0 || typeof type2 === "object" && type2 !== null && Object.keys(type2).length === 0) { info += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."; } var sourceInfo = getSourceInfoErrorAddendumForProps(props); if (sourceInfo) { info += sourceInfo; } else { info += getDeclarationErrorAddendum(); } var typeString; if (type2 === null) { typeString = "null"; } else if (isArray4(type2)) { typeString = "array"; } else if (type2 !== void 0 && type2.$$typeof === REACT_ELEMENT_TYPE) { typeString = "<" + (getComponentNameFromType(type2.type) || "Unknown") + " />"; info = " Did you accidentally export a JSX literal instead of a component?"; } else { typeString = typeof type2; } { error("React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", typeString, info); } } var element2 = createElement2.apply(this, arguments); if (element2 == null) { return element2; } if (validType) { for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], type2); } } if (type2 === REACT_FRAGMENT_TYPE) { validateFragmentProps(element2); } else { validatePropTypes(element2); } return element2; } var didWarnAboutDeprecatedCreateFactory = false; function createFactoryWithValidation(type2) { var validatedFactory = createElementWithValidation.bind(null, type2); validatedFactory.type = type2; { if (!didWarnAboutDeprecatedCreateFactory) { didWarnAboutDeprecatedCreateFactory = true; warn("React.createFactory() is deprecated and will be removed in a future major release. Consider using JSX or use React.createElement() directly instead."); } Object.defineProperty(validatedFactory, "type", { enumerable: false, get: function() { warn("Factory.type is deprecated. Access the class directly before passing it to createFactory."); Object.defineProperty(this, "type", { value: type2 }); return type2; } }); } return validatedFactory; } function cloneElementWithValidation(element2, props, children) { var newElement = cloneElement.apply(this, arguments); for (var i = 2; i < arguments.length; i++) { validateChildKeys(arguments[i], newElement.type); } validatePropTypes(newElement); return newElement; } function startTransition(scope, options) { var prevTransition = ReactCurrentBatchConfig.transition; ReactCurrentBatchConfig.transition = {}; var currentTransition = ReactCurrentBatchConfig.transition; { ReactCurrentBatchConfig.transition._updatedFibers = /* @__PURE__ */ new Set(); } try { scope(); } finally { ReactCurrentBatchConfig.transition = prevTransition; { if (prevTransition === null && currentTransition._updatedFibers) { var updatedFibersCount = currentTransition._updatedFibers.size; if (updatedFibersCount > 10) { warn("Detected a large number of updates inside startTransition. If this is due to a subscription please re-write it to use React provided hooks. Otherwise concurrent mode guarantees are off the table."); } currentTransition._updatedFibers.clear(); } } } } var didWarnAboutMessageChannel = false; var enqueueTaskImpl = null; function enqueueTask2(task) { if (enqueueTaskImpl === null) { try { var requireString = ("require" + Math.random()).slice(0, 7); var nodeRequire = module2 && module2[requireString]; enqueueTaskImpl = nodeRequire.call(module2, "timers").setImmediate; } catch (_err) { enqueueTaskImpl = function(callback) { { if (didWarnAboutMessageChannel === false) { didWarnAboutMessageChannel = true; if (typeof MessageChannel === "undefined") { error("This browser does not have a MessageChannel implementation, so enqueuing tasks via await act(async () => ...) will fail. Please file an issue at https://github.com/facebook/react/issues if you encounter this warning."); } } } var channel = new MessageChannel(); channel.port1.onmessage = callback; channel.port2.postMessage(void 0); }; } } return enqueueTaskImpl(task); } var actScopeDepth = 0; var didWarnNoAwaitAct = false; function act(callback) { { var prevActScopeDepth = actScopeDepth; actScopeDepth++; if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; } var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; var result; try { ReactCurrentActQueue.isBatchingLegacy = true; result = callback(); if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { var queue3 = ReactCurrentActQueue.current; if (queue3 !== null) { ReactCurrentActQueue.didScheduleLegacyUpdate = false; flushActQueue(queue3); } } } catch (error2) { popActScope(prevActScopeDepth); throw error2; } finally { ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; } if (result !== null && typeof result === "object" && typeof result.then === "function") { var thenableResult = result; var wasAwaited = false; var thenable = { then: function(resolve, reject) { wasAwaited = true; thenableResult.then(function(returnValue2) { popActScope(prevActScopeDepth); if (actScopeDepth === 0) { recursivelyFlushAsyncActWork(returnValue2, resolve, reject); } else { resolve(returnValue2); } }, function(error2) { popActScope(prevActScopeDepth); reject(error2); }); } }; { if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { Promise.resolve().then(function() { }).then(function() { if (!wasAwaited) { didWarnNoAwaitAct = true; error("You called act(async () => ...) without await. This could lead to unexpected testing behaviour, interleaving multiple act calls and mixing their scopes. You should - await act(async () => ...);"); } }); } } return thenable; } else { var returnValue = result; popActScope(prevActScopeDepth); if (actScopeDepth === 0) { var _queue = ReactCurrentActQueue.current; if (_queue !== null) { flushActQueue(_queue); ReactCurrentActQueue.current = null; } var _thenable = { then: function(resolve, reject) { if (ReactCurrentActQueue.current === null) { ReactCurrentActQueue.current = []; recursivelyFlushAsyncActWork(returnValue, resolve, reject); } else { resolve(returnValue); } } }; return _thenable; } else { var _thenable2 = { then: function(resolve, reject) { resolve(returnValue); } }; return _thenable2; } } } } function popActScope(prevActScopeDepth) { { if (prevActScopeDepth !== actScopeDepth - 1) { error("You seem to have overlapping act() calls, this is not supported. Be sure to await previous act() calls before making a new one. "); } actScopeDepth = prevActScopeDepth; } } function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { { var queue3 = ReactCurrentActQueue.current; if (queue3 !== null) { try { flushActQueue(queue3); enqueueTask2(function() { if (queue3.length === 0) { ReactCurrentActQueue.current = null; resolve(returnValue); } else { recursivelyFlushAsyncActWork(returnValue, resolve, reject); } }); } catch (error2) { reject(error2); } } else { resolve(returnValue); } } } var isFlushing = false; function flushActQueue(queue3) { { if (!isFlushing) { isFlushing = true; var i = 0; try { for (; i < queue3.length; i++) { var callback = queue3[i]; do { callback = callback(true); } while (callback !== null); } queue3.length = 0; } catch (error2) { queue3 = queue3.slice(i + 1); throw error2; } finally { isFlushing = false; } } } } var createElement$1 = createElementWithValidation; var cloneElement$1 = cloneElementWithValidation; var createFactory = createFactoryWithValidation; var Children = { map: mapChildren, forEach: forEachChildren, count: countChildren, toArray: toArray4, only: onlyChild }; exports.Children = Children; exports.Component = Component; exports.Fragment = REACT_FRAGMENT_TYPE; exports.Profiler = REACT_PROFILER_TYPE; exports.PureComponent = PureComponent; exports.StrictMode = REACT_STRICT_MODE_TYPE; exports.Suspense = REACT_SUSPENSE_TYPE; exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; exports.cloneElement = cloneElement$1; exports.createContext = createContext2; exports.createElement = createElement$1; exports.createFactory = createFactory; exports.createRef = createRef; exports.forwardRef = forwardRef; exports.isValidElement = isValidElement; exports.lazy = lazy; exports.memo = memo2; exports.startTransition = startTransition; exports.unstable_act = act; exports.useCallback = useCallback; exports.useContext = useContext2; exports.useDebugValue = useDebugValue; exports.useDeferredValue = useDeferredValue; exports.useEffect = useEffect6; exports.useId = useId; exports.useImperativeHandle = useImperativeHandle; exports.useInsertionEffect = useInsertionEffect; exports.useLayoutEffect = useLayoutEffect; exports.useMemo = useMemo; exports.useReducer = useReducer; exports.useRef = useRef2; exports.useState = useState7; exports.useSyncExternalStore = useSyncExternalStore; exports.useTransition = useTransition; exports.version = ReactVersion; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } } }); // node_modules/react/index.js var require_react = __commonJS({ "node_modules/react/index.js"(exports, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_react_development(); } } }); // node_modules/is-buffer/index.js var require_is_buffer = __commonJS({ "node_modules/is-buffer/index.js"(exports, module2) { module2.exports = function isBuffer3(obj) { return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); }; } }); // node_modules/extend/index.js var require_extend = __commonJS({ "node_modules/extend/index.js"(exports, module2) { "use strict"; var hasOwn = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var defineProperty = Object.defineProperty; var gOPD = Object.getOwnPropertyDescriptor; var isArray4 = function isArray5(arr) { if (typeof Array.isArray === "function") { return Array.isArray(arr); } return toStr.call(arr) === "[object Array]"; }; var isPlainObject4 = function isPlainObject5(obj) { if (!obj || toStr.call(obj) !== "[object Object]") { return false; } var hasOwnConstructor = hasOwn.call(obj, "constructor"); var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, "isPrototypeOf"); if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { return false; } var key; for (key in obj) { } return typeof key === "undefined" || hasOwn.call(obj, key); }; var setProperty = function setProperty2(target, options) { if (defineProperty && options.name === "__proto__") { defineProperty(target, options.name, { enumerable: true, configurable: true, value: options.newValue, writable: true }); } else { target[options.name] = options.newValue; } }; var getProperty = function getProperty2(obj, name) { if (name === "__proto__") { if (!hasOwn.call(obj, name)) { return void 0; } else if (gOPD) { return gOPD(obj, name).value; } } return obj[name]; }; module2.exports = function extend5() { var options, name, src, copy, copyIsArray, clone2; var target = arguments[0]; var i = 1; var length = arguments.length; var deep = false; if (typeof target === "boolean") { deep = target; target = arguments[1] || {}; i = 2; } if (target == null || typeof target !== "object" && typeof target !== "function") { target = {}; } for (; i < length; ++i) { options = arguments[i]; if (options != null) { for (name in options) { src = getProperty(target, name); copy = getProperty(options, name); if (target !== copy) { if (deep && copy && (isPlainObject4(copy) || (copyIsArray = isArray4(copy)))) { if (copyIsArray) { copyIsArray = false; clone2 = src && isArray4(src) ? src : []; } else { clone2 = src && isPlainObject4(src) ? src : {}; } setProperty(target, { name, newValue: extend5(deep, clone2, copy) }); } else if (typeof copy !== "undefined") { setProperty(target, { name, newValue: copy }); } } } } } return target; }; } }); // node_modules/react-is/cjs/react-is.development.js var require_react_is_development = __commonJS({ "node_modules/react-is/cjs/react-is.development.js"(exports) { "use strict"; if (true) { (function() { "use strict"; var hasSymbol = typeof Symbol === "function" && Symbol.for; var REACT_ELEMENT_TYPE = hasSymbol ? Symbol.for("react.element") : 60103; var REACT_PORTAL_TYPE = hasSymbol ? Symbol.for("react.portal") : 60106; var REACT_FRAGMENT_TYPE = hasSymbol ? Symbol.for("react.fragment") : 60107; var REACT_STRICT_MODE_TYPE = hasSymbol ? Symbol.for("react.strict_mode") : 60108; var REACT_PROFILER_TYPE = hasSymbol ? Symbol.for("react.profiler") : 60114; var REACT_PROVIDER_TYPE = hasSymbol ? Symbol.for("react.provider") : 60109; var REACT_CONTEXT_TYPE = hasSymbol ? Symbol.for("react.context") : 60110; var REACT_ASYNC_MODE_TYPE = hasSymbol ? Symbol.for("react.async_mode") : 60111; var REACT_CONCURRENT_MODE_TYPE = hasSymbol ? Symbol.for("react.concurrent_mode") : 60111; var REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for("react.forward_ref") : 60112; var REACT_SUSPENSE_TYPE = hasSymbol ? Symbol.for("react.suspense") : 60113; var REACT_SUSPENSE_LIST_TYPE = hasSymbol ? Symbol.for("react.suspense_list") : 60120; var REACT_MEMO_TYPE = hasSymbol ? Symbol.for("react.memo") : 60115; var REACT_LAZY_TYPE = hasSymbol ? Symbol.for("react.lazy") : 60116; var REACT_BLOCK_TYPE = hasSymbol ? Symbol.for("react.block") : 60121; var REACT_FUNDAMENTAL_TYPE = hasSymbol ? Symbol.for("react.fundamental") : 60117; var REACT_RESPONDER_TYPE = hasSymbol ? Symbol.for("react.responder") : 60118; var REACT_SCOPE_TYPE = hasSymbol ? Symbol.for("react.scope") : 60119; function isValidElementType(type2) { return typeof type2 === "string" || typeof type2 === "function" || // Note: its typeof might be other than 'symbol' or 'number' if it's a polyfill. type2 === REACT_FRAGMENT_TYPE || type2 === REACT_CONCURRENT_MODE_TYPE || type2 === REACT_PROFILER_TYPE || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || typeof type2 === "object" && type2 !== null && (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || type2.$$typeof === REACT_FUNDAMENTAL_TYPE || type2.$$typeof === REACT_RESPONDER_TYPE || type2.$$typeof === REACT_SCOPE_TYPE || type2.$$typeof === REACT_BLOCK_TYPE); } function typeOf(object) { if (typeof object === "object" && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type2 = object.type; switch (type2) { case REACT_ASYNC_MODE_TYPE: case REACT_CONCURRENT_MODE_TYPE: case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: return type2; default: var $$typeofType = type2 && type2.$$typeof; switch ($$typeofType) { case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return void 0; } var AsyncMode = REACT_ASYNC_MODE_TYPE; var ConcurrentMode = REACT_CONCURRENT_MODE_TYPE; var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode2 = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 17+. Update your code to use ReactIs.isConcurrentMode() instead. It has the exact same API."); } } return isConcurrentMode(object) || typeOf(object) === REACT_ASYNC_MODE_TYPE; } function isConcurrentMode(object) { return typeOf(object) === REACT_CONCURRENT_MODE_TYPE; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } exports.AsyncMode = AsyncMode; exports.ConcurrentMode = ConcurrentMode; exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode2; exports.Suspense = Suspense; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; exports.isValidElementType = isValidElementType; exports.typeOf = typeOf; })(); } } }); // node_modules/react-is/index.js var require_react_is = __commonJS({ "node_modules/react-is/index.js"(exports, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_react_is_development(); } } }); // node_modules/object-assign/index.js var require_object_assign = __commonJS({ "node_modules/object-assign/index.js"(exports, module2) { "use strict"; var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty3 = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; function toObject2(val) { if (val === null || val === void 0) { throw new TypeError("Object.assign cannot be called with null or undefined"); } return Object(val); } function shouldUseNative() { try { if (!Object.assign) { return false; } var test1 = new String("abc"); test1[5] = "de"; if (Object.getOwnPropertyNames(test1)[0] === "5") { return false; } var test2 = {}; for (var i = 0; i < 10; i++) { test2["_" + String.fromCharCode(i)] = i; } var order2 = Object.getOwnPropertyNames(test2).map(function(n) { return test2[n]; }); if (order2.join("") !== "0123456789") { return false; } var test3 = {}; "abcdefghijklmnopqrst".split("").forEach(function(letter) { test3[letter] = letter; }); if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { return false; } return true; } catch (err) { return false; } } module2.exports = shouldUseNative() ? Object.assign : function(target, source) { var from; var to = toObject2(target); var symbols; for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); for (var key in from) { if (hasOwnProperty3.call(from, key)) { to[key] = from[key]; } } if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { if (propIsEnumerable.call(from, symbols[i])) { to[symbols[i]] = from[symbols[i]]; } } } } return to; }; } }); // node_modules/prop-types/lib/ReactPropTypesSecret.js var require_ReactPropTypesSecret = __commonJS({ "node_modules/prop-types/lib/ReactPropTypesSecret.js"(exports, module2) { "use strict"; var ReactPropTypesSecret = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"; module2.exports = ReactPropTypesSecret; } }); // node_modules/prop-types/lib/has.js var require_has = __commonJS({ "node_modules/prop-types/lib/has.js"(exports, module2) { module2.exports = Function.call.bind(Object.prototype.hasOwnProperty); } }); // node_modules/prop-types/checkPropTypes.js var require_checkPropTypes = __commonJS({ "node_modules/prop-types/checkPropTypes.js"(exports, module2) { "use strict"; var printWarning = function() { }; if (true) { ReactPropTypesSecret = require_ReactPropTypesSecret(); loggedTypeFailures = {}; has = require_has(); printWarning = function(text4) { var message = "Warning: " + text4; if (typeof console !== "undefined") { console.error(message); } try { throw new Error(message); } catch (x) { } }; } var ReactPropTypesSecret; var loggedTypeFailures; var has; function checkPropTypes(typeSpecs, values, location, componentName, getStack) { if (true) { for (var typeSpecName in typeSpecs) { if (has(typeSpecs, typeSpecName)) { var error; try { if (typeof typeSpecs[typeSpecName] !== "function") { var err = Error( (componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`." ); err.name = "Invariant Violation"; throw err; } error = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, ReactPropTypesSecret); } catch (ex) { error = ex; } if (error && !(error instanceof Error)) { printWarning( (componentName || "React class") + ": type specification of " + location + " `" + typeSpecName + "` is invalid; the type checker function must return `null` or an `Error` but returned a " + typeof error + ". You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument)." ); } if (error instanceof Error && !(error.message in loggedTypeFailures)) { loggedTypeFailures[error.message] = true; var stack = getStack ? getStack() : ""; printWarning( "Failed " + location + " type: " + error.message + (stack != null ? stack : "") ); } } } } } checkPropTypes.resetWarningCache = function() { if (true) { loggedTypeFailures = {}; } }; module2.exports = checkPropTypes; } }); // node_modules/prop-types/factoryWithTypeCheckers.js var require_factoryWithTypeCheckers = __commonJS({ "node_modules/prop-types/factoryWithTypeCheckers.js"(exports, module2) { "use strict"; var ReactIs2 = require_react_is(); var assign2 = require_object_assign(); var ReactPropTypesSecret = require_ReactPropTypesSecret(); var has = require_has(); var checkPropTypes = require_checkPropTypes(); var printWarning = function() { }; if (true) { printWarning = function(text4) { var message = "Warning: " + text4; if (typeof console !== "undefined") { console.error(message); } try { throw new Error(message); } catch (x) { } }; } function emptyFunctionThatReturnsNull() { return null; } module2.exports = function(isValidElement, throwOnDirectAccess) { var ITERATOR_SYMBOL = typeof Symbol === "function" && Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { var iteratorFn = maybeIterable && (ITERATOR_SYMBOL && maybeIterable[ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]); if (typeof iteratorFn === "function") { return iteratorFn; } } var ANONYMOUS = "<>"; var ReactPropTypes = { array: createPrimitiveTypeChecker("array"), bigint: createPrimitiveTypeChecker("bigint"), bool: createPrimitiveTypeChecker("boolean"), func: createPrimitiveTypeChecker("function"), number: createPrimitiveTypeChecker("number"), object: createPrimitiveTypeChecker("object"), string: createPrimitiveTypeChecker("string"), symbol: createPrimitiveTypeChecker("symbol"), any: createAnyTypeChecker(), arrayOf: createArrayOfTypeChecker, element: createElementTypeChecker(), elementType: createElementTypeTypeChecker(), instanceOf: createInstanceTypeChecker, node: createNodeChecker(), objectOf: createObjectOfTypeChecker, oneOf: createEnumTypeChecker, oneOfType: createUnionTypeChecker, shape: createShapeTypeChecker, exact: createStrictShapeTypeChecker }; function is2(x, y) { if (x === y) { return x !== 0 || 1 / x === 1 / y; } else { return x !== x && y !== y; } } function PropTypeError(message, data) { this.message = message; this.data = data && typeof data === "object" ? data : {}; this.stack = ""; } PropTypeError.prototype = Error.prototype; function createChainableTypeChecker(validate3) { if (true) { var manualPropTypeCallCache = {}; var manualPropTypeWarningCount = 0; } function checkType(isRequired, props, propName, componentName, location, propFullName, secret) { componentName = componentName || ANONYMOUS; propFullName = propFullName || propName; if (secret !== ReactPropTypesSecret) { if (throwOnDirectAccess) { var err = new Error( "Calling PropTypes validators directly is not supported by the `prop-types` package. Use `PropTypes.checkPropTypes()` to call them. Read more at http://fb.me/use-check-prop-types" ); err.name = "Invariant Violation"; throw err; } else if (typeof console !== "undefined") { var cacheKey = componentName + ":" + propName; if (!manualPropTypeCallCache[cacheKey] && // Avoid spamming the console because they are often not actionable except for lib authors manualPropTypeWarningCount < 3) { printWarning( "You are manually calling a React.PropTypes validation function for the `" + propFullName + "` prop on `" + componentName + "`. This is deprecated and will throw in the standalone `prop-types` package. You may be seeing this warning due to a third-party PropTypes library. See https://fb.me/react-warning-dont-call-proptypes for details." ); manualPropTypeCallCache[cacheKey] = true; manualPropTypeWarningCount++; } } } if (props[propName] == null) { if (isRequired) { if (props[propName] === null) { return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required " + ("in `" + componentName + "`, but its value is `null`.")); } return new PropTypeError("The " + location + " `" + propFullName + "` is marked as required in " + ("`" + componentName + "`, but its value is `undefined`.")); } return null; } else { return validate3(props, propName, componentName, location, propFullName); } } var chainedCheckType = checkType.bind(null, false); chainedCheckType.isRequired = checkType.bind(null, true); return chainedCheckType; } function createPrimitiveTypeChecker(expectedType) { function validate3(props, propName, componentName, location, propFullName, secret) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== expectedType) { var preciseType = getPreciseType(propValue); return new PropTypeError( "Invalid " + location + " `" + propFullName + "` of type " + ("`" + preciseType + "` supplied to `" + componentName + "`, expected ") + ("`" + expectedType + "`."), { expectedType } ); } return null; } return createChainableTypeChecker(validate3); } function createAnyTypeChecker() { return createChainableTypeChecker(emptyFunctionThatReturnsNull); } function createArrayOfTypeChecker(typeChecker) { function validate3(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== "function") { return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside arrayOf."); } var propValue = props[propName]; if (!Array.isArray(propValue)) { var propType = getPropType(propValue); return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an array.")); } for (var i = 0; i < propValue.length; i++) { var error = typeChecker(propValue, i, componentName, location, propFullName + "[" + i + "]", ReactPropTypesSecret); if (error instanceof Error) { return error; } } return null; } return createChainableTypeChecker(validate3); } function createElementTypeChecker() { function validate3(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!isValidElement(propValue)) { var propType = getPropType(propValue); return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement.")); } return null; } return createChainableTypeChecker(validate3); } function createElementTypeTypeChecker() { function validate3(props, propName, componentName, location, propFullName) { var propValue = props[propName]; if (!ReactIs2.isValidElementType(propValue)) { var propType = getPropType(propValue); return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected a single ReactElement type.")); } return null; } return createChainableTypeChecker(validate3); } function createInstanceTypeChecker(expectedClass) { function validate3(props, propName, componentName, location, propFullName) { if (!(props[propName] instanceof expectedClass)) { var expectedClassName = expectedClass.name || ANONYMOUS; var actualClassName = getClassName(props[propName]); return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + actualClassName + "` supplied to `" + componentName + "`, expected ") + ("instance of `" + expectedClassName + "`.")); } return null; } return createChainableTypeChecker(validate3); } function createEnumTypeChecker(expectedValues) { if (!Array.isArray(expectedValues)) { if (true) { if (arguments.length > 1) { printWarning( "Invalid arguments supplied to oneOf, expected an array, got " + arguments.length + " arguments. A common mistake is to write oneOf(x, y, z) instead of oneOf([x, y, z])." ); } else { printWarning("Invalid argument supplied to oneOf, expected an array."); } } return emptyFunctionThatReturnsNull; } function validate3(props, propName, componentName, location, propFullName) { var propValue = props[propName]; for (var i = 0; i < expectedValues.length; i++) { if (is2(propValue, expectedValues[i])) { return null; } } var valuesString = JSON.stringify(expectedValues, function replacer(key, value) { var type2 = getPreciseType(value); if (type2 === "symbol") { return String(value); } return value; }); return new PropTypeError("Invalid " + location + " `" + propFullName + "` of value `" + String(propValue) + "` " + ("supplied to `" + componentName + "`, expected one of " + valuesString + ".")); } return createChainableTypeChecker(validate3); } function createObjectOfTypeChecker(typeChecker) { function validate3(props, propName, componentName, location, propFullName) { if (typeof typeChecker !== "function") { return new PropTypeError("Property `" + propFullName + "` of component `" + componentName + "` has invalid PropType notation inside objectOf."); } var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type " + ("`" + propType + "` supplied to `" + componentName + "`, expected an object.")); } for (var key in propValue) { if (has(propValue, key)) { var error = typeChecker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret); if (error instanceof Error) { return error; } } } return null; } return createChainableTypeChecker(validate3); } function createUnionTypeChecker(arrayOfTypeCheckers) { if (!Array.isArray(arrayOfTypeCheckers)) { true ? printWarning("Invalid argument supplied to oneOfType, expected an instance of array.") : void 0; return emptyFunctionThatReturnsNull; } for (var i = 0; i < arrayOfTypeCheckers.length; i++) { var checker = arrayOfTypeCheckers[i]; if (typeof checker !== "function") { printWarning( "Invalid argument supplied to oneOfType. Expected an array of check functions, but received " + getPostfixForTypeWarning(checker) + " at index " + i + "." ); return emptyFunctionThatReturnsNull; } } function validate3(props, propName, componentName, location, propFullName) { var expectedTypes = []; for (var i2 = 0; i2 < arrayOfTypeCheckers.length; i2++) { var checker2 = arrayOfTypeCheckers[i2]; var checkerResult = checker2(props, propName, componentName, location, propFullName, ReactPropTypesSecret); if (checkerResult == null) { return null; } if (checkerResult.data && has(checkerResult.data, "expectedType")) { expectedTypes.push(checkerResult.data.expectedType); } } var expectedTypesMessage = expectedTypes.length > 0 ? ", expected one of type [" + expectedTypes.join(", ") + "]" : ""; return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`" + expectedTypesMessage + ".")); } return createChainableTypeChecker(validate3); } function createNodeChecker() { function validate3(props, propName, componentName, location, propFullName) { if (!isNode3(props[propName])) { return new PropTypeError("Invalid " + location + " `" + propFullName + "` supplied to " + ("`" + componentName + "`, expected a ReactNode.")); } return null; } return createChainableTypeChecker(validate3); } function invalidValidatorError(componentName, location, propFullName, key, type2) { return new PropTypeError( (componentName || "React class") + ": " + location + " type `" + propFullName + "." + key + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + type2 + "`." ); } function createShapeTypeChecker(shapeTypes) { function validate3(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); } for (var key in shapeTypes) { var checker = shapeTypes[key]; if (typeof checker !== "function") { return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); } var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate3); } function createStrictShapeTypeChecker(shapeTypes) { function validate3(props, propName, componentName, location, propFullName) { var propValue = props[propName]; var propType = getPropType(propValue); if (propType !== "object") { return new PropTypeError("Invalid " + location + " `" + propFullName + "` of type `" + propType + "` " + ("supplied to `" + componentName + "`, expected `object`.")); } var allKeys = assign2({}, props[propName], shapeTypes); for (var key in allKeys) { var checker = shapeTypes[key]; if (has(shapeTypes, key) && typeof checker !== "function") { return invalidValidatorError(componentName, location, propFullName, key, getPreciseType(checker)); } if (!checker) { return new PropTypeError( "Invalid " + location + " `" + propFullName + "` key `" + key + "` supplied to `" + componentName + "`.\nBad object: " + JSON.stringify(props[propName], null, " ") + "\nValid keys: " + JSON.stringify(Object.keys(shapeTypes), null, " ") ); } var error = checker(propValue, key, componentName, location, propFullName + "." + key, ReactPropTypesSecret); if (error) { return error; } } return null; } return createChainableTypeChecker(validate3); } function isNode3(propValue) { switch (typeof propValue) { case "number": case "string": case "undefined": return true; case "boolean": return !propValue; case "object": if (Array.isArray(propValue)) { return propValue.every(isNode3); } if (propValue === null || isValidElement(propValue)) { return true; } var iteratorFn = getIteratorFn(propValue); if (iteratorFn) { var iterator = iteratorFn.call(propValue); var step; if (iteratorFn !== propValue.entries) { while (!(step = iterator.next()).done) { if (!isNode3(step.value)) { return false; } } } else { while (!(step = iterator.next()).done) { var entry = step.value; if (entry) { if (!isNode3(entry[1])) { return false; } } } } } else { return false; } return true; default: return false; } } function isSymbol(propType, propValue) { if (propType === "symbol") { return true; } if (!propValue) { return false; } if (propValue["@@toStringTag"] === "Symbol") { return true; } if (typeof Symbol === "function" && propValue instanceof Symbol) { return true; } return false; } function getPropType(propValue) { var propType = typeof propValue; if (Array.isArray(propValue)) { return "array"; } if (propValue instanceof RegExp) { return "object"; } if (isSymbol(propType, propValue)) { return "symbol"; } return propType; } function getPreciseType(propValue) { if (typeof propValue === "undefined" || propValue === null) { return "" + propValue; } var propType = getPropType(propValue); if (propType === "object") { if (propValue instanceof Date) { return "date"; } else if (propValue instanceof RegExp) { return "regexp"; } } return propType; } function getPostfixForTypeWarning(value) { var type2 = getPreciseType(value); switch (type2) { case "array": case "object": return "an " + type2; case "boolean": case "date": case "regexp": return "a " + type2; default: return type2; } } function getClassName(propValue) { if (!propValue.constructor || !propValue.constructor.name) { return ANONYMOUS; } return propValue.constructor.name; } ReactPropTypes.checkPropTypes = checkPropTypes; ReactPropTypes.resetWarningCache = checkPropTypes.resetWarningCache; ReactPropTypes.PropTypes = ReactPropTypes; return ReactPropTypes; }; } }); // node_modules/prop-types/index.js var require_prop_types = __commonJS({ "node_modules/prop-types/index.js"(exports, module2) { if (true) { ReactIs2 = require_react_is(); throwOnDirectAccess = true; module2.exports = require_factoryWithTypeCheckers()(ReactIs2.isElement, throwOnDirectAccess); } else { module2.exports = null(); } var ReactIs2; var throwOnDirectAccess; } }); // node_modules/react-markdown/node_modules/react-is/cjs/react-is.development.js var require_react_is_development2 = __commonJS({ "node_modules/react-markdown/node_modules/react-is/cjs/react-is.development.js"(exports) { "use strict"; if (true) { (function() { "use strict"; var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_SERVER_CONTEXT_TYPE = Symbol.for("react.server_context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var enableScopeAPI = false; var enableCacheElement = false; var enableTransitionTracing = false; var enableLegacyHidden = false; var enableDebugTracing = false; var REACT_MODULE_REFERENCE; { REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); } function isValidElementType(type2) { if (typeof type2 === "string" || typeof type2 === "function") { return true; } if (type2 === REACT_FRAGMENT_TYPE || type2 === REACT_PROFILER_TYPE || enableDebugTracing || type2 === REACT_STRICT_MODE_TYPE || type2 === REACT_SUSPENSE_TYPE || type2 === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type2 === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { return true; } if (typeof type2 === "object" && type2 !== null) { if (type2.$$typeof === REACT_LAZY_TYPE || type2.$$typeof === REACT_MEMO_TYPE || type2.$$typeof === REACT_PROVIDER_TYPE || type2.$$typeof === REACT_CONTEXT_TYPE || type2.$$typeof === REACT_FORWARD_REF_TYPE || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. type2.$$typeof === REACT_MODULE_REFERENCE || type2.getModuleId !== void 0) { return true; } } return false; } function typeOf(object) { if (typeof object === "object" && object !== null) { var $$typeof = object.$$typeof; switch ($$typeof) { case REACT_ELEMENT_TYPE: var type2 = object.type; switch (type2) { case REACT_FRAGMENT_TYPE: case REACT_PROFILER_TYPE: case REACT_STRICT_MODE_TYPE: case REACT_SUSPENSE_TYPE: case REACT_SUSPENSE_LIST_TYPE: return type2; default: var $$typeofType = type2 && type2.$$typeof; switch ($$typeofType) { case REACT_SERVER_CONTEXT_TYPE: case REACT_CONTEXT_TYPE: case REACT_FORWARD_REF_TYPE: case REACT_LAZY_TYPE: case REACT_MEMO_TYPE: case REACT_PROVIDER_TYPE: return $$typeofType; default: return $$typeof; } } case REACT_PORTAL_TYPE: return $$typeof; } } return void 0; } var ContextConsumer = REACT_CONTEXT_TYPE; var ContextProvider = REACT_PROVIDER_TYPE; var Element = REACT_ELEMENT_TYPE; var ForwardRef = REACT_FORWARD_REF_TYPE; var Fragment = REACT_FRAGMENT_TYPE; var Lazy = REACT_LAZY_TYPE; var Memo = REACT_MEMO_TYPE; var Portal = REACT_PORTAL_TYPE; var Profiler = REACT_PROFILER_TYPE; var StrictMode2 = REACT_STRICT_MODE_TYPE; var Suspense = REACT_SUSPENSE_TYPE; var SuspenseList = REACT_SUSPENSE_LIST_TYPE; var hasWarnedAboutDeprecatedIsAsyncMode = false; var hasWarnedAboutDeprecatedIsConcurrentMode = false; function isAsyncMode(object) { { if (!hasWarnedAboutDeprecatedIsAsyncMode) { hasWarnedAboutDeprecatedIsAsyncMode = true; console["warn"]("The ReactIs.isAsyncMode() alias has been deprecated, and will be removed in React 18+."); } } return false; } function isConcurrentMode(object) { { if (!hasWarnedAboutDeprecatedIsConcurrentMode) { hasWarnedAboutDeprecatedIsConcurrentMode = true; console["warn"]("The ReactIs.isConcurrentMode() alias has been deprecated, and will be removed in React 18+."); } } return false; } function isContextConsumer(object) { return typeOf(object) === REACT_CONTEXT_TYPE; } function isContextProvider(object) { return typeOf(object) === REACT_PROVIDER_TYPE; } function isElement(object) { return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; } function isForwardRef(object) { return typeOf(object) === REACT_FORWARD_REF_TYPE; } function isFragment(object) { return typeOf(object) === REACT_FRAGMENT_TYPE; } function isLazy(object) { return typeOf(object) === REACT_LAZY_TYPE; } function isMemo(object) { return typeOf(object) === REACT_MEMO_TYPE; } function isPortal(object) { return typeOf(object) === REACT_PORTAL_TYPE; } function isProfiler(object) { return typeOf(object) === REACT_PROFILER_TYPE; } function isStrictMode(object) { return typeOf(object) === REACT_STRICT_MODE_TYPE; } function isSuspense(object) { return typeOf(object) === REACT_SUSPENSE_TYPE; } function isSuspenseList(object) { return typeOf(object) === REACT_SUSPENSE_LIST_TYPE; } exports.ContextConsumer = ContextConsumer; exports.ContextProvider = ContextProvider; exports.Element = Element; exports.ForwardRef = ForwardRef; exports.Fragment = Fragment; exports.Lazy = Lazy; exports.Memo = Memo; exports.Portal = Portal; exports.Profiler = Profiler; exports.StrictMode = StrictMode2; exports.Suspense = Suspense; exports.SuspenseList = SuspenseList; exports.isAsyncMode = isAsyncMode; exports.isConcurrentMode = isConcurrentMode; exports.isContextConsumer = isContextConsumer; exports.isContextProvider = isContextProvider; exports.isElement = isElement; exports.isForwardRef = isForwardRef; exports.isFragment = isFragment; exports.isLazy = isLazy; exports.isMemo = isMemo; exports.isPortal = isPortal; exports.isProfiler = isProfiler; exports.isStrictMode = isStrictMode; exports.isSuspense = isSuspense; exports.isSuspenseList = isSuspenseList; exports.isValidElementType = isValidElementType; exports.typeOf = typeOf; })(); } } }); // node_modules/react-markdown/node_modules/react-is/index.js var require_react_is2 = __commonJS({ "node_modules/react-markdown/node_modules/react-is/index.js"(exports, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_react_is_development2(); } } }); // node_modules/inline-style-parser/index.js var require_inline_style_parser = __commonJS({ "node_modules/inline-style-parser/index.js"(exports, module2) { var COMMENT_REGEX = /\/\*[^*]*\*+([^/*][^*]*\*+)*\//g; var NEWLINE_REGEX = /\n/g; var WHITESPACE_REGEX = /^\s*/; var PROPERTY_REGEX = /^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/; var COLON_REGEX = /^:\s*/; var VALUE_REGEX = /^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/; var SEMICOLON_REGEX = /^[;\s]*/; var TRIM_REGEX = /^\s+|\s+$/g; var NEWLINE = "\n"; var FORWARD_SLASH = "/"; var ASTERISK = "*"; var EMPTY_STRING = ""; var TYPE_COMMENT = "comment"; var TYPE_DECLARATION = "declaration"; module2.exports = function(style, options) { if (typeof style !== "string") { throw new TypeError("First argument must be a string"); } if (!style) return []; options = options || {}; var lineno = 1; var column = 1; function updatePosition(str2) { var lines = str2.match(NEWLINE_REGEX); if (lines) lineno += lines.length; var i = str2.lastIndexOf(NEWLINE); column = ~i ? str2.length - i : column + str2.length; } function position3() { var start = { line: lineno, column }; return function(node2) { node2.position = new Position(start); whitespace2(); return node2; }; } function Position(start) { this.start = start; this.end = { line: lineno, column }; this.source = options.source; } Position.prototype.content = style; var errorsList = []; function error(msg) { var err = new Error( options.source + ":" + lineno + ":" + column + ": " + msg ); err.reason = msg; err.filename = options.source; err.line = lineno; err.column = column; err.source = style; if (options.silent) { errorsList.push(err); } else { throw err; } } function match2(re) { var m = re.exec(style); if (!m) return; var str2 = m[0]; updatePosition(str2); style = style.slice(str2.length); return m; } function whitespace2() { match2(WHITESPACE_REGEX); } function comments(rules) { var c; rules = rules || []; while (c = comment()) { if (c !== false) { rules.push(c); } } return rules; } function comment() { var pos = position3(); if (FORWARD_SLASH != style.charAt(0) || ASTERISK != style.charAt(1)) return; var i = 2; while (EMPTY_STRING != style.charAt(i) && (ASTERISK != style.charAt(i) || FORWARD_SLASH != style.charAt(i + 1))) { ++i; } i += 2; if (EMPTY_STRING === style.charAt(i - 1)) { return error("End of comment missing"); } var str2 = style.slice(2, i - 2); column += 2; updatePosition(str2); style = style.slice(i); column += 2; return pos({ type: TYPE_COMMENT, comment: str2 }); } function declaration() { var pos = position3(); var prop = match2(PROPERTY_REGEX); if (!prop) return; comment(); if (!match2(COLON_REGEX)) return error("property missing ':'"); var val = match2(VALUE_REGEX); var ret = pos({ type: TYPE_DECLARATION, property: trim2(prop[0].replace(COMMENT_REGEX, EMPTY_STRING)), value: val ? trim2(val[0].replace(COMMENT_REGEX, EMPTY_STRING)) : EMPTY_STRING }); match2(SEMICOLON_REGEX); return ret; } function declarations() { var decls = []; comments(decls); var decl; while (decl = declaration()) { if (decl !== false) { decls.push(decl); comments(decls); } } return decls; } whitespace2(); return declarations(); }; function trim2(str2) { return str2 ? str2.replace(TRIM_REGEX, EMPTY_STRING) : EMPTY_STRING; } } }); // node_modules/style-to-object/index.js var require_style_to_object = __commonJS({ "node_modules/style-to-object/index.js"(exports, module2) { var parse2 = require_inline_style_parser(); function StyleToObject2(style, iterator) { var output = null; if (!style || typeof style !== "string") { return output; } var declaration; var declarations = parse2(style); var hasIterator = typeof iterator === "function"; var property; var value; for (var i = 0, len = declarations.length; i < len; i++) { declaration = declarations[i]; property = declaration.property; value = declaration.value; if (hasIterator) { iterator(property, value, declaration); } else if (value) { output || (output = {}); output[property] = value; } } return output; } module2.exports = StyleToObject2; module2.exports.default = StyleToObject2; } }); // node_modules/scheduler/cjs/scheduler.development.js var require_scheduler_development = __commonJS({ "node_modules/scheduler/cjs/scheduler.development.js"(exports) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var enableSchedulerDebugging = false; var enableProfiling = false; var frameYieldMs = 5; function push2(heap, node2) { var index2 = heap.length; heap.push(node2); siftUp(heap, node2, index2); } function peek(heap) { return heap.length === 0 ? null : heap[0]; } function pop2(heap) { if (heap.length === 0) { return null; } var first = heap[0]; var last = heap.pop(); if (last !== first) { heap[0] = last; siftDown(heap, last, 0); } return first; } function siftUp(heap, node2, i) { var index2 = i; while (index2 > 0) { var parentIndex = index2 - 1 >>> 1; var parent = heap[parentIndex]; if (compare2(parent, node2) > 0) { heap[parentIndex] = node2; heap[index2] = parent; index2 = parentIndex; } else { return; } } } function siftDown(heap, node2, i) { var index2 = i; var length = heap.length; var halfLength = length >>> 1; while (index2 < halfLength) { var leftIndex = (index2 + 1) * 2 - 1; var left = heap[leftIndex]; var rightIndex = leftIndex + 1; var right = heap[rightIndex]; if (compare2(left, node2) < 0) { if (rightIndex < length && compare2(right, left) < 0) { heap[index2] = right; heap[rightIndex] = node2; index2 = rightIndex; } else { heap[index2] = left; heap[leftIndex] = node2; index2 = leftIndex; } } else if (rightIndex < length && compare2(right, node2) < 0) { heap[index2] = right; heap[rightIndex] = node2; index2 = rightIndex; } else { return; } } } function compare2(a2, b) { var diff = a2.sortIndex - b.sortIndex; return diff !== 0 ? diff : a2.id - b.id; } var ImmediatePriority = 1; var UserBlockingPriority = 2; var NormalPriority = 3; var LowPriority = 4; var IdlePriority = 5; function markTaskErrored(task, ms) { } var hasPerformanceNow = typeof performance === "object" && typeof performance.now === "function"; if (hasPerformanceNow) { var localPerformance = performance; exports.unstable_now = function() { return localPerformance.now(); }; } else { var localDate = Date; var initialTime = localDate.now(); exports.unstable_now = function() { return localDate.now() - initialTime; }; } var maxSigned31BitInt = 1073741823; var IMMEDIATE_PRIORITY_TIMEOUT = -1; var USER_BLOCKING_PRIORITY_TIMEOUT = 250; var NORMAL_PRIORITY_TIMEOUT = 5e3; var LOW_PRIORITY_TIMEOUT = 1e4; var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; var taskQueue = []; var timerQueue = []; var taskIdCounter = 1; var currentTask = null; var currentPriorityLevel = NormalPriority; var isPerformingWork = false; var isHostCallbackScheduled = false; var isHostTimeoutScheduled = false; var localSetTimeout = typeof setTimeout === "function" ? setTimeout : null; var localClearTimeout = typeof clearTimeout === "function" ? clearTimeout : null; var localSetImmediate = typeof setImmediate !== "undefined" ? setImmediate : null; var isInputPending = typeof navigator !== "undefined" && navigator.scheduling !== void 0 && navigator.scheduling.isInputPending !== void 0 ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; function advanceTimers(currentTime) { var timer = peek(timerQueue); while (timer !== null) { if (timer.callback === null) { pop2(timerQueue); } else if (timer.startTime <= currentTime) { pop2(timerQueue); timer.sortIndex = timer.expirationTime; push2(taskQueue, timer); } else { return; } timer = peek(timerQueue); } } function handleTimeout(currentTime) { isHostTimeoutScheduled = false; advanceTimers(currentTime); if (!isHostCallbackScheduled) { if (peek(taskQueue) !== null) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } } } } function flushWork(hasTimeRemaining, initialTime2) { isHostCallbackScheduled = false; if (isHostTimeoutScheduled) { isHostTimeoutScheduled = false; cancelHostTimeout(); } isPerformingWork = true; var previousPriorityLevel = currentPriorityLevel; try { if (enableProfiling) { try { return workLoop(hasTimeRemaining, initialTime2); } catch (error) { if (currentTask !== null) { var currentTime = exports.unstable_now(); markTaskErrored(currentTask, currentTime); currentTask.isQueued = false; } throw error; } } else { return workLoop(hasTimeRemaining, initialTime2); } } finally { currentTask = null; currentPriorityLevel = previousPriorityLevel; isPerformingWork = false; } } function workLoop(hasTimeRemaining, initialTime2) { var currentTime = initialTime2; advanceTimers(currentTime); currentTask = peek(taskQueue); while (currentTask !== null && !enableSchedulerDebugging) { if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { break; } var callback = currentTask.callback; if (typeof callback === "function") { currentTask.callback = null; currentPriorityLevel = currentTask.priorityLevel; var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; var continuationCallback = callback(didUserCallbackTimeout); currentTime = exports.unstable_now(); if (typeof continuationCallback === "function") { currentTask.callback = continuationCallback; } else { if (currentTask === peek(taskQueue)) { pop2(taskQueue); } } advanceTimers(currentTime); } else { pop2(taskQueue); } currentTask = peek(taskQueue); } if (currentTask !== null) { return true; } else { var firstTimer = peek(timerQueue); if (firstTimer !== null) { requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); } return false; } } function unstable_runWithPriority(priorityLevel, eventHandler) { switch (priorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: case LowPriority: case IdlePriority: break; default: priorityLevel = NormalPriority; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_next(eventHandler) { var priorityLevel; switch (currentPriorityLevel) { case ImmediatePriority: case UserBlockingPriority: case NormalPriority: priorityLevel = NormalPriority; break; default: priorityLevel = currentPriorityLevel; break; } var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = priorityLevel; try { return eventHandler(); } finally { currentPriorityLevel = previousPriorityLevel; } } function unstable_wrapCallback(callback) { var parentPriorityLevel = currentPriorityLevel; return function() { var previousPriorityLevel = currentPriorityLevel; currentPriorityLevel = parentPriorityLevel; try { return callback.apply(this, arguments); } finally { currentPriorityLevel = previousPriorityLevel; } }; } function unstable_scheduleCallback(priorityLevel, callback, options) { var currentTime = exports.unstable_now(); var startTime2; if (typeof options === "object" && options !== null) { var delay = options.delay; if (typeof delay === "number" && delay > 0) { startTime2 = currentTime + delay; } else { startTime2 = currentTime; } } else { startTime2 = currentTime; } var timeout; switch (priorityLevel) { case ImmediatePriority: timeout = IMMEDIATE_PRIORITY_TIMEOUT; break; case UserBlockingPriority: timeout = USER_BLOCKING_PRIORITY_TIMEOUT; break; case IdlePriority: timeout = IDLE_PRIORITY_TIMEOUT; break; case LowPriority: timeout = LOW_PRIORITY_TIMEOUT; break; case NormalPriority: default: timeout = NORMAL_PRIORITY_TIMEOUT; break; } var expirationTime = startTime2 + timeout; var newTask = { id: taskIdCounter++, callback, priorityLevel, startTime: startTime2, expirationTime, sortIndex: -1 }; if (startTime2 > currentTime) { newTask.sortIndex = startTime2; push2(timerQueue, newTask); if (peek(taskQueue) === null && newTask === peek(timerQueue)) { if (isHostTimeoutScheduled) { cancelHostTimeout(); } else { isHostTimeoutScheduled = true; } requestHostTimeout(handleTimeout, startTime2 - currentTime); } } else { newTask.sortIndex = expirationTime; push2(taskQueue, newTask); if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } return newTask; } function unstable_pauseExecution() { } function unstable_continueExecution() { if (!isHostCallbackScheduled && !isPerformingWork) { isHostCallbackScheduled = true; requestHostCallback(flushWork); } } function unstable_getFirstCallbackNode() { return peek(taskQueue); } function unstable_cancelCallback(task) { task.callback = null; } function unstable_getCurrentPriorityLevel() { return currentPriorityLevel; } var isMessageLoopRunning = false; var scheduledHostCallback = null; var taskTimeoutID = -1; var frameInterval = frameYieldMs; var startTime = -1; function shouldYieldToHost() { var timeElapsed = exports.unstable_now() - startTime; if (timeElapsed < frameInterval) { return false; } return true; } function requestPaint() { } function forceFrameRate(fps) { if (fps < 0 || fps > 125) { console["error"]("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"); return; } if (fps > 0) { frameInterval = Math.floor(1e3 / fps); } else { frameInterval = frameYieldMs; } } var performWorkUntilDeadline = function() { if (scheduledHostCallback !== null) { var currentTime = exports.unstable_now(); startTime = currentTime; var hasTimeRemaining = true; var hasMoreWork = true; try { hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); } finally { if (hasMoreWork) { schedulePerformWorkUntilDeadline(); } else { isMessageLoopRunning = false; scheduledHostCallback = null; } } } else { isMessageLoopRunning = false; } }; var schedulePerformWorkUntilDeadline; if (typeof localSetImmediate === "function") { schedulePerformWorkUntilDeadline = function() { localSetImmediate(performWorkUntilDeadline); }; } else if (typeof MessageChannel !== "undefined") { var channel = new MessageChannel(); var port = channel.port2; channel.port1.onmessage = performWorkUntilDeadline; schedulePerformWorkUntilDeadline = function() { port.postMessage(null); }; } else { schedulePerformWorkUntilDeadline = function() { localSetTimeout(performWorkUntilDeadline, 0); }; } function requestHostCallback(callback) { scheduledHostCallback = callback; if (!isMessageLoopRunning) { isMessageLoopRunning = true; schedulePerformWorkUntilDeadline(); } } function requestHostTimeout(callback, ms) { taskTimeoutID = localSetTimeout(function() { callback(exports.unstable_now()); }, ms); } function cancelHostTimeout() { localClearTimeout(taskTimeoutID); taskTimeoutID = -1; } var unstable_requestPaint = requestPaint; var unstable_Profiling = null; exports.unstable_IdlePriority = IdlePriority; exports.unstable_ImmediatePriority = ImmediatePriority; exports.unstable_LowPriority = LowPriority; exports.unstable_NormalPriority = NormalPriority; exports.unstable_Profiling = unstable_Profiling; exports.unstable_UserBlockingPriority = UserBlockingPriority; exports.unstable_cancelCallback = unstable_cancelCallback; exports.unstable_continueExecution = unstable_continueExecution; exports.unstable_forceFrameRate = forceFrameRate; exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; exports.unstable_next = unstable_next; exports.unstable_pauseExecution = unstable_pauseExecution; exports.unstable_requestPaint = unstable_requestPaint; exports.unstable_runWithPriority = unstable_runWithPriority; exports.unstable_scheduleCallback = unstable_scheduleCallback; exports.unstable_shouldYield = shouldYieldToHost; exports.unstable_wrapCallback = unstable_wrapCallback; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); } })(); } } }); // node_modules/scheduler/index.js var require_scheduler = __commonJS({ "node_modules/scheduler/index.js"(exports, module2) { "use strict"; if (false) { module2.exports = null; } else { module2.exports = require_scheduler_development(); } } }); // node_modules/react-dom/cjs/react-dom.development.js var require_react_dom_development = __commonJS({ "node_modules/react-dom/cjs/react-dom.development.js"(exports) { "use strict"; if (true) { (function() { "use strict"; if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); } var React11 = require_react(); var Scheduler = require_scheduler(); var ReactSharedInternals = React11.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; var suppressWarning = false; function setSuppressWarning(newSuppressWarning) { { suppressWarning = newSuppressWarning; } } function warn(format) { { if (!suppressWarning) { for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } printWarning("warn", format, args); } } } function error(format) { { if (!suppressWarning) { for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } printWarning("error", format, args); } } } function printWarning(level, format, args) { { var ReactDebugCurrentFrame2 = ReactSharedInternals.ReactDebugCurrentFrame; var stack = ReactDebugCurrentFrame2.getStackAddendum(); if (stack !== "") { format += "%s"; args = args.concat([stack]); } var argsWithFormat = args.map(function(item) { return String(item); }); argsWithFormat.unshift("Warning: " + format); Function.prototype.apply.call(console[level], console, argsWithFormat); } } var FunctionComponent = 0; var ClassComponent = 1; var IndeterminateComponent = 2; var HostRoot = 3; var HostPortal = 4; var HostComponent = 5; var HostText = 6; var Fragment = 7; var Mode = 8; var ContextConsumer = 9; var ContextProvider = 10; var ForwardRef = 11; var Profiler = 12; var SuspenseComponent = 13; var MemoComponent = 14; var SimpleMemoComponent = 15; var LazyComponent = 16; var IncompleteClassComponent = 17; var DehydratedFragment = 18; var SuspenseListComponent = 19; var ScopeComponent = 21; var OffscreenComponent = 22; var LegacyHiddenComponent = 23; var CacheComponent = 24; var TracingMarkerComponent = 25; var enableClientRenderFallbackOnTextMismatch = true; var enableNewReconciler = false; var enableLazyContextPropagation = false; var enableLegacyHidden = false; var enableSuspenseAvoidThisFallback = false; var disableCommentsAsDOMContainers = true; var enableCustomElementPropertySupport = false; var warnAboutStringRefs = false; var enableSchedulingProfiler = true; var enableProfilerTimer = true; var enableProfilerCommitHooks = true; var allNativeEvents = /* @__PURE__ */ new Set(); var registrationNameDependencies = {}; var possibleRegistrationNames = {}; function registerTwoPhaseEvent(registrationName, dependencies) { registerDirectEvent(registrationName, dependencies); registerDirectEvent(registrationName + "Capture", dependencies); } function registerDirectEvent(registrationName, dependencies) { { if (registrationNameDependencies[registrationName]) { error("EventRegistry: More than one plugin attempted to publish the same registration name, `%s`.", registrationName); } } registrationNameDependencies[registrationName] = dependencies; { var lowerCasedName = registrationName.toLowerCase(); possibleRegistrationNames[lowerCasedName] = registrationName; if (registrationName === "onDoubleClick") { possibleRegistrationNames.ondblclick = registrationName; } } for (var i = 0; i < dependencies.length; i++) { allNativeEvents.add(dependencies[i]); } } var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); var hasOwnProperty3 = Object.prototype.hasOwnProperty; function typeName(value) { { var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; var type2 = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; return type2; } } function willCoercionThrow(value) { { try { testStringCoercion(value); return false; } catch (e) { return true; } } } function testStringCoercion(value) { return "" + value; } function checkAttributeStringCoercion(value, attributeName) { { if (willCoercionThrow(value)) { error("The provided `%s` attribute is an unsupported type %s. This value must be coerced to a string before before using it here.", attributeName, typeName(value)); return testStringCoercion(value); } } } function checkKeyStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function checkPropStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error("The provided `%s` prop is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); return testStringCoercion(value); } } } function checkCSSPropertyStringCoercion(value, propName) { { if (willCoercionThrow(value)) { error("The provided `%s` CSS property is an unsupported type %s. This value must be coerced to a string before before using it here.", propName, typeName(value)); return testStringCoercion(value); } } } function checkHtmlStringCoercion(value) { { if (willCoercionThrow(value)) { error("The provided HTML markup uses a value of unsupported type %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } function checkFormFieldValueStringCoercion(value) { { if (willCoercionThrow(value)) { error("Form field values (value, checked, defaultValue, or defaultChecked props) must be strings, not %s. This value must be coerced to a string before before using it here.", typeName(value)); return testStringCoercion(value); } } } var RESERVED = 0; var STRING = 1; var BOOLEANISH_STRING = 2; var BOOLEAN = 3; var OVERLOADED_BOOLEAN = 4; var NUMERIC = 5; var POSITIVE_NUMERIC = 6; var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); var illegalAttributeNameCache = {}; var validatedAttributeNameCache = {}; function isAttributeNameSafe(attributeName) { if (hasOwnProperty3.call(validatedAttributeNameCache, attributeName)) { return true; } if (hasOwnProperty3.call(illegalAttributeNameCache, attributeName)) { return false; } if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { validatedAttributeNameCache[attributeName] = true; return true; } illegalAttributeNameCache[attributeName] = true; { error("Invalid attribute name: `%s`", attributeName); } return false; } function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null) { return propertyInfo.type === RESERVED; } if (isCustomComponentTag) { return false; } if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { return true; } return false; } function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { if (propertyInfo !== null && propertyInfo.type === RESERVED) { return false; } switch (typeof value) { case "function": case "symbol": return true; case "boolean": { if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { return !propertyInfo.acceptsBooleans; } else { var prefix2 = name.toLowerCase().slice(0, 5); return prefix2 !== "data-" && prefix2 !== "aria-"; } } default: return false; } } function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { if (value === null || typeof value === "undefined") { return true; } if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { return true; } if (isCustomComponentTag) { return false; } if (propertyInfo !== null) { switch (propertyInfo.type) { case BOOLEAN: return !value; case OVERLOADED_BOOLEAN: return value === false; case NUMERIC: return isNaN(value); case POSITIVE_NUMERIC: return isNaN(value) || value < 1; } } return false; } function getPropertyInfo(name) { return properties.hasOwnProperty(name) ? properties[name] : null; } function PropertyInfoRecord(name, type2, mustUseProperty, attributeName, attributeNamespace, sanitizeURL2, removeEmptyString) { this.acceptsBooleans = type2 === BOOLEANISH_STRING || type2 === BOOLEAN || type2 === OVERLOADED_BOOLEAN; this.attributeName = attributeName; this.attributeNamespace = attributeNamespace; this.mustUseProperty = mustUseProperty; this.propertyName = name; this.type = type2; this.sanitizeURL = sanitizeURL2; this.removeEmptyString = removeEmptyString; } var properties = {}; var reservedProps = [ "children", "dangerouslySetInnerHTML", // TODO: This prevents the assignment of defaultValue to regular // elements (not just inputs). Now that ReactDOMInput assigns to the // defaultValue property -- do we need this? "defaultValue", "defaultChecked", "innerHTML", "suppressContentEditableWarning", "suppressHydrationWarning", "style" ]; reservedProps.forEach(function(name) { properties[name] = new PropertyInfoRecord( name, RESERVED, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function(_ref) { var name = _ref[0], attributeName = _ref[1]; properties[name] = new PropertyInfoRecord( name, STRING, false, // mustUseProperty attributeName, // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); ["contentEditable", "draggable", "spellCheck", "value"].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, BOOLEANISH_STRING, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, BOOLEANISH_STRING, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); [ "allowFullScreen", "async", // Note: there is a special case that prevents it from being written to the DOM // on the client side because the browsers are inconsistent. Instead we call focus(). "autoFocus", "autoPlay", "controls", "default", "defer", "disabled", "disablePictureInPicture", "disableRemotePlayback", "formNoValidate", "hidden", "loop", "noModule", "noValidate", "open", "playsInline", "readOnly", "required", "reversed", "scoped", "seamless", // Microdata "itemScope" ].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, BOOLEAN, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); [ "checked", // Note: `option.selected` is not updated if `select.multiple` is // disabled with `removeAttribute`. We have special logic for handling this. "multiple", "muted", "selected" // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, BOOLEAN, true, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); [ "capture", "download" // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, OVERLOADED_BOOLEAN, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); [ "cols", "rows", "size", "span" // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, POSITIVE_NUMERIC, false, // mustUseProperty name, // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); ["rowSpan", "start"].forEach(function(name) { properties[name] = new PropertyInfoRecord( name, NUMERIC, false, // mustUseProperty name.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); var CAMELIZE = /[\-\:]([a-z])/g; var capitalize = function(token) { return token[1].toUpperCase(); }; [ "accent-height", "alignment-baseline", "arabic-form", "baseline-shift", "cap-height", "clip-path", "clip-rule", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "dominant-baseline", "enable-background", "fill-opacity", "fill-rule", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "glyph-name", "glyph-orientation-horizontal", "glyph-orientation-vertical", "horiz-adv-x", "horiz-origin-x", "image-rendering", "letter-spacing", "lighting-color", "marker-end", "marker-mid", "marker-start", "overline-position", "overline-thickness", "paint-order", "panose-1", "pointer-events", "rendering-intent", "shape-rendering", "stop-color", "stop-opacity", "strikethrough-position", "strikethrough-thickness", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-anchor", "text-decoration", "text-rendering", "underline-position", "underline-thickness", "unicode-bidi", "unicode-range", "units-per-em", "v-alphabetic", "v-hanging", "v-ideographic", "v-mathematical", "vector-effect", "vert-adv-y", "vert-origin-x", "vert-origin-y", "word-spacing", "writing-mode", "xmlns:xlink", "x-height" // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function(attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord( name, STRING, false, // mustUseProperty attributeName, null, // attributeNamespace false, // sanitizeURL false ); }); [ "xlink:actuate", "xlink:arcrole", "xlink:role", "xlink:show", "xlink:title", "xlink:type" // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function(attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord( name, STRING, false, // mustUseProperty attributeName, "http://www.w3.org/1999/xlink", false, // sanitizeURL false ); }); [ "xml:base", "xml:lang", "xml:space" // NOTE: if you add a camelCased prop to this list, // you'll need to set attributeName to name.toLowerCase() // instead in the assignment below. ].forEach(function(attributeName) { var name = attributeName.replace(CAMELIZE, capitalize); properties[name] = new PropertyInfoRecord( name, STRING, false, // mustUseProperty attributeName, "http://www.w3.org/XML/1998/namespace", false, // sanitizeURL false ); }); ["tabIndex", "crossOrigin"].forEach(function(attributeName) { properties[attributeName] = new PropertyInfoRecord( attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace false, // sanitizeURL false ); }); var xlinkHref = "xlinkHref"; properties[xlinkHref] = new PropertyInfoRecord( "xlinkHref", STRING, false, // mustUseProperty "xlink:href", "http://www.w3.org/1999/xlink", true, // sanitizeURL false ); ["src", "href", "action", "formAction"].forEach(function(attributeName) { properties[attributeName] = new PropertyInfoRecord( attributeName, STRING, false, // mustUseProperty attributeName.toLowerCase(), // attributeName null, // attributeNamespace true, // sanitizeURL true ); }); var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; var didWarn = false; function sanitizeURL(url) { { if (!didWarn && isJavaScriptProtocol.test(url)) { didWarn = true; error("A future version of React will block javascript: URLs as a security precaution. Use event handlers instead if you can. If you need to generate unsafe HTML try using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); } } } function getValueForProperty(node2, name, expected, propertyInfo) { { if (propertyInfo.mustUseProperty) { var propertyName = propertyInfo.propertyName; return node2[propertyName]; } else { { checkAttributeStringCoercion(expected, name); } if (propertyInfo.sanitizeURL) { sanitizeURL("" + expected); } var attributeName = propertyInfo.attributeName; var stringValue = null; if (propertyInfo.type === OVERLOADED_BOOLEAN) { if (node2.hasAttribute(attributeName)) { var value = node2.getAttribute(attributeName); if (value === "") { return true; } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return value; } if (value === "" + expected) { return expected; } return value; } } else if (node2.hasAttribute(attributeName)) { if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return node2.getAttribute(attributeName); } if (propertyInfo.type === BOOLEAN) { return expected; } stringValue = node2.getAttribute(attributeName); } if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { return stringValue === null ? expected : stringValue; } else if (stringValue === "" + expected) { return expected; } else { return stringValue; } } } } function getValueForAttribute(node2, name, expected, isCustomComponentTag) { { if (!isAttributeNameSafe(name)) { return; } if (!node2.hasAttribute(name)) { return expected === void 0 ? void 0 : null; } var value = node2.getAttribute(name); { checkAttributeStringCoercion(expected, name); } if (value === "" + expected) { return expected; } return value; } } function setValueForProperty(node2, name, value, isCustomComponentTag) { var propertyInfo = getPropertyInfo(name); if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { return; } if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { value = null; } if (isCustomComponentTag || propertyInfo === null) { if (isAttributeNameSafe(name)) { var _attributeName = name; if (value === null) { node2.removeAttribute(_attributeName); } else { { checkAttributeStringCoercion(value, name); } node2.setAttribute(_attributeName, "" + value); } } return; } var mustUseProperty = propertyInfo.mustUseProperty; if (mustUseProperty) { var propertyName = propertyInfo.propertyName; if (value === null) { var type2 = propertyInfo.type; node2[propertyName] = type2 === BOOLEAN ? false : ""; } else { node2[propertyName] = value; } return; } var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; if (value === null) { node2.removeAttribute(attributeName); } else { var _type = propertyInfo.type; var attributeValue; if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { attributeValue = ""; } else { { { checkAttributeStringCoercion(value, attributeName); } attributeValue = "" + value; } if (propertyInfo.sanitizeURL) { sanitizeURL(attributeValue.toString()); } } if (attributeNamespace) { node2.setAttributeNS(attributeNamespace, attributeName, attributeValue); } else { node2.setAttribute(attributeName, attributeValue); } } } var REACT_ELEMENT_TYPE = Symbol.for("react.element"); var REACT_PORTAL_TYPE = Symbol.for("react.portal"); var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); var REACT_CONTEXT_TYPE = Symbol.for("react.context"); var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); var REACT_MEMO_TYPE = Symbol.for("react.memo"); var REACT_LAZY_TYPE = Symbol.for("react.lazy"); var REACT_SCOPE_TYPE = Symbol.for("react.scope"); var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); var REACT_CACHE_TYPE = Symbol.for("react.cache"); var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; var FAUX_ITERATOR_SYMBOL = "@@iterator"; function getIteratorFn(maybeIterable) { if (maybeIterable === null || typeof maybeIterable !== "object") { return null; } var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; if (typeof maybeIterator === "function") { return maybeIterator; } return null; } var assign2 = Object.assign; var disabledDepth = 0; var prevLog; var prevInfo; var prevWarn; var prevError; var prevGroup; var prevGroupCollapsed; var prevGroupEnd; function disabledLog() { } disabledLog.__reactDisabledLog = true; function disableLogs() { { if (disabledDepth === 0) { prevLog = console.log; prevInfo = console.info; prevWarn = console.warn; prevError = console.error; prevGroup = console.group; prevGroupCollapsed = console.groupCollapsed; prevGroupEnd = console.groupEnd; var props = { configurable: true, enumerable: true, value: disabledLog, writable: true }; Object.defineProperties(console, { info: props, log: props, warn: props, error: props, group: props, groupCollapsed: props, groupEnd: props }); } disabledDepth++; } } function reenableLogs() { { disabledDepth--; if (disabledDepth === 0) { var props = { configurable: true, enumerable: true, writable: true }; Object.defineProperties(console, { log: assign2({}, props, { value: prevLog }), info: assign2({}, props, { value: prevInfo }), warn: assign2({}, props, { value: prevWarn }), error: assign2({}, props, { value: prevError }), group: assign2({}, props, { value: prevGroup }), groupCollapsed: assign2({}, props, { value: prevGroupCollapsed }), groupEnd: assign2({}, props, { value: prevGroupEnd }) }); } if (disabledDepth < 0) { error("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } } var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; var prefix; function describeBuiltInComponentFrame(name, source, ownerFn) { { if (prefix === void 0) { try { throw Error(); } catch (x) { var match2 = x.stack.trim().match(/\n( *(at )?)/); prefix = match2 && match2[1] || ""; } } return "\n" + prefix + name; } } var reentry = false; var componentFrameCache; { var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; componentFrameCache = new PossiblyWeakMap(); } function describeNativeComponentFrame(fn, construct) { if (!fn || reentry) { return ""; } { var frame = componentFrameCache.get(fn); if (frame !== void 0) { return frame; } } var control; reentry = true; var previousPrepareStackTrace = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var previousDispatcher; { previousDispatcher = ReactCurrentDispatcher.current; ReactCurrentDispatcher.current = null; disableLogs(); } try { if (construct) { var Fake = function() { throw Error(); }; Object.defineProperty(Fake.prototype, "props", { set: function() { throw Error(); } }); if (typeof Reflect === "object" && Reflect.construct) { try { Reflect.construct(Fake, []); } catch (x) { control = x; } Reflect.construct(fn, [], Fake); } else { try { Fake.call(); } catch (x) { control = x; } fn.call(Fake.prototype); } } else { try { throw Error(); } catch (x) { control = x; } fn(); } } catch (sample) { if (sample && control && typeof sample.stack === "string") { var sampleLines = sample.stack.split("\n"); var controlLines = control.stack.split("\n"); var s = sampleLines.length - 1; var c = controlLines.length - 1; while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { c--; } for (; s >= 1 && c >= 0; s--, c--) { if (sampleLines[s] !== controlLines[c]) { if (s !== 1 || c !== 1) { do { s--; c--; if (c < 0 || sampleLines[s] !== controlLines[c]) { var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); if (fn.displayName && _frame.includes("")) { _frame = _frame.replace("", fn.displayName); } { if (typeof fn === "function") { componentFrameCache.set(fn, _frame); } } return _frame; } } while (s >= 1 && c >= 0); } break; } } } } finally { reentry = false; { ReactCurrentDispatcher.current = previousDispatcher; reenableLogs(); } Error.prepareStackTrace = previousPrepareStackTrace; } var name = fn ? fn.displayName || fn.name : ""; var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; { if (typeof fn === "function") { componentFrameCache.set(fn, syntheticFrame); } } return syntheticFrame; } function describeClassComponentFrame(ctor, source, ownerFn) { { return describeNativeComponentFrame(ctor, true); } } function describeFunctionComponentFrame(fn, source, ownerFn) { { return describeNativeComponentFrame(fn, false); } } function shouldConstruct(Component) { var prototype3 = Component.prototype; return !!(prototype3 && prototype3.isReactComponent); } function describeUnknownElementTypeFrameInDEV(type2, source, ownerFn) { if (type2 == null) { return ""; } if (typeof type2 === "function") { { return describeNativeComponentFrame(type2, shouldConstruct(type2)); } } if (typeof type2 === "string") { return describeBuiltInComponentFrame(type2); } switch (type2) { case REACT_SUSPENSE_TYPE: return describeBuiltInComponentFrame("Suspense"); case REACT_SUSPENSE_LIST_TYPE: return describeBuiltInComponentFrame("SuspenseList"); } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_FORWARD_REF_TYPE: return describeFunctionComponentFrame(type2.render); case REACT_MEMO_TYPE: return describeUnknownElementTypeFrameInDEV(type2.type, source, ownerFn); case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return describeUnknownElementTypeFrameInDEV(init2(payload), source, ownerFn); } catch (x) { } } } } return ""; } function describeFiber(fiber) { var owner = fiber._debugOwner ? fiber._debugOwner.type : null; var source = fiber._debugSource; switch (fiber.tag) { case HostComponent: return describeBuiltInComponentFrame(fiber.type); case LazyComponent: return describeBuiltInComponentFrame("Lazy"); case SuspenseComponent: return describeBuiltInComponentFrame("Suspense"); case SuspenseListComponent: return describeBuiltInComponentFrame("SuspenseList"); case FunctionComponent: case IndeterminateComponent: case SimpleMemoComponent: return describeFunctionComponentFrame(fiber.type); case ForwardRef: return describeFunctionComponentFrame(fiber.type.render); case ClassComponent: return describeClassComponentFrame(fiber.type); default: return ""; } } function getStackByFiberInDevAndProd(workInProgress2) { try { var info = ""; var node2 = workInProgress2; do { info += describeFiber(node2); node2 = node2.return; } while (node2); return info; } catch (x) { return "\nError generating stack: " + x.message + "\n" + x.stack; } } function getWrappedName(outerType, innerType, wrapperName) { var displayName = outerType.displayName; if (displayName) { return displayName; } var functionName = innerType.displayName || innerType.name || ""; return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; } function getContextName(type2) { return type2.displayName || "Context"; } function getComponentNameFromType(type2) { if (type2 == null) { return null; } { if (typeof type2.tag === "number") { error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."); } } if (typeof type2 === "function") { return type2.displayName || type2.name || null; } if (typeof type2 === "string") { return type2; } switch (type2) { case REACT_FRAGMENT_TYPE: return "Fragment"; case REACT_PORTAL_TYPE: return "Portal"; case REACT_PROFILER_TYPE: return "Profiler"; case REACT_STRICT_MODE_TYPE: return "StrictMode"; case REACT_SUSPENSE_TYPE: return "Suspense"; case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList"; } if (typeof type2 === "object") { switch (type2.$$typeof) { case REACT_CONTEXT_TYPE: var context = type2; return getContextName(context) + ".Consumer"; case REACT_PROVIDER_TYPE: var provider = type2; return getContextName(provider._context) + ".Provider"; case REACT_FORWARD_REF_TYPE: return getWrappedName(type2, type2.render, "ForwardRef"); case REACT_MEMO_TYPE: var outerName = type2.displayName || null; if (outerName !== null) { return outerName; } return getComponentNameFromType(type2.type) || "Memo"; case REACT_LAZY_TYPE: { var lazyComponent = type2; var payload = lazyComponent._payload; var init2 = lazyComponent._init; try { return getComponentNameFromType(init2(payload)); } catch (x) { return null; } } } } return null; } function getWrappedName$1(outerType, innerType, wrapperName) { var functionName = innerType.displayName || innerType.name || ""; return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); } function getContextName$1(type2) { return type2.displayName || "Context"; } function getComponentNameFromFiber(fiber) { var tag = fiber.tag, type2 = fiber.type; switch (tag) { case CacheComponent: return "Cache"; case ContextConsumer: var context = type2; return getContextName$1(context) + ".Consumer"; case ContextProvider: var provider = type2; return getContextName$1(provider._context) + ".Provider"; case DehydratedFragment: return "DehydratedFragment"; case ForwardRef: return getWrappedName$1(type2, type2.render, "ForwardRef"); case Fragment: return "Fragment"; case HostComponent: return type2; case HostPortal: return "Portal"; case HostRoot: return "Root"; case HostText: return "Text"; case LazyComponent: return getComponentNameFromType(type2); case Mode: if (type2 === REACT_STRICT_MODE_TYPE) { return "StrictMode"; } return "Mode"; case OffscreenComponent: return "Offscreen"; case Profiler: return "Profiler"; case ScopeComponent: return "Scope"; case SuspenseComponent: return "Suspense"; case SuspenseListComponent: return "SuspenseList"; case TracingMarkerComponent: return "TracingMarker"; case ClassComponent: case FunctionComponent: case IncompleteClassComponent: case IndeterminateComponent: case MemoComponent: case SimpleMemoComponent: if (typeof type2 === "function") { return type2.displayName || type2.name || null; } if (typeof type2 === "string") { return type2; } break; } return null; } var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; var current = null; var isRendering = false; function getCurrentFiberOwnerNameInDevOrNull() { { if (current === null) { return null; } var owner = current._debugOwner; if (owner !== null && typeof owner !== "undefined") { return getComponentNameFromFiber(owner); } } return null; } function getCurrentFiberStackInDev() { { if (current === null) { return ""; } return getStackByFiberInDevAndProd(current); } } function resetCurrentFiber() { { ReactDebugCurrentFrame.getCurrentStack = null; current = null; isRendering = false; } } function setCurrentFiber(fiber) { { ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; current = fiber; isRendering = false; } } function getCurrentFiber() { { return current; } } function setIsRendering(rendering) { { isRendering = rendering; } } function toString7(value) { return "" + value; } function getToStringValue(value) { switch (typeof value) { case "boolean": case "number": case "string": case "undefined": return value; case "object": { checkFormFieldValueStringCoercion(value); } return value; default: return ""; } } var hasReadOnlyValue = { button: true, checkbox: true, image: true, hidden: true, radio: true, reset: true, submit: true }; function checkControlledValueProps(tagName, props) { { if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { error("You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`."); } if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { error("You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`."); } } } function isCheckable(elem) { var type2 = elem.type; var nodeName = elem.nodeName; return nodeName && nodeName.toLowerCase() === "input" && (type2 === "checkbox" || type2 === "radio"); } function getTracker(node2) { return node2._valueTracker; } function detachTracker(node2) { node2._valueTracker = null; } function getValueFromNode(node2) { var value = ""; if (!node2) { return value; } if (isCheckable(node2)) { value = node2.checked ? "true" : "false"; } else { value = node2.value; } return value; } function trackValueOnNode(node2) { var valueField = isCheckable(node2) ? "checked" : "value"; var descriptor = Object.getOwnPropertyDescriptor(node2.constructor.prototype, valueField); { checkFormFieldValueStringCoercion(node2[valueField]); } var currentValue = "" + node2[valueField]; if (node2.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { return; } var get2 = descriptor.get, set3 = descriptor.set; Object.defineProperty(node2, valueField, { configurable: true, get: function() { return get2.call(this); }, set: function(value) { { checkFormFieldValueStringCoercion(value); } currentValue = "" + value; set3.call(this, value); } }); Object.defineProperty(node2, valueField, { enumerable: descriptor.enumerable }); var tracker = { getValue: function() { return currentValue; }, setValue: function(value) { { checkFormFieldValueStringCoercion(value); } currentValue = "" + value; }, stopTracking: function() { detachTracker(node2); delete node2[valueField]; } }; return tracker; } function track(node2) { if (getTracker(node2)) { return; } node2._valueTracker = trackValueOnNode(node2); } function updateValueIfChanged(node2) { if (!node2) { return false; } var tracker = getTracker(node2); if (!tracker) { return true; } var lastValue = tracker.getValue(); var nextValue = getValueFromNode(node2); if (nextValue !== lastValue) { tracker.setValue(nextValue); return true; } return false; } function getActiveElement(doc) { doc = doc || (typeof document !== "undefined" ? document : void 0); if (typeof doc === "undefined") { return null; } try { return doc.activeElement || doc.body; } catch (e) { return doc.body; } } var didWarnValueDefaultValue = false; var didWarnCheckedDefaultChecked = false; var didWarnControlledToUncontrolled = false; var didWarnUncontrolledToControlled = false; function isControlled(props) { var usesChecked = props.type === "checkbox" || props.type === "radio"; return usesChecked ? props.checked != null : props.value != null; } function getHostProps(element2, props) { var node2 = element2; var checked = props.checked; var hostProps = assign2({}, props, { defaultChecked: void 0, defaultValue: void 0, value: void 0, checked: checked != null ? checked : node2._wrapperState.initialChecked }); return hostProps; } function initWrapperState(element2, props) { { checkControlledValueProps("input", props); if (props.checked !== void 0 && props.defaultChecked !== void 0 && !didWarnCheckedDefaultChecked) { error("%s contains an input of type %s with both checked and defaultChecked props. Input elements must be either controlled or uncontrolled (specify either the checked prop, or the defaultChecked prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); didWarnCheckedDefaultChecked = true; } if (props.value !== void 0 && props.defaultValue !== void 0 && !didWarnValueDefaultValue) { error("%s contains an input of type %s with both value and defaultValue props. Input elements must be either controlled or uncontrolled (specify either the value prop, or the defaultValue prop, but not both). Decide between using a controlled or uncontrolled input element and remove one of these props. More info: https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); didWarnValueDefaultValue = true; } } var node2 = element2; var defaultValue = props.defaultValue == null ? "" : props.defaultValue; node2._wrapperState = { initialChecked: props.checked != null ? props.checked : props.defaultChecked, initialValue: getToStringValue(props.value != null ? props.value : defaultValue), controlled: isControlled(props) }; } function updateChecked(element2, props) { var node2 = element2; var checked = props.checked; if (checked != null) { setValueForProperty(node2, "checked", checked, false); } } function updateWrapper(element2, props) { var node2 = element2; { var controlled = isControlled(props); if (!node2._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { error("A component is changing an uncontrolled input to be controlled. This is likely caused by the value changing from undefined to a defined value, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); didWarnUncontrolledToControlled = true; } if (node2._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { error("A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); didWarnControlledToUncontrolled = true; } } updateChecked(element2, props); var value = getToStringValue(props.value); var type2 = props.type; if (value != null) { if (type2 === "number") { if (value === 0 && node2.value === "" || // We explicitly want to coerce to number here if possible. // eslint-disable-next-line node2.value != value) { node2.value = toString7(value); } } else if (node2.value !== toString7(value)) { node2.value = toString7(value); } } else if (type2 === "submit" || type2 === "reset") { node2.removeAttribute("value"); return; } { if (props.hasOwnProperty("value")) { setDefaultValue(node2, props.type, value); } else if (props.hasOwnProperty("defaultValue")) { setDefaultValue(node2, props.type, getToStringValue(props.defaultValue)); } } { if (props.checked == null && props.defaultChecked != null) { node2.defaultChecked = !!props.defaultChecked; } } } function postMountWrapper(element2, props, isHydrating2) { var node2 = element2; if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { var type2 = props.type; var isButton = type2 === "submit" || type2 === "reset"; if (isButton && (props.value === void 0 || props.value === null)) { return; } var initialValue = toString7(node2._wrapperState.initialValue); if (!isHydrating2) { { if (initialValue !== node2.value) { node2.value = initialValue; } } } { node2.defaultValue = initialValue; } } var name = node2.name; if (name !== "") { node2.name = ""; } { node2.defaultChecked = !node2.defaultChecked; node2.defaultChecked = !!node2._wrapperState.initialChecked; } if (name !== "") { node2.name = name; } } function restoreControlledState(element2, props) { var node2 = element2; updateWrapper(node2, props); updateNamedCousins(node2, props); } function updateNamedCousins(rootNode, props) { var name = props.name; if (props.type === "radio" && name != null) { var queryRoot = rootNode; while (queryRoot.parentNode) { queryRoot = queryRoot.parentNode; } { checkAttributeStringCoercion(name, "name"); } var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + '][type="radio"]'); for (var i = 0; i < group.length; i++) { var otherNode = group[i]; if (otherNode === rootNode || otherNode.form !== rootNode.form) { continue; } var otherProps = getFiberCurrentPropsFromNode(otherNode); if (!otherProps) { throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the same `name` is not supported."); } updateValueIfChanged(otherNode); updateWrapper(otherNode, otherProps); } } } function setDefaultValue(node2, type2, value) { if ( // Focused number inputs synchronize on blur. See ChangeEventPlugin.js type2 !== "number" || getActiveElement(node2.ownerDocument) !== node2 ) { if (value == null) { node2.defaultValue = toString7(node2._wrapperState.initialValue); } else if (node2.defaultValue !== toString7(value)) { node2.defaultValue = toString7(value); } } } var didWarnSelectedSetOnOption = false; var didWarnInvalidChild = false; var didWarnInvalidInnerHTML = false; function validateProps(element2, props) { { if (props.value == null) { if (typeof props.children === "object" && props.children !== null) { React11.Children.forEach(props.children, function(child) { if (child == null) { return; } if (typeof child === "string" || typeof child === "number") { return; } if (!didWarnInvalidChild) { didWarnInvalidChild = true; error("Cannot infer the option value of complex children. Pass a `value` prop or use a plain string as children to