/* 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 __commonJS = (cb, mod) => function __require() { return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; }; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[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); // node_modules/handlebars/dist/cjs/handlebars/utils.js var require_utils = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/utils.js"(exports) { "use strict"; exports.__esModule = true; exports.extend = extend; exports.indexOf = indexOf; exports.escapeExpression = escapeExpression; exports.isEmpty = isEmpty; exports.createFrame = createFrame; exports.blockParams = blockParams; exports.appendContextPath = appendContextPath; var escape = { "&": "&", "<": "<", ">": ">", '"': """, "'": "'", "`": "`", "=": "=" }; var badChars = /[&<>"'`=]/g; var possible = /[&<>"'`=]/; function escapeChar(chr) { return escape[chr]; } function extend(obj) { for (var i = 1; i < arguments.length; i++) { for (var key in arguments[i]) { if (Object.prototype.hasOwnProperty.call(arguments[i], key)) { obj[key] = arguments[i][key]; } } } return obj; } var toString = Object.prototype.toString; exports.toString = toString; var isFunction = function isFunction2(value) { return typeof value === "function"; }; if (isFunction(/x/)) { exports.isFunction = isFunction = function(value) { return typeof value === "function" && toString.call(value) === "[object Function]"; }; } exports.isFunction = isFunction; var isArray = Array.isArray || function(value) { return value && typeof value === "object" ? toString.call(value) === "[object Array]" : false; }; exports.isArray = isArray; function indexOf(array, value) { for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } return -1; } function escapeExpression(string2) { if (typeof string2 !== "string") { if (string2 && string2.toHTML) { return string2.toHTML(); } else if (string2 == null) { return ""; } else if (!string2) { return string2 + ""; } string2 = "" + string2; } if (!possible.test(string2)) { return string2; } return string2.replace(badChars, escapeChar); } function isEmpty(value) { if (!value && value !== 0) { return true; } else if (isArray(value) && value.length === 0) { return true; } else { return false; } } function createFrame(object2) { var frame = extend({}, object2); frame._parent = object2; return frame; } function blockParams(params, ids) { params.path = ids; return params; } function appendContextPath(contextPath, id) { return (contextPath ? contextPath + "." : "") + id; } } }); // node_modules/handlebars/dist/cjs/handlebars/exception.js var require_exception = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/exception.js"(exports, module2) { "use strict"; exports.__esModule = true; var errorProps = ["description", "fileName", "lineNumber", "endLineNumber", "message", "name", "number", "stack"]; function Exception(message2, node) { var loc = node && node.loc, line = void 0, endLineNumber = void 0, column = void 0, endColumn = void 0; if (loc) { line = loc.start.line; endLineNumber = loc.end.line; column = loc.start.column; endColumn = loc.end.column; message2 += " - " + line + ":" + column; } var tmp = Error.prototype.constructor.call(this, message2); for (var idx = 0; idx < errorProps.length; idx++) { this[errorProps[idx]] = tmp[errorProps[idx]]; } if (Error.captureStackTrace) { Error.captureStackTrace(this, Exception); } try { if (loc) { this.lineNumber = line; this.endLineNumber = endLineNumber; if (Object.defineProperty) { Object.defineProperty(this, "column", { value: column, enumerable: true }); Object.defineProperty(this, "endColumn", { value: endColumn, enumerable: true }); } else { this.column = column; this.endColumn = endColumn; } } } catch (nop) { } } Exception.prototype = new Error(); exports["default"] = Exception; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js var require_block_helper_missing = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/block-helper-missing.js"(exports, module2) { "use strict"; exports.__esModule = true; var _utils = require_utils(); exports["default"] = function(instance) { instance.registerHelper("blockHelperMissing", function(context, options) { var inverse = options.inverse, fn = options.fn; if (context === true) { return fn(this); } else if (context === false || context == null) { return inverse(this); } else if (_utils.isArray(context)) { if (context.length > 0) { if (options.ids) { options.ids = [options.name]; } return instance.helpers.each(context, options); } else { return inverse(this); } } else { if (options.data && options.ids) { var data = _utils.createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name); options = { data }; } return fn(context, options); } }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/each.js var require_each = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/each.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports["default"] = function(instance) { instance.registerHelper("each", function(context, options) { if (!options) { throw new _exception2["default"]("Must pass iterator to #each"); } var fn = options.fn, inverse = options.inverse, i = 0, ret = "", data = void 0, contextPath = void 0; if (options.data && options.ids) { contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + "."; } if (_utils.isFunction(context)) { context = context.call(this); } if (options.data) { data = _utils.createFrame(options.data); } function execIteration(field, index, last) { if (data) { data.key = field; data.index = index; data.first = index === 0; data.last = !!last; if (contextPath) { data.contextPath = contextPath + field; } } ret = ret + fn(context[field], { data, blockParams: _utils.blockParams([context[field], field], [contextPath + field, null]) }); } if (context && typeof context === "object") { if (_utils.isArray(context)) { for (var j = context.length; i < j; i++) { if (i in context) { execIteration(i, i, i === context.length - 1); } } } else if (typeof Symbol === "function" && context[Symbol.iterator]) { var newContext = []; var iterator = context[Symbol.iterator](); for (var it = iterator.next(); !it.done; it = iterator.next()) { newContext.push(it.value); } context = newContext; for (var j = context.length; i < j; i++) { execIteration(i, i, i === context.length - 1); } } else { (function() { var priorKey = void 0; Object.keys(context).forEach(function(key) { if (priorKey !== void 0) { execIteration(priorKey, i - 1); } priorKey = key; i++; }); if (priorKey !== void 0) { execIteration(priorKey, i - 1, true); } })(); } } if (i === 0) { ret = inverse(this); } return ret; }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js var require_helper_missing = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/helper-missing.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports["default"] = function(instance) { instance.registerHelper("helperMissing", function() { if (arguments.length === 1) { return void 0; } else { throw new _exception2["default"]('Missing helper: "' + arguments[arguments.length - 1].name + '"'); } }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/if.js var require_if = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/if.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports["default"] = function(instance) { instance.registerHelper("if", function(conditional, options) { if (arguments.length != 2) { throw new _exception2["default"]("#if requires exactly one argument"); } if (_utils.isFunction(conditional)) { conditional = conditional.call(this); } if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); instance.registerHelper("unless", function(conditional, options) { if (arguments.length != 2) { throw new _exception2["default"]("#unless requires exactly one argument"); } return instance.helpers["if"].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/log.js var require_log = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/log.js"(exports, module2) { "use strict"; exports.__esModule = true; exports["default"] = function(instance) { instance.registerHelper("log", function() { var args = [void 0], options = arguments[arguments.length - 1]; for (var i = 0; i < arguments.length - 1; i++) { args.push(arguments[i]); } var level = 1; if (options.hash.level != null) { level = options.hash.level; } else if (options.data && options.data.level != null) { level = options.data.level; } args[0] = level; instance.log.apply(instance, args); }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/lookup.js var require_lookup = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/lookup.js"(exports, module2) { "use strict"; exports.__esModule = true; exports["default"] = function(instance) { instance.registerHelper("lookup", function(obj, field, options) { if (!obj) { return obj; } return options.lookupProperty(obj, field); }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers/with.js var require_with = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers/with.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); exports["default"] = function(instance) { instance.registerHelper("with", function(context, options) { if (arguments.length != 2) { throw new _exception2["default"]("#with requires exactly one argument"); } if (_utils.isFunction(context)) { context = context.call(this); } var fn = options.fn; if (!_utils.isEmpty(context)) { var data = options.data; if (options.data && options.ids) { data = _utils.createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]); } return fn(context, { data, blockParams: _utils.blockParams([context], [data && data.contextPath]) }); } else { return options.inverse(this); } }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/helpers.js var require_helpers = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/helpers.js"(exports) { "use strict"; exports.__esModule = true; exports.registerDefaultHelpers = registerDefaultHelpers; exports.moveHelperToHooks = moveHelperToHooks; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _helpersBlockHelperMissing = require_block_helper_missing(); var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing); var _helpersEach = require_each(); var _helpersEach2 = _interopRequireDefault(_helpersEach); var _helpersHelperMissing = require_helper_missing(); var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing); var _helpersIf = require_if(); var _helpersIf2 = _interopRequireDefault(_helpersIf); var _helpersLog = require_log(); var _helpersLog2 = _interopRequireDefault(_helpersLog); var _helpersLookup = require_lookup(); var _helpersLookup2 = _interopRequireDefault(_helpersLookup); var _helpersWith = require_with(); var _helpersWith2 = _interopRequireDefault(_helpersWith); function registerDefaultHelpers(instance) { _helpersBlockHelperMissing2["default"](instance); _helpersEach2["default"](instance); _helpersHelperMissing2["default"](instance); _helpersIf2["default"](instance); _helpersLog2["default"](instance); _helpersLookup2["default"](instance); _helpersWith2["default"](instance); } function moveHelperToHooks(instance, helperName, keepHelper) { if (instance.helpers[helperName]) { instance.hooks[helperName] = instance.helpers[helperName]; if (!keepHelper) { delete instance.helpers[helperName]; } } } } }); // node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js var require_inline = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/decorators/inline.js"(exports, module2) { "use strict"; exports.__esModule = true; var _utils = require_utils(); exports["default"] = function(instance) { instance.registerDecorator("inline", function(fn, props, container, options) { var ret = fn; if (!props.partials) { props.partials = {}; ret = function(context, options2) { var original = container.partials; container.partials = _utils.extend({}, original, props.partials); var ret2 = fn(context, options2); container.partials = original; return ret2; }; } props.partials[options.args[0]] = options.fn; return ret; }); }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/decorators.js var require_decorators = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/decorators.js"(exports) { "use strict"; exports.__esModule = true; exports.registerDefaultDecorators = registerDefaultDecorators; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _decoratorsInline = require_inline(); var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline); function registerDefaultDecorators(instance) { _decoratorsInline2["default"](instance); } } }); // node_modules/handlebars/dist/cjs/handlebars/logger.js var require_logger = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/logger.js"(exports, module2) { "use strict"; exports.__esModule = true; var _utils = require_utils(); var logger = { methodMap: ["debug", "info", "warn", "error"], level: "info", // Maps a given level value to the `methodMap` indexes above. lookupLevel: function lookupLevel(level) { if (typeof level === "string") { var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase()); if (levelMap >= 0) { level = levelMap; } else { level = parseInt(level, 10); } } return level; }, // Can be overridden in the host environment log: function log(level) { level = logger.lookupLevel(level); if (typeof console !== "undefined" && logger.lookupLevel(logger.level) <= level) { var method = logger.methodMap[level]; if (!console[method]) { method = "log"; } for (var _len = arguments.length, message2 = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { message2[_key - 1] = arguments[_key]; } console[method].apply(console, message2); } } }; exports["default"] = logger; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/internal/create-new-lookup-object.js var require_create_new_lookup_object = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/internal/create-new-lookup-object.js"(exports) { "use strict"; exports.__esModule = true; exports.createNewLookupObject = createNewLookupObject; var _utils = require_utils(); function createNewLookupObject() { for (var _len = arguments.length, sources = Array(_len), _key = 0; _key < _len; _key++) { sources[_key] = arguments[_key]; } return _utils.extend.apply(void 0, [/* @__PURE__ */ Object.create(null)].concat(sources)); } } }); // node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js var require_proto_access = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/internal/proto-access.js"(exports) { "use strict"; exports.__esModule = true; exports.createProtoAccessControl = createProtoAccessControl; exports.resultIsAllowed = resultIsAllowed; exports.resetLoggedProperties = resetLoggedProperties; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _createNewLookupObject = require_create_new_lookup_object(); var _logger = require_logger(); var _logger2 = _interopRequireDefault(_logger); var loggedProperties = /* @__PURE__ */ Object.create(null); function createProtoAccessControl(runtimeOptions) { var defaultMethodWhiteList = /* @__PURE__ */ Object.create(null); defaultMethodWhiteList["constructor"] = false; defaultMethodWhiteList["__defineGetter__"] = false; defaultMethodWhiteList["__defineSetter__"] = false; defaultMethodWhiteList["__lookupGetter__"] = false; var defaultPropertyWhiteList = /* @__PURE__ */ Object.create(null); defaultPropertyWhiteList["__proto__"] = false; return { properties: { whitelist: _createNewLookupObject.createNewLookupObject(defaultPropertyWhiteList, runtimeOptions.allowedProtoProperties), defaultValue: runtimeOptions.allowProtoPropertiesByDefault }, methods: { whitelist: _createNewLookupObject.createNewLookupObject(defaultMethodWhiteList, runtimeOptions.allowedProtoMethods), defaultValue: runtimeOptions.allowProtoMethodsByDefault } }; } function resultIsAllowed(result, protoAccessControl, propertyName) { if (typeof result === "function") { return checkWhiteList(protoAccessControl.methods, propertyName); } else { return checkWhiteList(protoAccessControl.properties, propertyName); } } function checkWhiteList(protoAccessControlForType, propertyName) { if (protoAccessControlForType.whitelist[propertyName] !== void 0) { return protoAccessControlForType.whitelist[propertyName] === true; } if (protoAccessControlForType.defaultValue !== void 0) { return protoAccessControlForType.defaultValue; } logUnexpecedPropertyAccessOnce(propertyName); return false; } function logUnexpecedPropertyAccessOnce(propertyName) { if (loggedProperties[propertyName] !== true) { loggedProperties[propertyName] = true; _logger2["default"].log("error", 'Handlebars: Access has been denied to resolve the property "' + propertyName + '" because it is not an "own property" of its parent.\nYou can add a runtime option to disable the check or this warning:\nSee https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details'); } } function resetLoggedProperties() { Object.keys(loggedProperties).forEach(function(propertyName) { delete loggedProperties[propertyName]; }); } } }); // node_modules/handlebars/dist/cjs/handlebars/base.js var require_base = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/base.js"(exports) { "use strict"; exports.__esModule = true; exports.HandlebarsEnvironment = HandlebarsEnvironment; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _utils = require_utils(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _helpers = require_helpers(); var _decorators = require_decorators(); var _logger = require_logger(); var _logger2 = _interopRequireDefault(_logger); var _internalProtoAccess = require_proto_access(); var VERSION2 = "4.7.8"; exports.VERSION = VERSION2; var COMPILER_REVISION = 8; exports.COMPILER_REVISION = COMPILER_REVISION; var LAST_COMPATIBLE_COMPILER_REVISION = 7; exports.LAST_COMPATIBLE_COMPILER_REVISION = LAST_COMPATIBLE_COMPILER_REVISION; var REVISION_CHANGES = { 1: "<= 1.0.rc.2", // 1.0.rc.2 is actually rev2 but doesn't report it 2: "== 1.0.0-rc.3", 3: "== 1.0.0-rc.4", 4: "== 1.x.x", 5: "== 2.0.0-alpha.x", 6: ">= 2.0.0-beta.1", 7: ">= 4.0.0 <4.3.0", 8: ">= 4.3.0" }; exports.REVISION_CHANGES = REVISION_CHANGES; var objectType = "[object Object]"; function HandlebarsEnvironment(helpers, partials, decorators) { this.helpers = helpers || {}; this.partials = partials || {}; this.decorators = decorators || {}; _helpers.registerDefaultHelpers(this); _decorators.registerDefaultDecorators(this); } HandlebarsEnvironment.prototype = { constructor: HandlebarsEnvironment, logger: _logger2["default"], log: _logger2["default"].log, registerHelper: function registerHelper(name, fn) { if (_utils.toString.call(name) === objectType) { if (fn) { throw new _exception2["default"]("Arg not supported with multiple helpers"); } _utils.extend(this.helpers, name); } else { this.helpers[name] = fn; } }, unregisterHelper: function unregisterHelper(name) { delete this.helpers[name]; }, registerPartial: function registerPartial(name, partial2) { if (_utils.toString.call(name) === objectType) { _utils.extend(this.partials, name); } else { if (typeof partial2 === "undefined") { throw new _exception2["default"]('Attempting to register a partial called "' + name + '" as undefined'); } this.partials[name] = partial2; } }, unregisterPartial: function unregisterPartial(name) { delete this.partials[name]; }, registerDecorator: function registerDecorator(name, fn) { if (_utils.toString.call(name) === objectType) { if (fn) { throw new _exception2["default"]("Arg not supported with multiple decorators"); } _utils.extend(this.decorators, name); } else { this.decorators[name] = fn; } }, unregisterDecorator: function unregisterDecorator(name) { delete this.decorators[name]; }, /** * Reset the memory of illegal property accesses that have already been logged. * @deprecated should only be used in handlebars test-cases */ resetLoggedPropertyAccesses: function resetLoggedPropertyAccesses() { _internalProtoAccess.resetLoggedProperties(); } }; var log = _logger2["default"].log; exports.log = log; exports.createFrame = _utils.createFrame; exports.logger = _logger2["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/safe-string.js var require_safe_string = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/safe-string.js"(exports, module2) { "use strict"; exports.__esModule = true; function SafeString(string2) { this.string = string2; } SafeString.prototype.toString = SafeString.prototype.toHTML = function() { return "" + this.string; }; exports["default"] = SafeString; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js var require_wrapHelper = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/internal/wrapHelper.js"(exports) { "use strict"; exports.__esModule = true; exports.wrapHelper = wrapHelper; function wrapHelper(helper, transformOptionsFn) { if (typeof helper !== "function") { return helper; } var wrapper = function wrapper2() { var options = arguments[arguments.length - 1]; arguments[arguments.length - 1] = transformOptionsFn(options); return helper.apply(this, arguments); }; return wrapper; } } }); // node_modules/handlebars/dist/cjs/handlebars/runtime.js var require_runtime = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/runtime.js"(exports) { "use strict"; exports.__esModule = true; exports.checkRevision = checkRevision; exports.template = template; exports.wrapProgram = wrapProgram; exports.resolvePartial = resolvePartial; exports.invokePartial = invokePartial; exports.noop = noop; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _utils = require_utils(); var Utils = _interopRequireWildcard(_utils); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _base = require_base(); var _helpers = require_helpers(); var _internalWrapHelper = require_wrapHelper(); var _internalProtoAccess = require_proto_access(); function checkRevision(compilerInfo) { var compilerRevision = compilerInfo && compilerInfo[0] || 1, currentRevision = _base.COMPILER_REVISION; if (compilerRevision >= _base.LAST_COMPATIBLE_COMPILER_REVISION && compilerRevision <= _base.COMPILER_REVISION) { return; } if (compilerRevision < _base.LAST_COMPATIBLE_COMPILER_REVISION) { var runtimeVersions = _base.REVISION_CHANGES[currentRevision], compilerVersions = _base.REVISION_CHANGES[compilerRevision]; throw new _exception2["default"]("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version (" + runtimeVersions + ") or downgrade your runtime to an older version (" + compilerVersions + ")."); } else { throw new _exception2["default"]("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version (" + compilerInfo[1] + ")."); } } function template(templateSpec, env) { if (!env) { throw new _exception2["default"]("No environment passed to template"); } if (!templateSpec || !templateSpec.main) { throw new _exception2["default"]("Unknown template object: " + typeof templateSpec); } templateSpec.main.decorator = templateSpec.main_d; env.VM.checkRevision(templateSpec.compiler); var templateWasPrecompiledWithCompilerV7 = templateSpec.compiler && templateSpec.compiler[0] === 7; function invokePartialWrapper(partial2, context, options) { if (options.hash) { context = Utils.extend({}, context, options.hash); if (options.ids) { options.ids[0] = true; } } partial2 = env.VM.resolvePartial.call(this, partial2, context, options); var extendedOptions = Utils.extend({}, options, { hooks: this.hooks, protoAccessControl: this.protoAccessControl }); var result = env.VM.invokePartial.call(this, partial2, context, extendedOptions); if (result == null && env.compile) { options.partials[options.name] = env.compile(partial2, templateSpec.compilerOptions, env); result = options.partials[options.name](context, extendedOptions); } if (result != null) { if (options.indent) { var lines = result.split("\n"); for (var i = 0, l = lines.length; i < l; i++) { if (!lines[i] && i + 1 === l) { break; } lines[i] = options.indent + lines[i]; } result = lines.join("\n"); } return result; } else { throw new _exception2["default"]("The partial " + options.name + " could not be compiled when running in runtime-only mode"); } } var container = { strict: function strict(obj, name, loc) { if (!obj || !(name in obj)) { throw new _exception2["default"]('"' + name + '" not defined in ' + obj, { loc }); } return container.lookupProperty(obj, name); }, lookupProperty: function lookupProperty(parent, propertyName) { var result = parent[propertyName]; if (result == null) { return result; } if (Object.prototype.hasOwnProperty.call(parent, propertyName)) { return result; } if (_internalProtoAccess.resultIsAllowed(result, container.protoAccessControl, propertyName)) { return result; } return void 0; }, lookup: function lookup(depths, name) { var len = depths.length; for (var i = 0; i < len; i++) { var result = depths[i] && container.lookupProperty(depths[i], name); if (result != null) { return depths[i][name]; } } }, lambda: function lambda(current, context) { return typeof current === "function" ? current.call(context) : current; }, escapeExpression: Utils.escapeExpression, invokePartial: invokePartialWrapper, fn: function fn(i) { var ret2 = templateSpec[i]; ret2.decorator = templateSpec[i + "_d"]; return ret2; }, programs: [], program: function program(i, data, declaredBlockParams, blockParams, depths) { var programWrapper = this.programs[i], fn = this.fn(i); if (data || depths || blockParams || declaredBlockParams) { programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths); } else if (!programWrapper) { programWrapper = this.programs[i] = wrapProgram(this, i, fn); } return programWrapper; }, data: function data(value, depth) { while (value && depth--) { value = value._parent; } return value; }, mergeIfNeeded: function mergeIfNeeded(param, common) { var obj = param || common; if (param && common && param !== common) { obj = Utils.extend({}, common, param); } return obj; }, // An empty object to use as replacement for null-contexts nullContext: Object.seal({}), noop: env.VM.noop, compilerInfo: templateSpec.compiler }; function ret(context) { var options = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1]; var data = options.data; ret._setup(options); if (!options.partial && templateSpec.useData) { data = initData(context, data); } var depths = void 0, blockParams = templateSpec.useBlockParams ? [] : void 0; if (templateSpec.useDepths) { if (options.depths) { depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths; } else { depths = [context]; } } function main(context2) { return "" + templateSpec.main(container, context2, container.helpers, container.partials, data, blockParams, depths); } main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams); return main(context, options); } ret.isTop = true; ret._setup = function(options) { if (!options.partial) { var mergedHelpers = Utils.extend({}, env.helpers, options.helpers); wrapHelpersToPassLookupProperty(mergedHelpers, container); container.helpers = mergedHelpers; if (templateSpec.usePartial) { container.partials = container.mergeIfNeeded(options.partials, env.partials); } if (templateSpec.usePartial || templateSpec.useDecorators) { container.decorators = Utils.extend({}, env.decorators, options.decorators); } container.hooks = {}; container.protoAccessControl = _internalProtoAccess.createProtoAccessControl(options); var keepHelperInHelpers = options.allowCallsToHelperMissing || templateWasPrecompiledWithCompilerV7; _helpers.moveHelperToHooks(container, "helperMissing", keepHelperInHelpers); _helpers.moveHelperToHooks(container, "blockHelperMissing", keepHelperInHelpers); } else { container.protoAccessControl = options.protoAccessControl; container.helpers = options.helpers; container.partials = options.partials; container.decorators = options.decorators; container.hooks = options.hooks; } }; ret._child = function(i, data, blockParams, depths) { if (templateSpec.useBlockParams && !blockParams) { throw new _exception2["default"]("must pass block params"); } if (templateSpec.useDepths && !depths) { throw new _exception2["default"]("must pass parent depths"); } return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths); }; return ret; } function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) { function prog(context) { var options = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1]; var currentDepths = depths; if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) { currentDepths = [context].concat(depths); } return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths); } prog = executeDecorators(fn, prog, container, depths, data, blockParams); prog.program = i; prog.depth = depths ? depths.length : 0; prog.blockParams = declaredBlockParams || 0; return prog; } function resolvePartial(partial2, context, options) { if (!partial2) { if (options.name === "@partial-block") { partial2 = options.data["partial-block"]; } else { partial2 = options.partials[options.name]; } } else if (!partial2.call && !options.name) { options.name = partial2; partial2 = options.partials[partial2]; } return partial2; } function invokePartial(partial2, context, options) { var currentPartialBlock = options.data && options.data["partial-block"]; options.partial = true; if (options.ids) { options.data.contextPath = options.ids[0] || options.data.contextPath; } var partialBlock = void 0; if (options.fn && options.fn !== noop) { (function() { options.data = _base.createFrame(options.data); var fn = options.fn; partialBlock = options.data["partial-block"] = function partialBlockWrapper(context2) { var options2 = arguments.length <= 1 || arguments[1] === void 0 ? {} : arguments[1]; options2.data = _base.createFrame(options2.data); options2.data["partial-block"] = currentPartialBlock; return fn(context2, options2); }; if (fn.partials) { options.partials = Utils.extend({}, options.partials, fn.partials); } })(); } if (partial2 === void 0 && partialBlock) { partial2 = partialBlock; } if (partial2 === void 0) { throw new _exception2["default"]("The partial " + options.name + " could not be found"); } else if (partial2 instanceof Function) { return partial2(context, options); } } function noop() { return ""; } function initData(context, data) { if (!data || !("root" in data)) { data = data ? _base.createFrame(data) : {}; data.root = context; } return data; } function executeDecorators(fn, prog, container, depths, data, blockParams) { if (fn.decorator) { var props = {}; prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths); Utils.extend(prog, props); } return prog; } function wrapHelpersToPassLookupProperty(mergedHelpers, container) { Object.keys(mergedHelpers).forEach(function(helperName) { var helper = mergedHelpers[helperName]; mergedHelpers[helperName] = passLookupPropertyOption(helper, container); }); } function passLookupPropertyOption(helper, container) { var lookupProperty = container.lookupProperty; return _internalWrapHelper.wrapHelper(helper, function(options) { return Utils.extend({ lookupProperty }, options); }); } } }); // node_modules/handlebars/dist/cjs/handlebars/no-conflict.js var require_no_conflict = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/no-conflict.js"(exports, module2) { "use strict"; exports.__esModule = true; exports["default"] = function(Handlebars2) { (function() { if (typeof globalThis === "object") return; Object.prototype.__defineGetter__("__magic__", function() { return this; }); __magic__.globalThis = __magic__; delete Object.prototype.__magic__; })(); var $Handlebars = globalThis.Handlebars; Handlebars2.noConflict = function() { if (globalThis.Handlebars === Handlebars2) { globalThis.Handlebars = $Handlebars; } return Handlebars2; }; }; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars.runtime.js var require_handlebars_runtime = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars.runtime.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _handlebarsBase = require_base(); var base = _interopRequireWildcard(_handlebarsBase); var _handlebarsSafeString = require_safe_string(); var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString); var _handlebarsException = require_exception(); var _handlebarsException2 = _interopRequireDefault(_handlebarsException); var _handlebarsUtils = require_utils(); var Utils = _interopRequireWildcard(_handlebarsUtils); var _handlebarsRuntime = require_runtime(); var runtime = _interopRequireWildcard(_handlebarsRuntime); var _handlebarsNoConflict = require_no_conflict(); var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); function create() { var hb = new base.HandlebarsEnvironment(); Utils.extend(hb, base); hb.SafeString = _handlebarsSafeString2["default"]; hb.Exception = _handlebarsException2["default"]; hb.Utils = Utils; hb.escapeExpression = Utils.escapeExpression; hb.VM = runtime; hb.template = function(spec) { return runtime.template(spec, hb); }; return hb; } var inst = create(); inst.create = create; _handlebarsNoConflict2["default"](inst); inst["default"] = inst; exports["default"] = inst; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/ast.js var require_ast = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/ast.js"(exports, module2) { "use strict"; exports.__esModule = true; var AST = { // Public API used to evaluate derived attributes regarding AST nodes helpers: { // a mustache is definitely a helper if: // * it is an eligible helper, and // * it has at least one parameter or hash segment helperExpression: function helperExpression(node) { return node.type === "SubExpression" || (node.type === "MustacheStatement" || node.type === "BlockStatement") && !!(node.params && node.params.length || node.hash); }, scopedId: function scopedId(path) { return /^\.|this\b/.test(path.original); }, // an ID is simple if it only has one part, and that part is not // `..` or `this`. simpleId: function simpleId(path) { return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth; } } }; exports["default"] = AST; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js var require_parser = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/parser.js"(exports, module2) { "use strict"; exports.__esModule = true; var handlebars = function() { var parser = { trace: function trace() { }, yy: {}, symbols_: { "error": 2, "root": 3, "program": 4, "EOF": 5, "program_repetition0": 6, "statement": 7, "mustache": 8, "block": 9, "rawBlock": 10, "partial": 11, "partialBlock": 12, "content": 13, "COMMENT": 14, "CONTENT": 15, "openRawBlock": 16, "rawBlock_repetition0": 17, "END_RAW_BLOCK": 18, "OPEN_RAW_BLOCK": 19, "helperName": 20, "openRawBlock_repetition0": 21, "openRawBlock_option0": 22, "CLOSE_RAW_BLOCK": 23, "openBlock": 24, "block_option0": 25, "closeBlock": 26, "openInverse": 27, "block_option1": 28, "OPEN_BLOCK": 29, "openBlock_repetition0": 30, "openBlock_option0": 31, "openBlock_option1": 32, "CLOSE": 33, "OPEN_INVERSE": 34, "openInverse_repetition0": 35, "openInverse_option0": 36, "openInverse_option1": 37, "openInverseChain": 38, "OPEN_INVERSE_CHAIN": 39, "openInverseChain_repetition0": 40, "openInverseChain_option0": 41, "openInverseChain_option1": 42, "inverseAndProgram": 43, "INVERSE": 44, "inverseChain": 45, "inverseChain_option0": 46, "OPEN_ENDBLOCK": 47, "OPEN": 48, "mustache_repetition0": 49, "mustache_option0": 50, "OPEN_UNESCAPED": 51, "mustache_repetition1": 52, "mustache_option1": 53, "CLOSE_UNESCAPED": 54, "OPEN_PARTIAL": 55, "partialName": 56, "partial_repetition0": 57, "partial_option0": 58, "openPartialBlock": 59, "OPEN_PARTIAL_BLOCK": 60, "openPartialBlock_repetition0": 61, "openPartialBlock_option0": 62, "param": 63, "sexpr": 64, "OPEN_SEXPR": 65, "sexpr_repetition0": 66, "sexpr_option0": 67, "CLOSE_SEXPR": 68, "hash": 69, "hash_repetition_plus0": 70, "hashSegment": 71, "ID": 72, "EQUALS": 73, "blockParams": 74, "OPEN_BLOCK_PARAMS": 75, "blockParams_repetition_plus0": 76, "CLOSE_BLOCK_PARAMS": 77, "path": 78, "dataName": 79, "STRING": 80, "NUMBER": 81, "BOOLEAN": 82, "UNDEFINED": 83, "NULL": 84, "DATA": 85, "pathSegments": 86, "SEP": 87, "$accept": 0, "$end": 1 }, terminals_: { 2: "error", 5: "EOF", 14: "COMMENT", 15: "CONTENT", 18: "END_RAW_BLOCK", 19: "OPEN_RAW_BLOCK", 23: "CLOSE_RAW_BLOCK", 29: "OPEN_BLOCK", 33: "CLOSE", 34: "OPEN_INVERSE", 39: "OPEN_INVERSE_CHAIN", 44: "INVERSE", 47: "OPEN_ENDBLOCK", 48: "OPEN", 51: "OPEN_UNESCAPED", 54: "CLOSE_UNESCAPED", 55: "OPEN_PARTIAL", 60: "OPEN_PARTIAL_BLOCK", 65: "OPEN_SEXPR", 68: "CLOSE_SEXPR", 72: "ID", 73: "EQUALS", 75: "OPEN_BLOCK_PARAMS", 77: "CLOSE_BLOCK_PARAMS", 80: "STRING", 81: "NUMBER", 82: "BOOLEAN", 83: "UNDEFINED", 84: "NULL", 85: "DATA", 87: "SEP" }, productions_: [0, [3, 2], [4, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [7, 1], [13, 1], [10, 3], [16, 5], [9, 4], [9, 4], [24, 6], [27, 6], [38, 6], [43, 2], [45, 3], [45, 1], [26, 3], [8, 5], [8, 5], [11, 5], [12, 3], [59, 5], [63, 1], [63, 1], [64, 5], [69, 1], [71, 3], [74, 3], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [20, 1], [56, 1], [56, 1], [79, 2], [78, 1], [86, 3], [86, 1], [6, 0], [6, 2], [17, 0], [17, 2], [21, 0], [21, 2], [22, 0], [22, 1], [25, 0], [25, 1], [28, 0], [28, 1], [30, 0], [30, 2], [31, 0], [31, 1], [32, 0], [32, 1], [35, 0], [35, 2], [36, 0], [36, 1], [37, 0], [37, 1], [40, 0], [40, 2], [41, 0], [41, 1], [42, 0], [42, 1], [46, 0], [46, 1], [49, 0], [49, 2], [50, 0], [50, 1], [52, 0], [52, 2], [53, 0], [53, 1], [57, 0], [57, 2], [58, 0], [58, 1], [61, 0], [61, 2], [62, 0], [62, 1], [66, 0], [66, 2], [67, 0], [67, 1], [70, 1], [70, 2], [76, 1], [76, 2]], performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$) { var $0 = $$.length - 1; switch (yystate) { case 1: return $$[$0 - 1]; break; case 2: this.$ = yy.prepareProgram($$[$0]); break; case 3: this.$ = $$[$0]; break; case 4: this.$ = $$[$0]; break; case 5: this.$ = $$[$0]; break; case 6: this.$ = $$[$0]; break; case 7: this.$ = $$[$0]; break; case 8: this.$ = $$[$0]; break; case 9: this.$ = { type: "CommentStatement", value: yy.stripComment($$[$0]), strip: yy.stripFlags($$[$0], $$[$0]), loc: yy.locInfo(this._$) }; break; case 10: this.$ = { type: "ContentStatement", original: $$[$0], value: $$[$0], loc: yy.locInfo(this._$) }; break; case 11: this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 12: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] }; break; case 13: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$); break; case 14: this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$); break; case 15: this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 16: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 17: this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) }; break; case 18: this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] }; break; case 19: var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$), program = yy.prepareProgram([inverse], $$[$0 - 1].loc); program.chained = true; this.$ = { strip: $$[$0 - 2].strip, program, chain: true }; break; case 20: this.$ = $$[$0]; break; case 21: this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) }; break; case 22: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 23: this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$); break; case 24: this.$ = { type: "PartialStatement", name: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], indent: "", strip: yy.stripFlags($$[$0 - 4], $$[$0]), loc: yy.locInfo(this._$) }; break; case 25: this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$); break; case 26: this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) }; break; case 27: this.$ = $$[$0]; break; case 28: this.$ = $$[$0]; break; case 29: this.$ = { type: "SubExpression", path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], loc: yy.locInfo(this._$) }; break; case 30: this.$ = { type: "Hash", pairs: $$[$0], loc: yy.locInfo(this._$) }; break; case 31: this.$ = { type: "HashPair", key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) }; break; case 32: this.$ = yy.id($$[$0 - 1]); break; case 33: this.$ = $$[$0]; break; case 34: this.$ = $$[$0]; break; case 35: this.$ = { type: "StringLiteral", value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) }; break; case 36: this.$ = { type: "NumberLiteral", value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) }; break; case 37: this.$ = { type: "BooleanLiteral", value: $$[$0] === "true", original: $$[$0] === "true", loc: yy.locInfo(this._$) }; break; case 38: this.$ = { type: "UndefinedLiteral", original: void 0, value: void 0, loc: yy.locInfo(this._$) }; break; case 39: this.$ = { type: "NullLiteral", original: null, value: null, loc: yy.locInfo(this._$) }; break; case 40: this.$ = $$[$0]; break; case 41: this.$ = $$[$0]; break; case 42: this.$ = yy.preparePath(true, $$[$0], this._$); break; case 43: this.$ = yy.preparePath(false, $$[$0], this._$); break; case 44: $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] }); this.$ = $$[$0 - 2]; break; case 45: this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }]; break; case 46: this.$ = []; break; case 47: $$[$0 - 1].push($$[$0]); break; case 48: this.$ = []; break; case 49: $$[$0 - 1].push($$[$0]); break; case 50: this.$ = []; break; case 51: $$[$0 - 1].push($$[$0]); break; case 58: this.$ = []; break; case 59: $$[$0 - 1].push($$[$0]); break; case 64: this.$ = []; break; case 65: $$[$0 - 1].push($$[$0]); break; case 70: this.$ = []; break; case 71: $$[$0 - 1].push($$[$0]); break; case 78: this.$ = []; break; case 79: $$[$0 - 1].push($$[$0]); break; case 82: this.$ = []; break; case 83: $$[$0 - 1].push($$[$0]); break; case 86: this.$ = []; break; case 87: $$[$0 - 1].push($$[$0]); break; case 90: this.$ = []; break; case 91: $$[$0 - 1].push($$[$0]); break; case 94: this.$ = []; break; case 95: $$[$0 - 1].push($$[$0]); break; case 98: this.$ = [$$[$0]]; break; case 99: $$[$0 - 1].push($$[$0]); break; case 100: this.$ = [$$[$0]]; break; case 101: $$[$0 - 1].push($$[$0]); break; } }, table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 15: [2, 48], 17: 39, 18: [2, 48] }, { 20: 41, 56: 40, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 44, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 45, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 41, 56: 48, 64: 42, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 49, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 50] }, { 72: [1, 35], 86: 51 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 52, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 53, 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 54, 47: [2, 54] }, { 28: 59, 43: 60, 44: [1, 58], 47: [2, 56] }, { 13: 62, 15: [1, 20], 18: [1, 61] }, { 33: [2, 86], 57: 63, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 64, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 65, 47: [1, 66] }, { 30: 67, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 68, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 69, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 70, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 74, 33: [2, 80], 50: 71, 63: 72, 64: 75, 65: [1, 43], 69: 73, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 79] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 50] }, { 20: 74, 53: 80, 54: [2, 84], 63: 81, 64: 75, 65: [1, 43], 69: 82, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 83, 47: [1, 66] }, { 47: [2, 55] }, { 4: 84, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 85, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 86, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 87, 47: [1, 66] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 74, 33: [2, 88], 58: 88, 63: 89, 64: 75, 65: [1, 43], 69: 90, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 91, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 92, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 31: 93, 33: [2, 60], 63: 94, 64: 75, 65: [1, 43], 69: 95, 70: 76, 71: 77, 72: [1, 78], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 66], 36: 96, 63: 97, 64: 75, 65: [1, 43], 69: 98, 70: 76, 71: 77, 72: [1, 78], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 22: 99, 23: [2, 52], 63: 100, 64: 75, 65: [1, 43], 69: 101, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 74, 33: [2, 92], 62: 102, 63: 103, 64: 75, 65: [1, 43], 69: 104, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 105] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 106, 72: [1, 107], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 108], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 109] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 55, 39: [1, 57], 43: 56, 44: [1, 58], 45: 111, 46: 110, 47: [2, 76] }, { 33: [2, 70], 40: 112, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 113] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 74, 63: 115, 64: 75, 65: [1, 43], 67: 114, 68: [2, 96], 69: 116, 70: 76, 71: 77, 72: [1, 78], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 117] }, { 32: 118, 33: [2, 62], 74: 119, 75: [1, 120] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 121, 74: 122, 75: [1, 120] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 123] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 124] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 108] }, { 20: 74, 63: 125, 64: 75, 65: [1, 43], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 74, 33: [2, 72], 41: 126, 63: 127, 64: 75, 65: [1, 43], 69: 128, 70: 76, 71: 77, 72: [1, 78], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 129] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 130] }, { 33: [2, 63] }, { 72: [1, 132], 76: 131 }, { 33: [1, 133] }, { 33: [2, 69] }, { 15: [2, 12], 18: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 134, 74: 135, 75: [1, 120] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 137], 77: [1, 136] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 138] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }], defaultActions: { 4: [2, 1], 54: [2, 55], 56: [2, 20], 60: [2, 57], 73: [2, 81], 82: [2, 85], 86: [2, 18], 90: [2, 89], 101: [2, 53], 104: [2, 93], 110: [2, 19], 111: [2, 77], 116: [2, 97], 119: [2, 63], 122: [2, 69], 135: [2, 75], 136: [2, 32] }, parseError: function parseError(str2, hash) { throw new Error(str2); }, parse: function parse(input) { var self = this, stack = [0], vstack = [null], lstack = [], table = this.table, yytext = "", yylineno = 0, yyleng = 0, recovering = 0, TERROR = 2, EOF = 1; this.lexer.setInput(input); this.lexer.yy = this.yy; this.yy.lexer = this.lexer; this.yy.parser = this; if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {}; var yyloc = this.lexer.yylloc; lstack.push(yyloc); var ranges = this.lexer.options && this.lexer.options.ranges; if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError; function popStack(n) { stack.length = stack.length - 2 * n; vstack.length = vstack.length - n; lstack.length = lstack.length - n; } function lex() { var token; token = self.lexer.lex() || 1; if (typeof token !== "number") { token = self.symbols_[token] || token; } return token; } var symbol, preErrorSymbol, state, action, a, r, yyval = {}, p, len, newState, expected; while (true) { state = stack[stack.length - 1]; if (this.defaultActions[state]) { action = this.defaultActions[state]; } else { if (symbol === null || typeof symbol == "undefined") { symbol = lex(); } action = table[state] && table[state][symbol]; } if (typeof action === "undefined" || !action.length || !action[0]) { var errStr = ""; if (!recovering) { expected = []; for (p in table[state]) if (this.terminals_[p] && p > 2) { expected.push("'" + this.terminals_[p] + "'"); } if (this.lexer.showPosition) { errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'"; } else { errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'"); } this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected }); } } if (action[0] instanceof Array && action.length > 1) { throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol); } switch (action[0]) { case 1: stack.push(symbol); vstack.push(this.lexer.yytext); lstack.push(this.lexer.yylloc); stack.push(action[1]); symbol = null; if (!preErrorSymbol) { yyleng = this.lexer.yyleng; yytext = this.lexer.yytext; yylineno = this.lexer.yylineno; yyloc = this.lexer.yylloc; if (recovering > 0) recovering--; } else { symbol = preErrorSymbol; preErrorSymbol = null; } break; case 2: len = this.productions_[action[1]][1]; yyval.$ = vstack[vstack.length - len]; yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column }; if (ranges) { yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]]; } r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack); if (typeof r !== "undefined") { return r; } if (len) { stack = stack.slice(0, -1 * len * 2); vstack = vstack.slice(0, -1 * len); lstack = lstack.slice(0, -1 * len); } stack.push(this.productions_[action[1]][0]); vstack.push(yyval.$); lstack.push(yyval._$); newState = table[stack[stack.length - 2]][stack[stack.length - 1]]; stack.push(newState); break; case 3: return true; } } return true; } }; var lexer = function() { var lexer2 = { EOF: 1, parseError: function parseError(str2, hash) { if (this.yy.parser) { this.yy.parser.parseError(str2, hash); } else { throw new Error(str2); } }, setInput: function setInput(input) { this._input = input; this._more = this._less = this.done = false; this.yylineno = this.yyleng = 0; this.yytext = this.matched = this.match = ""; this.conditionStack = ["INITIAL"]; this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 }; if (this.options.ranges) this.yylloc.range = [0, 0]; this.offset = 0; return this; }, input: function input() { var ch = this._input[0]; this.yytext += ch; this.yyleng++; this.offset++; this.match += ch; this.matched += ch; var lines = ch.match(/(?:\r\n?|\n).*/g); if (lines) { this.yylineno++; this.yylloc.last_line++; } else { this.yylloc.last_column++; } if (this.options.ranges) this.yylloc.range[1]++; this._input = this._input.slice(1); return ch; }, unput: function unput(ch) { var len = ch.length; var lines = ch.split(/(?:\r\n?|\n)/g); this._input = ch + this._input; this.yytext = this.yytext.substr(0, this.yytext.length - len - 1); this.offset -= len; var oldLines = this.match.split(/(?:\r\n?|\n)/g); this.match = this.match.substr(0, this.match.length - 1); this.matched = this.matched.substr(0, this.matched.length - 1); if (lines.length - 1) this.yylineno -= lines.length - 1; var r = this.yylloc.range; this.yylloc = { first_line: this.yylloc.first_line, last_line: this.yylineno + 1, first_column: this.yylloc.first_column, last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len }; if (this.options.ranges) { this.yylloc.range = [r[0], r[0] + this.yyleng - len]; } return this; }, more: function more() { this._more = true; return this; }, less: function less(n) { this.unput(this.match.slice(n)); }, pastInput: function pastInput() { var past = this.matched.substr(0, this.matched.length - this.match.length); return (past.length > 20 ? "..." : "") + past.substr(-20).replace(/\n/g, ""); }, upcomingInput: function upcomingInput() { var next = this.match; if (next.length < 20) { next += this._input.substr(0, 20 - next.length); } return (next.substr(0, 20) + (next.length > 20 ? "..." : "")).replace(/\n/g, ""); }, showPosition: function showPosition() { var pre = this.pastInput(); var c = new Array(pre.length + 1).join("-"); return pre + this.upcomingInput() + "\n" + c + "^"; }, next: function next() { if (this.done) { return this.EOF; } if (!this._input) this.done = true; var token, match2, tempMatch, index, col, lines; if (!this._more) { this.yytext = ""; this.match = ""; } var rules = this._currentRules(); for (var i = 0; i < rules.length; i++) { tempMatch = this._input.match(this.rules[rules[i]]); if (tempMatch && (!match2 || tempMatch[0].length > match2[0].length)) { match2 = tempMatch; index = i; if (!this.options.flex) break; } } if (match2) { lines = match2[0].match(/(?:\r\n?|\n).*/g); if (lines) this.yylineno += lines.length; this.yylloc = { first_line: this.yylloc.last_line, last_line: this.yylineno + 1, first_column: this.yylloc.last_column, last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match2[0].length }; this.yytext += match2[0]; this.match += match2[0]; this.matches = match2; this.yyleng = this.yytext.length; if (this.options.ranges) { this.yylloc.range = [this.offset, this.offset += this.yyleng]; } this._more = false; this._input = this._input.slice(match2[0].length); this.matched += match2[0]; token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]); if (this.done && this._input) this.done = false; if (token) return token; else return; } if (this._input === "") { return this.EOF; } else { return this.parseError("Lexical error on line " + (this.yylineno + 1) + ". Unrecognized text.\n" + this.showPosition(), { text: "", token: null, line: this.yylineno }); } }, lex: function lex() { var r = this.next(); if (typeof r !== "undefined") { return r; } else { return this.lex(); } }, begin: function begin(condition) { this.conditionStack.push(condition); }, popState: function popState() { return this.conditionStack.pop(); }, _currentRules: function _currentRules() { return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules; }, topState: function topState() { return this.conditionStack[this.conditionStack.length - 2]; }, pushState: function begin(condition) { this.begin(condition); } }; lexer2.options = {}; lexer2.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START) { function strip(start, end) { return yy_.yytext = yy_.yytext.substring(start, yy_.yyleng - end + start); } var YYSTATE = YY_START; switch ($avoiding_name_collisions) { case 0: if (yy_.yytext.slice(-2) === "\\\\") { strip(0, 1); this.begin("mu"); } else if (yy_.yytext.slice(-1) === "\\") { strip(0, 1); this.begin("emu"); } else { this.begin("mu"); } if (yy_.yytext) return 15; break; case 1: return 15; break; case 2: this.popState(); return 15; break; case 3: this.begin("raw"); return 15; break; case 4: this.popState(); if (this.conditionStack[this.conditionStack.length - 1] === "raw") { return 15; } else { strip(5, 9); return "END_RAW_BLOCK"; } break; case 5: return 15; break; case 6: this.popState(); return 14; break; case 7: return 65; break; case 8: return 68; break; case 9: return 19; break; case 10: this.popState(); this.begin("raw"); return 23; break; case 11: return 55; break; case 12: return 60; break; case 13: return 29; break; case 14: return 47; break; case 15: this.popState(); return 44; break; case 16: this.popState(); return 44; break; case 17: return 34; break; case 18: return 39; break; case 19: return 51; break; case 20: return 48; break; case 21: this.unput(yy_.yytext); this.popState(); this.begin("com"); break; case 22: this.popState(); return 14; break; case 23: return 48; break; case 24: return 73; break; case 25: return 72; break; case 26: return 72; break; case 27: return 87; break; case 28: break; case 29: this.popState(); return 54; break; case 30: this.popState(); return 33; break; case 31: yy_.yytext = strip(1, 2).replace(/\\"/g, '"'); return 80; break; case 32: yy_.yytext = strip(1, 2).replace(/\\'/g, "'"); return 80; break; case 33: return 85; break; case 34: return 82; break; case 35: return 82; break; case 36: return 83; break; case 37: return 84; break; case 38: return 81; break; case 39: return 75; break; case 40: return 77; break; case 41: return 72; break; case 42: yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, "$1"); return 72; break; case 43: return "INVALID"; break; case 44: return 5; break; } }; lexer2.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]+?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/]; lexer2.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } }; return lexer2; }(); parser.lexer = lexer; function Parser() { this.yy = {}; } Parser.prototype = parser; parser.Parser = Parser; return new Parser(); }(); exports["default"] = handlebars; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js var require_visitor = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/visitor.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); function Visitor() { this.parents = []; } Visitor.prototype = { constructor: Visitor, mutating: false, // Visits a given value. If mutating, will replace the value if necessary. acceptKey: function acceptKey(node, name) { var value = this.accept(node[name]); if (this.mutating) { if (value && !Visitor.prototype[value.type]) { throw new _exception2["default"]('Unexpected node type "' + value.type + '" found when accepting ' + name + " on " + node.type); } node[name] = value; } }, // Performs an accept operation with added sanity check to ensure // required keys are not removed. acceptRequired: function acceptRequired(node, name) { this.acceptKey(node, name); if (!node[name]) { throw new _exception2["default"](node.type + " requires " + name); } }, // Traverses a given array. If mutating, empty respnses will be removed // for child elements. acceptArray: function acceptArray(array) { for (var i = 0, l = array.length; i < l; i++) { this.acceptKey(array, i); if (!array[i]) { array.splice(i, 1); i--; l--; } } }, accept: function accept(object2) { if (!object2) { return; } if (!this[object2.type]) { throw new _exception2["default"]("Unknown type: " + object2.type, object2); } if (this.current) { this.parents.unshift(this.current); } this.current = object2; var ret = this[object2.type](object2); this.current = this.parents.shift(); if (!this.mutating || ret) { return ret; } else if (ret !== false) { return object2; } }, Program: function Program(program) { this.acceptArray(program.body); }, MustacheStatement: visitSubExpression, Decorator: visitSubExpression, BlockStatement: visitBlock, DecoratorBlock: visitBlock, PartialStatement: visitPartial, PartialBlockStatement: function PartialBlockStatement(partial2) { visitPartial.call(this, partial2); this.acceptKey(partial2, "program"); }, ContentStatement: function ContentStatement() { }, CommentStatement: function CommentStatement() { }, SubExpression: visitSubExpression, PathExpression: function PathExpression() { }, StringLiteral: function StringLiteral() { }, NumberLiteral: function NumberLiteral() { }, BooleanLiteral: function BooleanLiteral() { }, UndefinedLiteral: function UndefinedLiteral() { }, NullLiteral: function NullLiteral() { }, Hash: function Hash(hash) { this.acceptArray(hash.pairs); }, HashPair: function HashPair(pair) { this.acceptRequired(pair, "value"); } }; function visitSubExpression(mustache) { this.acceptRequired(mustache, "path"); this.acceptArray(mustache.params); this.acceptKey(mustache, "hash"); } function visitBlock(block) { visitSubExpression.call(this, block); this.acceptKey(block, "program"); this.acceptKey(block, "inverse"); } function visitPartial(partial2) { this.acceptRequired(partial2, "name"); this.acceptArray(partial2.params); this.acceptKey(partial2, "hash"); } exports["default"] = Visitor; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/whitespace-control.js var require_whitespace_control = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/whitespace-control.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _visitor = require_visitor(); var _visitor2 = _interopRequireDefault(_visitor); function WhitespaceControl() { var options = arguments.length <= 0 || arguments[0] === void 0 ? {} : arguments[0]; this.options = options; } WhitespaceControl.prototype = new _visitor2["default"](); WhitespaceControl.prototype.Program = function(program) { var doStandalone = !this.options.ignoreStandalone; var isRoot = !this.isRootSeen; this.isRootSeen = true; var body = program.body; for (var i = 0, l = body.length; i < l; i++) { var current = body[i], strip = this.accept(current); if (!strip) { continue; } var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot), _isNextWhitespace = isNextWhitespace(body, i, isRoot), openStandalone = strip.openStandalone && _isPrevWhitespace, closeStandalone = strip.closeStandalone && _isNextWhitespace, inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace; if (strip.close) { omitRight(body, i, true); } if (strip.open) { omitLeft(body, i, true); } if (doStandalone && inlineStandalone) { omitRight(body, i); if (omitLeft(body, i)) { if (current.type === "PartialStatement") { current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1]; } } } if (doStandalone && openStandalone) { omitRight((current.program || current.inverse).body); omitLeft(body, i); } if (doStandalone && closeStandalone) { omitRight(body, i); omitLeft((current.inverse || current.program).body); } } return program; }; WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function(block) { this.accept(block.program); this.accept(block.inverse); var program = block.program || block.inverse, inverse = block.program && block.inverse, firstInverse = inverse, lastInverse = inverse; if (inverse && inverse.chained) { firstInverse = inverse.body[0].program; while (lastInverse.chained) { lastInverse = lastInverse.body[lastInverse.body.length - 1].program; } } var strip = { open: block.openStrip.open, close: block.closeStrip.close, // Determine the standalone candiacy. Basically flag our content as being possibly standalone // so our parent can determine if we actually are standalone openStandalone: isNextWhitespace(program.body), closeStandalone: isPrevWhitespace((firstInverse || program).body) }; if (block.openStrip.close) { omitRight(program.body, null, true); } if (inverse) { var inverseStrip = block.inverseStrip; if (inverseStrip.open) { omitLeft(program.body, null, true); } if (inverseStrip.close) { omitRight(firstInverse.body, null, true); } if (block.closeStrip.open) { omitLeft(lastInverse.body, null, true); } if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) { omitLeft(program.body); omitRight(firstInverse.body); } } else if (block.closeStrip.open) { omitLeft(program.body, null, true); } return strip; }; WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function(mustache) { return mustache.strip; }; WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function(node) { var strip = node.strip || {}; return { inlineStandalone: true, open: strip.open, close: strip.close }; }; function isPrevWhitespace(body, i, isRoot) { if (i === void 0) { i = body.length; } var prev = body[i - 1], sibling = body[i - 2]; if (!prev) { return isRoot; } if (prev.type === "ContentStatement") { return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original); } } function isNextWhitespace(body, i, isRoot) { if (i === void 0) { i = -1; } var next = body[i + 1], sibling = body[i + 2]; if (!next) { return isRoot; } if (next.type === "ContentStatement") { return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original); } } function omitRight(body, i, multiple) { var current = body[i == null ? 0 : i + 1]; if (!current || current.type !== "ContentStatement" || !multiple && current.rightStripped) { return; } var original = current.value; current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, ""); current.rightStripped = current.value !== original; } function omitLeft(body, i, multiple) { var current = body[i == null ? body.length - 1 : i - 1]; if (!current || current.type !== "ContentStatement" || !multiple && current.leftStripped) { return; } var original = current.value; current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, ""); current.leftStripped = current.value !== original; return current.leftStripped; } exports["default"] = WhitespaceControl; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/helpers.js var require_helpers2 = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/helpers.js"(exports) { "use strict"; exports.__esModule = true; exports.SourceLocation = SourceLocation; exports.id = id; exports.stripFlags = stripFlags; exports.stripComment = stripComment; exports.preparePath = preparePath; exports.prepareMustache = prepareMustache; exports.prepareRawBlock = prepareRawBlock; exports.prepareBlock = prepareBlock; exports.prepareProgram = prepareProgram; exports.preparePartialBlock = preparePartialBlock; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); function validateClose(open, close) { close = close.path ? close.path.original : close; if (open.path.original !== close) { var errorNode = { loc: open.path.loc }; throw new _exception2["default"](open.path.original + " doesn't match " + close, errorNode); } } function SourceLocation(source, locInfo) { this.source = source; this.start = { line: locInfo.first_line, column: locInfo.first_column }; this.end = { line: locInfo.last_line, column: locInfo.last_column }; } function id(token) { if (/^\[.*\]$/.test(token)) { return token.substring(1, token.length - 1); } else { return token; } } function stripFlags(open, close) { return { open: open.charAt(2) === "~", close: close.charAt(close.length - 3) === "~" }; } function stripComment(comment) { return comment.replace(/^\{\{~?!-?-?/, "").replace(/-?-?~?\}\}$/, ""); } function preparePath(data, parts, loc) { loc = this.locInfo(loc); var original = data ? "@" : "", dig = [], depth = 0; for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i].part, isLiteral = parts[i].original !== part; original += (parts[i].separator || "") + part; if (!isLiteral && (part === ".." || part === "." || part === "this")) { if (dig.length > 0) { throw new _exception2["default"]("Invalid path: " + original, { loc }); } else if (part === "..") { depth++; } } else { dig.push(part); } } return { type: "PathExpression", data, depth, parts: dig, original, loc }; } function prepareMustache(path, params, hash, open, strip, locInfo) { var escapeFlag = open.charAt(3) || open.charAt(2), escaped = escapeFlag !== "{" && escapeFlag !== "&"; var decorator = /\*/.test(open); return { type: decorator ? "Decorator" : "MustacheStatement", path, params, hash, escaped, strip, loc: this.locInfo(locInfo) }; } function prepareRawBlock(openRawBlock, contents, close, locInfo) { validateClose(openRawBlock, close); locInfo = this.locInfo(locInfo); var program = { type: "Program", body: contents, strip: {}, loc: locInfo }; return { type: "BlockStatement", path: openRawBlock.path, params: openRawBlock.params, hash: openRawBlock.hash, program, openStrip: {}, inverseStrip: {}, closeStrip: {}, loc: locInfo }; } function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) { if (close && close.path) { validateClose(openBlock, close); } var decorator = /\*/.test(openBlock.open); program.blockParams = openBlock.blockParams; var inverse = void 0, inverseStrip = void 0; if (inverseAndProgram) { if (decorator) { throw new _exception2["default"]("Unexpected inverse block on decorator", inverseAndProgram); } if (inverseAndProgram.chain) { inverseAndProgram.program.body[0].closeStrip = close.strip; } inverseStrip = inverseAndProgram.strip; inverse = inverseAndProgram.program; } if (inverted) { inverted = inverse; inverse = program; program = inverted; } return { type: decorator ? "DecoratorBlock" : "BlockStatement", path: openBlock.path, params: openBlock.params, hash: openBlock.hash, program, inverse, openStrip: openBlock.strip, inverseStrip, closeStrip: close && close.strip, loc: this.locInfo(locInfo) }; } function prepareProgram(statements, loc) { if (!loc && statements.length) { var firstLoc = statements[0].loc, lastLoc = statements[statements.length - 1].loc; if (firstLoc && lastLoc) { loc = { source: firstLoc.source, start: { line: firstLoc.start.line, column: firstLoc.start.column }, end: { line: lastLoc.end.line, column: lastLoc.end.column } }; } } return { type: "Program", body: statements, strip: {}, loc }; } function preparePartialBlock(open, program, close, locInfo) { validateClose(open, close); return { type: "PartialBlockStatement", name: open.path, params: open.params, hash: open.hash, program, openStrip: open.strip, closeStrip: close && close.strip, loc: this.locInfo(locInfo) }; } } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/base.js var require_base2 = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/base.js"(exports) { "use strict"; exports.__esModule = true; exports.parseWithoutProcessing = parseWithoutProcessing; exports.parse = parse; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _parser = require_parser(); var _parser2 = _interopRequireDefault(_parser); var _whitespaceControl = require_whitespace_control(); var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl); var _helpers = require_helpers2(); var Helpers = _interopRequireWildcard(_helpers); var _utils = require_utils(); exports.parser = _parser2["default"]; var yy = {}; _utils.extend(yy, Helpers); function parseWithoutProcessing(input, options) { if (input.type === "Program") { return input; } _parser2["default"].yy = yy; yy.locInfo = function(locInfo) { return new yy.SourceLocation(options && options.srcName, locInfo); }; var ast = _parser2["default"].parse(input); return ast; } function parse(input, options) { var ast = parseWithoutProcessing(input, options); var strip = new _whitespaceControl2["default"](options); return strip.accept(ast); } } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js var require_compiler = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/compiler.js"(exports) { "use strict"; exports.__esModule = true; exports.Compiler = Compiler; exports.precompile = precompile; exports.compile = compile; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _utils = require_utils(); var _ast = require_ast(); var _ast2 = _interopRequireDefault(_ast); var slice = [].slice; function Compiler() { } Compiler.prototype = { compiler: Compiler, equals: function equals(other) { var len = this.opcodes.length; if (other.opcodes.length !== len) { return false; } for (var i = 0; i < len; i++) { var opcode = this.opcodes[i], otherOpcode = other.opcodes[i]; if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) { return false; } } len = this.children.length; for (var i = 0; i < len; i++) { if (!this.children[i].equals(other.children[i])) { return false; } } return true; }, guid: 0, compile: function compile2(program, options) { this.sourceNode = []; this.opcodes = []; this.children = []; this.options = options; this.stringParams = options.stringParams; this.trackIds = options.trackIds; options.blockParams = options.blockParams || []; options.knownHelpers = _utils.extend(/* @__PURE__ */ Object.create(null), { helperMissing: true, blockHelperMissing: true, each: true, "if": true, unless: true, "with": true, log: true, lookup: true }, options.knownHelpers); return this.accept(program); }, compileProgram: function compileProgram(program) { var childCompiler = new this.compiler(), result = childCompiler.compile(program, this.options), guid = this.guid++; this.usePartial = this.usePartial || result.usePartial; this.children[guid] = result; this.useDepths = this.useDepths || result.useDepths; return guid; }, accept: function accept(node) { if (!this[node.type]) { throw new _exception2["default"]("Unknown type: " + node.type, node); } this.sourceNode.unshift(node); var ret = this[node.type](node); this.sourceNode.shift(); return ret; }, Program: function Program(program) { this.options.blockParams.unshift(program.blockParams); var body = program.body, bodyLength = body.length; for (var i = 0; i < bodyLength; i++) { this.accept(body[i]); } this.options.blockParams.shift(); this.isSimple = bodyLength === 1; this.blockParams = program.blockParams ? program.blockParams.length : 0; return this; }, BlockStatement: function BlockStatement(block) { transformLiteralToPath(block); var program = block.program, inverse = block.inverse; program = program && this.compileProgram(program); inverse = inverse && this.compileProgram(inverse); var type2 = this.classifySexpr(block); if (type2 === "helper") { this.helperSexpr(block, program, inverse); } else if (type2 === "simple") { this.simpleSexpr(block); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); this.opcode("emptyHash"); this.opcode("blockValue", block.path.original); } else { this.ambiguousSexpr(block, program, inverse); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); this.opcode("emptyHash"); this.opcode("ambiguousBlockValue"); } this.opcode("append"); }, DecoratorBlock: function DecoratorBlock(decorator) { var program = decorator.program && this.compileProgram(decorator.program); var params = this.setupFullMustacheParams(decorator, program, void 0), path = decorator.path; this.useDecorators = true; this.opcode("registerDecorator", params.length, path.original); }, PartialStatement: function PartialStatement(partial2) { this.usePartial = true; var program = partial2.program; if (program) { program = this.compileProgram(partial2.program); } var params = partial2.params; if (params.length > 1) { throw new _exception2["default"]("Unsupported number of partial arguments: " + params.length, partial2); } else if (!params.length) { if (this.options.explicitPartialContext) { this.opcode("pushLiteral", "undefined"); } else { params.push({ type: "PathExpression", parts: [], depth: 0 }); } } var partialName = partial2.name.original, isDynamic = partial2.name.type === "SubExpression"; if (isDynamic) { this.accept(partial2.name); } this.setupFullMustacheParams(partial2, program, void 0, true); var indent = partial2.indent || ""; if (this.options.preventIndent && indent) { this.opcode("appendContent", indent); indent = ""; } this.opcode("invokePartial", isDynamic, partialName, indent); this.opcode("append"); }, PartialBlockStatement: function PartialBlockStatement(partialBlock) { this.PartialStatement(partialBlock); }, MustacheStatement: function MustacheStatement(mustache) { this.SubExpression(mustache); if (mustache.escaped && !this.options.noEscape) { this.opcode("appendEscaped"); } else { this.opcode("append"); } }, Decorator: function Decorator(decorator) { this.DecoratorBlock(decorator); }, ContentStatement: function ContentStatement(content) { if (content.value) { this.opcode("appendContent", content.value); } }, CommentStatement: function CommentStatement() { }, SubExpression: function SubExpression(sexpr) { transformLiteralToPath(sexpr); var type2 = this.classifySexpr(sexpr); if (type2 === "simple") { this.simpleSexpr(sexpr); } else if (type2 === "helper") { this.helperSexpr(sexpr); } else { this.ambiguousSexpr(sexpr); } }, ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) { var path = sexpr.path, name = path.parts[0], isBlock = program != null || inverse != null; this.opcode("getContext", path.depth); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); path.strict = true; this.accept(path); this.opcode("invokeAmbiguous", name, isBlock); }, simpleSexpr: function simpleSexpr(sexpr) { var path = sexpr.path; path.strict = true; this.accept(path); this.opcode("resolvePossibleLambda"); }, helperSexpr: function helperSexpr(sexpr, program, inverse) { var params = this.setupFullMustacheParams(sexpr, program, inverse), path = sexpr.path, name = path.parts[0]; if (this.options.knownHelpers[name]) { this.opcode("invokeKnownHelper", params.length, name); } else if (this.options.knownHelpersOnly) { throw new _exception2["default"]("You specified knownHelpersOnly, but used the unknown helper " + name, sexpr); } else { path.strict = true; path.falsy = true; this.accept(path); this.opcode("invokeHelper", params.length, path.original, _ast2["default"].helpers.simpleId(path)); } }, PathExpression: function PathExpression(path) { this.addDepth(path.depth); this.opcode("getContext", path.depth); var name = path.parts[0], scoped = _ast2["default"].helpers.scopedId(path), blockParamId = !path.depth && !scoped && this.blockParamIndex(name); if (blockParamId) { this.opcode("lookupBlockParam", blockParamId, path.parts); } else if (!name) { this.opcode("pushContext"); } else if (path.data) { this.options.data = true; this.opcode("lookupData", path.depth, path.parts, path.strict); } else { this.opcode("lookupOnContext", path.parts, path.falsy, path.strict, scoped); } }, StringLiteral: function StringLiteral(string2) { this.opcode("pushString", string2.value); }, NumberLiteral: function NumberLiteral(number2) { this.opcode("pushLiteral", number2.value); }, BooleanLiteral: function BooleanLiteral(bool) { this.opcode("pushLiteral", bool.value); }, UndefinedLiteral: function UndefinedLiteral() { this.opcode("pushLiteral", "undefined"); }, NullLiteral: function NullLiteral() { this.opcode("pushLiteral", "null"); }, Hash: function Hash(hash) { var pairs = hash.pairs, i = 0, l = pairs.length; this.opcode("pushHash"); for (; i < l; i++) { this.pushParam(pairs[i].value); } while (i--) { this.opcode("assignToHash", pairs[i].key); } this.opcode("popHash"); }, // HELPERS opcode: function opcode(name) { this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc }); }, addDepth: function addDepth(depth) { if (!depth) { return; } this.useDepths = true; }, classifySexpr: function classifySexpr(sexpr) { var isSimple = _ast2["default"].helpers.simpleId(sexpr.path); var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]); var isHelper = !isBlockParam && _ast2["default"].helpers.helperExpression(sexpr); var isEligible = !isBlockParam && (isHelper || isSimple); if (isEligible && !isHelper) { var _name = sexpr.path.parts[0], options = this.options; if (options.knownHelpers[_name]) { isHelper = true; } else if (options.knownHelpersOnly) { isEligible = false; } } if (isHelper) { return "helper"; } else if (isEligible) { return "ambiguous"; } else { return "simple"; } }, pushParams: function pushParams(params) { for (var i = 0, l = params.length; i < l; i++) { this.pushParam(params[i]); } }, pushParam: function pushParam(val) { var value = val.value != null ? val.value : val.original || ""; if (this.stringParams) { if (value.replace) { value = value.replace(/^(\.?\.\/)*/g, "").replace(/\//g, "."); } if (val.depth) { this.addDepth(val.depth); } this.opcode("getContext", val.depth || 0); this.opcode("pushStringParam", value, val.type); if (val.type === "SubExpression") { this.accept(val); } } else { if (this.trackIds) { var blockParamIndex = void 0; if (val.parts && !_ast2["default"].helpers.scopedId(val) && !val.depth) { blockParamIndex = this.blockParamIndex(val.parts[0]); } if (blockParamIndex) { var blockParamChild = val.parts.slice(1).join("."); this.opcode("pushId", "BlockParam", blockParamIndex, blockParamChild); } else { value = val.original || value; if (value.replace) { value = value.replace(/^this(?:\.|$)/, "").replace(/^\.\//, "").replace(/^\.$/, ""); } this.opcode("pushId", val.type, value); } } this.accept(val); } }, setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) { var params = sexpr.params; this.pushParams(params); this.opcode("pushProgram", program); this.opcode("pushProgram", inverse); if (sexpr.hash) { this.accept(sexpr.hash); } else { this.opcode("emptyHash", omitEmpty); } return params; }, blockParamIndex: function blockParamIndex(name) { for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) { var blockParams = this.options.blockParams[depth], param = blockParams && _utils.indexOf(blockParams, name); if (blockParams && param >= 0) { return [depth, param]; } } } }; function precompile(input, options, env) { if (input == null || typeof input !== "string" && input.type !== "Program") { throw new _exception2["default"]("You must pass a string or Handlebars AST to Handlebars.precompile. You passed " + input); } options = options || {}; if (!("data" in options)) { options.data = true; } if (options.compat) { options.useDepths = true; } var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options); return new env.JavaScriptCompiler().compile(environment, options); } function compile(input, options, env) { if (options === void 0) options = {}; if (input == null || typeof input !== "string" && input.type !== "Program") { throw new _exception2["default"]("You must pass a string or Handlebars AST to Handlebars.compile. You passed " + input); } options = _utils.extend({}, options); if (!("data" in options)) { options.data = true; } if (options.compat) { options.useDepths = true; } var compiled = void 0; function compileInput() { var ast = env.parse(input, options), environment = new env.Compiler().compile(ast, options), templateSpec = new env.JavaScriptCompiler().compile(environment, options, void 0, true); return env.template(templateSpec); } function ret(context, execOptions) { if (!compiled) { compiled = compileInput(); } return compiled.call(this, context, execOptions); } ret._setup = function(setupOptions) { if (!compiled) { compiled = compileInput(); } return compiled._setup(setupOptions); }; ret._child = function(i, data, blockParams, depths) { if (!compiled) { compiled = compileInput(); } return compiled._child(i, data, blockParams, depths); }; return ret; } function argEquals(a, b) { if (a === b) { return true; } if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) { for (var i = 0; i < a.length; i++) { if (!argEquals(a[i], b[i])) { return false; } } return true; } } function transformLiteralToPath(sexpr) { if (!sexpr.path.parts) { var literal2 = sexpr.path; sexpr.path = { type: "PathExpression", data: false, depth: 0, parts: [literal2.original + ""], original: literal2.original + "", loc: literal2.loc }; } } } }); // node_modules/source-map/lib/base64.js var require_base64 = __commonJS({ "node_modules/source-map/lib/base64.js"(exports) { var intToCharMap = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split(""); exports.encode = function(number2) { if (0 <= number2 && number2 < intToCharMap.length) { return intToCharMap[number2]; } throw new TypeError("Must be between 0 and 63: " + number2); }; exports.decode = function(charCode) { var bigA = 65; var bigZ = 90; var littleA = 97; var littleZ = 122; var zero = 48; var nine = 57; var plus = 43; var slash = 47; var littleOffset = 26; var numberOffset = 52; if (bigA <= charCode && charCode <= bigZ) { return charCode - bigA; } if (littleA <= charCode && charCode <= littleZ) { return charCode - littleA + littleOffset; } if (zero <= charCode && charCode <= nine) { return charCode - zero + numberOffset; } if (charCode == plus) { return 62; } if (charCode == slash) { return 63; } return -1; }; } }); // node_modules/source-map/lib/base64-vlq.js var require_base64_vlq = __commonJS({ "node_modules/source-map/lib/base64-vlq.js"(exports) { var base64 = require_base64(); var VLQ_BASE_SHIFT = 5; var VLQ_BASE = 1 << VLQ_BASE_SHIFT; var VLQ_BASE_MASK = VLQ_BASE - 1; var VLQ_CONTINUATION_BIT = VLQ_BASE; function toVLQSigned(aValue) { return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; } function fromVLQSigned(aValue) { var isNegative = (aValue & 1) === 1; var shifted = aValue >> 1; return isNegative ? -shifted : shifted; } exports.encode = function base64VLQ_encode(aValue) { var encoded = ""; var digit; var vlq = toVLQSigned(aValue); do { digit = vlq & VLQ_BASE_MASK; vlq >>>= VLQ_BASE_SHIFT; if (vlq > 0) { digit |= VLQ_CONTINUATION_BIT; } encoded += base64.encode(digit); } while (vlq > 0); return encoded; }; exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { var strLen = aStr.length; var result = 0; var shift = 0; var continuation, digit; do { if (aIndex >= strLen) { throw new Error("Expected more digits in base 64 VLQ value."); } digit = base64.decode(aStr.charCodeAt(aIndex++)); if (digit === -1) { throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); } continuation = !!(digit & VLQ_CONTINUATION_BIT); digit &= VLQ_BASE_MASK; result = result + (digit << shift); shift += VLQ_BASE_SHIFT; } while (continuation); aOutParam.value = fromVLQSigned(result); aOutParam.rest = aIndex; }; } }); // node_modules/source-map/lib/util.js var require_util = __commonJS({ "node_modules/source-map/lib/util.js"(exports) { function getArg(aArgs, aName, aDefaultValue) { if (aName in aArgs) { return aArgs[aName]; } else if (arguments.length === 3) { return aDefaultValue; } else { throw new Error('"' + aName + '" is a required argument.'); } } exports.getArg = getArg; var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; var dataUrlRegexp = /^data:.+\,.+$/; function urlParse(aUrl) { var match2 = aUrl.match(urlRegexp); if (!match2) { return null; } return { scheme: match2[1], auth: match2[2], host: match2[3], port: match2[4], path: match2[5] }; } exports.urlParse = urlParse; function urlGenerate(aParsedUrl) { var url = ""; if (aParsedUrl.scheme) { url += aParsedUrl.scheme + ":"; } url += "//"; if (aParsedUrl.auth) { url += aParsedUrl.auth + "@"; } if (aParsedUrl.host) { url += aParsedUrl.host; } if (aParsedUrl.port) { url += ":" + aParsedUrl.port; } if (aParsedUrl.path) { url += aParsedUrl.path; } return url; } exports.urlGenerate = urlGenerate; function normalize(aPath) { var path = aPath; var url = urlParse(aPath); if (url) { if (!url.path) { return aPath; } path = url.path; } var isAbsolute = exports.isAbsolute(path); var parts = path.split(/\/+/); for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { part = parts[i]; if (part === ".") { parts.splice(i, 1); } else if (part === "..") { up++; } else if (up > 0) { if (part === "") { parts.splice(i + 1, up); up = 0; } else { parts.splice(i, 2); up--; } } } path = parts.join("/"); if (path === "") { path = isAbsolute ? "/" : "."; } if (url) { url.path = path; return urlGenerate(url); } return path; } exports.normalize = normalize; function join(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } if (aPath === "") { aPath = "."; } var aPathUrl = urlParse(aPath); var aRootUrl = urlParse(aRoot); if (aRootUrl) { aRoot = aRootUrl.path || "/"; } if (aPathUrl && !aPathUrl.scheme) { if (aRootUrl) { aPathUrl.scheme = aRootUrl.scheme; } return urlGenerate(aPathUrl); } if (aPathUrl || aPath.match(dataUrlRegexp)) { return aPath; } if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { aRootUrl.host = aPath; return urlGenerate(aRootUrl); } var joined = aPath.charAt(0) === "/" ? aPath : normalize(aRoot.replace(/\/+$/, "") + "/" + aPath); if (aRootUrl) { aRootUrl.path = joined; return urlGenerate(aRootUrl); } return joined; } exports.join = join; exports.isAbsolute = function(aPath) { return aPath.charAt(0) === "/" || urlRegexp.test(aPath); }; function relative(aRoot, aPath) { if (aRoot === "") { aRoot = "."; } aRoot = aRoot.replace(/\/$/, ""); var level = 0; while (aPath.indexOf(aRoot + "/") !== 0) { var index = aRoot.lastIndexOf("/"); if (index < 0) { return aPath; } aRoot = aRoot.slice(0, index); if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { return aPath; } ++level; } return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); } exports.relative = relative; var supportsNullProto = function() { var obj = /* @__PURE__ */ Object.create(null); return !("__proto__" in obj); }(); function identity3(s) { return s; } function toSetString(aStr) { if (isProtoString(aStr)) { return "$" + aStr; } return aStr; } exports.toSetString = supportsNullProto ? identity3 : toSetString; function fromSetString(aStr) { if (isProtoString(aStr)) { return aStr.slice(1); } return aStr; } exports.fromSetString = supportsNullProto ? identity3 : fromSetString; function isProtoString(s) { if (!s) { return false; } var length = s.length; if (length < 9) { return false; } if (s.charCodeAt(length - 1) !== 95 || s.charCodeAt(length - 2) !== 95 || s.charCodeAt(length - 3) !== 111 || s.charCodeAt(length - 4) !== 116 || s.charCodeAt(length - 5) !== 111 || s.charCodeAt(length - 6) !== 114 || s.charCodeAt(length - 7) !== 112 || s.charCodeAt(length - 8) !== 95 || s.charCodeAt(length - 9) !== 95) { return false; } for (var i = length - 10; i >= 0; i--) { if (s.charCodeAt(i) !== 36) { return false; } } return true; } function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { var cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0 || onlyCompareOriginal) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByOriginalPositions = compareByOriginalPositions; function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0 || onlyCompareGenerated) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; function strcmp(aStr1, aStr2) { if (aStr1 === aStr2) { return 0; } if (aStr1 === null) { return 1; } if (aStr2 === null) { return -1; } if (aStr1 > aStr2) { return 1; } return -1; } function compareByGeneratedPositionsInflated(mappingA, mappingB) { var cmp = mappingA.generatedLine - mappingB.generatedLine; if (cmp !== 0) { return cmp; } cmp = mappingA.generatedColumn - mappingB.generatedColumn; if (cmp !== 0) { return cmp; } cmp = strcmp(mappingA.source, mappingB.source); if (cmp !== 0) { return cmp; } cmp = mappingA.originalLine - mappingB.originalLine; if (cmp !== 0) { return cmp; } cmp = mappingA.originalColumn - mappingB.originalColumn; if (cmp !== 0) { return cmp; } return strcmp(mappingA.name, mappingB.name); } exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; function parseSourceMapInput(str2) { return JSON.parse(str2.replace(/^\)]}'[^\n]*\n/, "")); } exports.parseSourceMapInput = parseSourceMapInput; function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { sourceURL = sourceURL || ""; if (sourceRoot) { if (sourceRoot[sourceRoot.length - 1] !== "/" && sourceURL[0] !== "/") { sourceRoot += "/"; } sourceURL = sourceRoot + sourceURL; } if (sourceMapURL) { var parsed = urlParse(sourceMapURL); if (!parsed) { throw new Error("sourceMapURL could not be parsed"); } if (parsed.path) { var index = parsed.path.lastIndexOf("/"); if (index >= 0) { parsed.path = parsed.path.substring(0, index + 1); } } sourceURL = join(urlGenerate(parsed), sourceURL); } return normalize(sourceURL); } exports.computeSourceURL = computeSourceURL; } }); // node_modules/source-map/lib/array-set.js var require_array_set = __commonJS({ "node_modules/source-map/lib/array-set.js"(exports) { var util = require_util(); var has = Object.prototype.hasOwnProperty; var hasNativeMap = typeof Map !== "undefined"; function ArraySet() { this._array = []; this._set = hasNativeMap ? /* @__PURE__ */ new Map() : /* @__PURE__ */ Object.create(null); } ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { var set = new ArraySet(); for (var i = 0, len = aArray.length; i < len; i++) { set.add(aArray[i], aAllowDuplicates); } return set; }; ArraySet.prototype.size = function ArraySet_size() { return hasNativeMap ? this._set.size : Object.getOwnPropertyNames(this._set).length; }; ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { var sStr = hasNativeMap ? aStr : util.toSetString(aStr); var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); var idx = this._array.length; if (!isDuplicate || aAllowDuplicates) { this._array.push(aStr); } if (!isDuplicate) { if (hasNativeMap) { this._set.set(aStr, idx); } else { this._set[sStr] = idx; } } }; ArraySet.prototype.has = function ArraySet_has(aStr) { if (hasNativeMap) { return this._set.has(aStr); } else { var sStr = util.toSetString(aStr); return has.call(this._set, sStr); } }; ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { if (hasNativeMap) { var idx = this._set.get(aStr); if (idx >= 0) { return idx; } } else { var sStr = util.toSetString(aStr); if (has.call(this._set, sStr)) { return this._set[sStr]; } } throw new Error('"' + aStr + '" is not in the set.'); }; ArraySet.prototype.at = function ArraySet_at(aIdx) { if (aIdx >= 0 && aIdx < this._array.length) { return this._array[aIdx]; } throw new Error("No element indexed by " + aIdx); }; ArraySet.prototype.toArray = function ArraySet_toArray() { return this._array.slice(); }; exports.ArraySet = ArraySet; } }); // node_modules/source-map/lib/mapping-list.js var require_mapping_list = __commonJS({ "node_modules/source-map/lib/mapping-list.js"(exports) { var util = require_util(); function generatedPositionAfter(mappingA, mappingB) { var lineA = mappingA.generatedLine; var lineB = mappingB.generatedLine; var columnA = mappingA.generatedColumn; var columnB = mappingB.generatedColumn; return lineB > lineA || lineB == lineA && columnB >= columnA || util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; } function MappingList() { this._array = []; this._sorted = true; this._last = { generatedLine: -1, generatedColumn: 0 }; } MappingList.prototype.unsortedForEach = function MappingList_forEach(aCallback, aThisArg) { this._array.forEach(aCallback, aThisArg); }; MappingList.prototype.add = function MappingList_add(aMapping) { if (generatedPositionAfter(this._last, aMapping)) { this._last = aMapping; this._array.push(aMapping); } else { this._sorted = false; this._array.push(aMapping); } }; MappingList.prototype.toArray = function MappingList_toArray() { if (!this._sorted) { this._array.sort(util.compareByGeneratedPositionsInflated); this._sorted = true; } return this._array; }; exports.MappingList = MappingList; } }); // node_modules/source-map/lib/source-map-generator.js var require_source_map_generator = __commonJS({ "node_modules/source-map/lib/source-map-generator.js"(exports) { var base64VLQ = require_base64_vlq(); var util = require_util(); var ArraySet = require_array_set().ArraySet; var MappingList = require_mapping_list().MappingList; function SourceMapGenerator(aArgs) { if (!aArgs) { aArgs = {}; } this._file = util.getArg(aArgs, "file", null); this._sourceRoot = util.getArg(aArgs, "sourceRoot", null); this._skipValidation = util.getArg(aArgs, "skipValidation", false); this._sources = new ArraySet(); this._names = new ArraySet(); this._mappings = new MappingList(); this._sourcesContents = null; } SourceMapGenerator.prototype._version = 3; SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { var sourceRoot = aSourceMapConsumer.sourceRoot; var generator = new SourceMapGenerator({ file: aSourceMapConsumer.file, sourceRoot }); aSourceMapConsumer.eachMapping(function(mapping) { var newMapping = { generated: { line: mapping.generatedLine, column: mapping.generatedColumn } }; if (mapping.source != null) { newMapping.source = mapping.source; if (sourceRoot != null) { newMapping.source = util.relative(sourceRoot, newMapping.source); } newMapping.original = { line: mapping.originalLine, column: mapping.originalColumn }; if (mapping.name != null) { newMapping.name = mapping.name; } } generator.addMapping(newMapping); }); aSourceMapConsumer.sources.forEach(function(sourceFile) { var sourceRelative = sourceFile; if (sourceRoot !== null) { sourceRelative = util.relative(sourceRoot, sourceFile); } if (!generator._sources.has(sourceRelative)) { generator._sources.add(sourceRelative); } var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { generator.setSourceContent(sourceFile, content); } }); return generator; }; SourceMapGenerator.prototype.addMapping = function SourceMapGenerator_addMapping(aArgs) { var generated = util.getArg(aArgs, "generated"); var original = util.getArg(aArgs, "original", null); var source = util.getArg(aArgs, "source", null); var name = util.getArg(aArgs, "name", null); if (!this._skipValidation) { this._validateMapping(generated, original, source, name); } if (source != null) { source = String(source); if (!this._sources.has(source)) { this._sources.add(source); } } if (name != null) { name = String(name); if (!this._names.has(name)) { this._names.add(name); } } this._mappings.add({ generatedLine: generated.line, generatedColumn: generated.column, originalLine: original != null && original.line, originalColumn: original != null && original.column, source, name }); }; SourceMapGenerator.prototype.setSourceContent = function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { var source = aSourceFile; if (this._sourceRoot != null) { source = util.relative(this._sourceRoot, source); } if (aSourceContent != null) { if (!this._sourcesContents) { this._sourcesContents = /* @__PURE__ */ Object.create(null); } this._sourcesContents[util.toSetString(source)] = aSourceContent; } else if (this._sourcesContents) { delete this._sourcesContents[util.toSetString(source)]; if (Object.keys(this._sourcesContents).length === 0) { this._sourcesContents = null; } } }; SourceMapGenerator.prototype.applySourceMap = function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { var sourceFile = aSourceFile; if (aSourceFile == null) { if (aSourceMapConsumer.file == null) { throw new Error( `SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.` ); } sourceFile = aSourceMapConsumer.file; } var sourceRoot = this._sourceRoot; if (sourceRoot != null) { sourceFile = util.relative(sourceRoot, sourceFile); } var newSources = new ArraySet(); var newNames = new ArraySet(); this._mappings.unsortedForEach(function(mapping) { if (mapping.source === sourceFile && mapping.originalLine != null) { var original = aSourceMapConsumer.originalPositionFor({ line: mapping.originalLine, column: mapping.originalColumn }); if (original.source != null) { mapping.source = original.source; if (aSourceMapPath != null) { mapping.source = util.join(aSourceMapPath, mapping.source); } if (sourceRoot != null) { mapping.source = util.relative(sourceRoot, mapping.source); } mapping.originalLine = original.line; mapping.originalColumn = original.column; if (original.name != null) { mapping.name = original.name; } } } var source = mapping.source; if (source != null && !newSources.has(source)) { newSources.add(source); } var name = mapping.name; if (name != null && !newNames.has(name)) { newNames.add(name); } }, this); this._sources = newSources; this._names = newNames; aSourceMapConsumer.sources.forEach(function(sourceFile2) { var content = aSourceMapConsumer.sourceContentFor(sourceFile2); if (content != null) { if (aSourceMapPath != null) { sourceFile2 = util.join(aSourceMapPath, sourceFile2); } if (sourceRoot != null) { sourceFile2 = util.relative(sourceRoot, sourceFile2); } this.setSourceContent(sourceFile2, content); } }, this); }; SourceMapGenerator.prototype._validateMapping = function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, aName) { if (aOriginal && typeof aOriginal.line !== "number" && typeof aOriginal.column !== "number") { throw new Error( "original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values." ); } if (aGenerated && "line" in aGenerated && "column" in aGenerated && aGenerated.line > 0 && aGenerated.column >= 0 && !aOriginal && !aSource && !aName) { return; } else if (aGenerated && "line" in aGenerated && "column" in aGenerated && aOriginal && "line" in aOriginal && "column" in aOriginal && aGenerated.line > 0 && aGenerated.column >= 0 && aOriginal.line > 0 && aOriginal.column >= 0 && aSource) { return; } else { throw new Error("Invalid mapping: " + JSON.stringify({ generated: aGenerated, source: aSource, original: aOriginal, name: aName })); } }; SourceMapGenerator.prototype._serializeMappings = function SourceMapGenerator_serializeMappings() { var previousGeneratedColumn = 0; var previousGeneratedLine = 1; var previousOriginalColumn = 0; var previousOriginalLine = 0; var previousName = 0; var previousSource = 0; var result = ""; var next; var mapping; var nameIdx; var sourceIdx; var mappings = this._mappings.toArray(); for (var i = 0, len = mappings.length; i < len; i++) { mapping = mappings[i]; next = ""; if (mapping.generatedLine !== previousGeneratedLine) { previousGeneratedColumn = 0; while (mapping.generatedLine !== previousGeneratedLine) { next += ";"; previousGeneratedLine++; } } else { if (i > 0) { if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { continue; } next += ","; } } next += base64VLQ.encode(mapping.generatedColumn - previousGeneratedColumn); previousGeneratedColumn = mapping.generatedColumn; if (mapping.source != null) { sourceIdx = this._sources.indexOf(mapping.source); next += base64VLQ.encode(sourceIdx - previousSource); previousSource = sourceIdx; next += base64VLQ.encode(mapping.originalLine - 1 - previousOriginalLine); previousOriginalLine = mapping.originalLine - 1; next += base64VLQ.encode(mapping.originalColumn - previousOriginalColumn); previousOriginalColumn = mapping.originalColumn; if (mapping.name != null) { nameIdx = this._names.indexOf(mapping.name); next += base64VLQ.encode(nameIdx - previousName); previousName = nameIdx; } } result += next; } return result; }; SourceMapGenerator.prototype._generateSourcesContent = function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { return aSources.map(function(source) { if (!this._sourcesContents) { return null; } if (aSourceRoot != null) { source = util.relative(aSourceRoot, source); } var key = util.toSetString(source); return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) ? this._sourcesContents[key] : null; }, this); }; SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { var map2 = { version: this._version, sources: this._sources.toArray(), names: this._names.toArray(), mappings: this._serializeMappings() }; if (this._file != null) { map2.file = this._file; } if (this._sourceRoot != null) { map2.sourceRoot = this._sourceRoot; } if (this._sourcesContents) { map2.sourcesContent = this._generateSourcesContent(map2.sources, map2.sourceRoot); } return map2; }; SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { return JSON.stringify(this.toJSON()); }; exports.SourceMapGenerator = SourceMapGenerator; } }); // node_modules/source-map/lib/binary-search.js var require_binary_search = __commonJS({ "node_modules/source-map/lib/binary-search.js"(exports) { exports.GREATEST_LOWER_BOUND = 1; exports.LEAST_UPPER_BOUND = 2; function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { var mid = Math.floor((aHigh - aLow) / 2) + aLow; var cmp = aCompare(aNeedle, aHaystack[mid], true); if (cmp === 0) { return mid; } else if (cmp > 0) { if (aHigh - mid > 1) { return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); } if (aBias == exports.LEAST_UPPER_BOUND) { return aHigh < aHaystack.length ? aHigh : -1; } else { return mid; } } else { if (mid - aLow > 1) { return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); } if (aBias == exports.LEAST_UPPER_BOUND) { return mid; } else { return aLow < 0 ? -1 : aLow; } } } exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { if (aHaystack.length === 0) { return -1; } var index = recursiveSearch( -1, aHaystack.length, aNeedle, aHaystack, aCompare, aBias || exports.GREATEST_LOWER_BOUND ); if (index < 0) { return -1; } while (index - 1 >= 0) { if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { break; } --index; } return index; }; } }); // node_modules/source-map/lib/quick-sort.js var require_quick_sort = __commonJS({ "node_modules/source-map/lib/quick-sort.js"(exports) { function swap(ary, x, y) { var temp = ary[x]; ary[x] = ary[y]; ary[y] = temp; } function randomIntInRange(low, high) { return Math.round(low + Math.random() * (high - low)); } function doQuickSort(ary, comparator, p, r) { if (p < r) { var pivotIndex = randomIntInRange(p, r); var i = p - 1; swap(ary, pivotIndex, r); var pivot = ary[r]; for (var j = p; j < r; j++) { if (comparator(ary[j], pivot) <= 0) { i += 1; swap(ary, i, j); } } swap(ary, i + 1, j); var q = i + 1; doQuickSort(ary, comparator, p, q - 1); doQuickSort(ary, comparator, q + 1, r); } } exports.quickSort = function(ary, comparator) { doQuickSort(ary, comparator, 0, ary.length - 1); }; } }); // node_modules/source-map/lib/source-map-consumer.js var require_source_map_consumer = __commonJS({ "node_modules/source-map/lib/source-map-consumer.js"(exports) { var util = require_util(); var binarySearch = require_binary_search(); var ArraySet = require_array_set().ArraySet; var base64VLQ = require_base64_vlq(); var quickSort = require_quick_sort().quickSort; function SourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util.parseSourceMapInput(aSourceMap); } return sourceMap.sections != null ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); } SourceMapConsumer.fromSourceMap = function(aSourceMap, aSourceMapURL) { return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); }; SourceMapConsumer.prototype._version = 3; SourceMapConsumer.prototype.__generatedMappings = null; Object.defineProperty(SourceMapConsumer.prototype, "_generatedMappings", { configurable: true, enumerable: true, get: function() { if (!this.__generatedMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__generatedMappings; } }); SourceMapConsumer.prototype.__originalMappings = null; Object.defineProperty(SourceMapConsumer.prototype, "_originalMappings", { configurable: true, enumerable: true, get: function() { if (!this.__originalMappings) { this._parseMappings(this._mappings, this.sourceRoot); } return this.__originalMappings; } }); SourceMapConsumer.prototype._charIsMappingSeparator = function SourceMapConsumer_charIsMappingSeparator(aStr, index) { var c = aStr.charAt(index); return c === ";" || c === ","; }; SourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { throw new Error("Subclasses must implement _parseMappings"); }; SourceMapConsumer.GENERATED_ORDER = 1; SourceMapConsumer.ORIGINAL_ORDER = 2; SourceMapConsumer.GREATEST_LOWER_BOUND = 1; SourceMapConsumer.LEAST_UPPER_BOUND = 2; SourceMapConsumer.prototype.eachMapping = function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { var context = aContext || null; var order = aOrder || SourceMapConsumer.GENERATED_ORDER; var mappings; switch (order) { case SourceMapConsumer.GENERATED_ORDER: mappings = this._generatedMappings; break; case SourceMapConsumer.ORIGINAL_ORDER: mappings = this._originalMappings; break; default: throw new Error("Unknown order of iteration."); } var sourceRoot = this.sourceRoot; mappings.map(function(mapping) { var source = mapping.source === null ? null : this._sources.at(mapping.source); source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL); return { source, generatedLine: mapping.generatedLine, generatedColumn: mapping.generatedColumn, originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name: mapping.name === null ? null : this._names.at(mapping.name) }; }, this).forEach(aCallback, context); }; SourceMapConsumer.prototype.allGeneratedPositionsFor = function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { var line = util.getArg(aArgs, "line"); var needle = { source: util.getArg(aArgs, "source"), originalLine: line, originalColumn: util.getArg(aArgs, "column", 0) }; needle.source = this._findSourceIndex(needle.source); if (needle.source < 0) { return []; } var mappings = []; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, binarySearch.LEAST_UPPER_BOUND ); if (index >= 0) { var mapping = this._originalMappings[index]; if (aArgs.column === void 0) { var originalLine = mapping.originalLine; while (mapping && mapping.originalLine === originalLine) { mappings.push({ line: util.getArg(mapping, "generatedLine", null), column: util.getArg(mapping, "generatedColumn", null), lastColumn: util.getArg(mapping, "lastGeneratedColumn", null) }); mapping = this._originalMappings[++index]; } } else { var originalColumn = mapping.originalColumn; while (mapping && mapping.originalLine === line && mapping.originalColumn == originalColumn) { mappings.push({ line: util.getArg(mapping, "generatedLine", null), column: util.getArg(mapping, "generatedColumn", null), lastColumn: util.getArg(mapping, "lastGeneratedColumn", null) }); mapping = this._originalMappings[++index]; } } } return mappings; }; exports.SourceMapConsumer = SourceMapConsumer; function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util.parseSourceMapInput(aSourceMap); } var version = util.getArg(sourceMap, "version"); var sources = util.getArg(sourceMap, "sources"); var names = util.getArg(sourceMap, "names", []); var sourceRoot = util.getArg(sourceMap, "sourceRoot", null); var sourcesContent = util.getArg(sourceMap, "sourcesContent", null); var mappings = util.getArg(sourceMap, "mappings"); var file = util.getArg(sourceMap, "file", null); if (version != this._version) { throw new Error("Unsupported version: " + version); } if (sourceRoot) { sourceRoot = util.normalize(sourceRoot); } sources = sources.map(String).map(util.normalize).map(function(source) { return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) ? util.relative(sourceRoot, source) : source; }); this._names = ArraySet.fromArray(names.map(String), true); this._sources = ArraySet.fromArray(sources, true); this._absoluteSources = this._sources.toArray().map(function(s) { return util.computeSourceURL(sourceRoot, s, aSourceMapURL); }); this.sourceRoot = sourceRoot; this.sourcesContent = sourcesContent; this._mappings = mappings; this._sourceMapURL = aSourceMapURL; this.file = file; } BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; BasicSourceMapConsumer.prototype._findSourceIndex = function(aSource) { var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util.relative(this.sourceRoot, relativeSource); } if (this._sources.has(relativeSource)) { return this._sources.indexOf(relativeSource); } var i; for (i = 0; i < this._absoluteSources.length; ++i) { if (this._absoluteSources[i] == aSource) { return i; } } return -1; }; BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap(aSourceMap, aSourceMapURL) { var smc = Object.create(BasicSourceMapConsumer.prototype); var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); smc.sourceRoot = aSourceMap._sourceRoot; smc.sourcesContent = aSourceMap._generateSourcesContent( smc._sources.toArray(), smc.sourceRoot ); smc.file = aSourceMap._file; smc._sourceMapURL = aSourceMapURL; smc._absoluteSources = smc._sources.toArray().map(function(s) { return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); }); var generatedMappings = aSourceMap._mappings.toArray().slice(); var destGeneratedMappings = smc.__generatedMappings = []; var destOriginalMappings = smc.__originalMappings = []; for (var i = 0, length = generatedMappings.length; i < length; i++) { var srcMapping = generatedMappings[i]; var destMapping = new Mapping(); destMapping.generatedLine = srcMapping.generatedLine; destMapping.generatedColumn = srcMapping.generatedColumn; if (srcMapping.source) { destMapping.source = sources.indexOf(srcMapping.source); destMapping.originalLine = srcMapping.originalLine; destMapping.originalColumn = srcMapping.originalColumn; if (srcMapping.name) { destMapping.name = names.indexOf(srcMapping.name); } destOriginalMappings.push(destMapping); } destGeneratedMappings.push(destMapping); } quickSort(smc.__originalMappings, util.compareByOriginalPositions); return smc; }; BasicSourceMapConsumer.prototype._version = 3; Object.defineProperty(BasicSourceMapConsumer.prototype, "sources", { get: function() { return this._absoluteSources.slice(); } }); function Mapping() { this.generatedLine = 0; this.generatedColumn = 0; this.source = null; this.originalLine = null; this.originalColumn = null; this.name = null; } BasicSourceMapConsumer.prototype._parseMappings = function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { var generatedLine = 1; var previousGeneratedColumn = 0; var previousOriginalLine = 0; var previousOriginalColumn = 0; var previousSource = 0; var previousName = 0; var length = aStr.length; var index = 0; var cachedSegments = {}; var temp = {}; var originalMappings = []; var generatedMappings = []; var mapping, str2, segment, end, value; while (index < length) { if (aStr.charAt(index) === ";") { generatedLine++; index++; previousGeneratedColumn = 0; } else if (aStr.charAt(index) === ",") { index++; } else { mapping = new Mapping(); mapping.generatedLine = generatedLine; for (end = index; end < length; end++) { if (this._charIsMappingSeparator(aStr, end)) { break; } } str2 = aStr.slice(index, end); segment = cachedSegments[str2]; if (segment) { index += str2.length; } else { segment = []; while (index < end) { base64VLQ.decode(aStr, index, temp); value = temp.value; index = temp.rest; segment.push(value); } if (segment.length === 2) { throw new Error("Found a source, but no line and column"); } if (segment.length === 3) { throw new Error("Found a source and line, but no column"); } cachedSegments[str2] = segment; } mapping.generatedColumn = previousGeneratedColumn + segment[0]; previousGeneratedColumn = mapping.generatedColumn; if (segment.length > 1) { mapping.source = previousSource + segment[1]; previousSource += segment[1]; mapping.originalLine = previousOriginalLine + segment[2]; previousOriginalLine = mapping.originalLine; mapping.originalLine += 1; mapping.originalColumn = previousOriginalColumn + segment[3]; previousOriginalColumn = mapping.originalColumn; if (segment.length > 4) { mapping.name = previousName + segment[4]; previousName += segment[4]; } } generatedMappings.push(mapping); if (typeof mapping.originalLine === "number") { originalMappings.push(mapping); } } } quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); this.__generatedMappings = generatedMappings; quickSort(originalMappings, util.compareByOriginalPositions); this.__originalMappings = originalMappings; }; BasicSourceMapConsumer.prototype._findMapping = function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) { if (aNeedle[aLineName] <= 0) { throw new TypeError("Line must be greater than or equal to 1, got " + aNeedle[aLineName]); } if (aNeedle[aColumnName] < 0) { throw new TypeError("Column must be greater than or equal to 0, got " + aNeedle[aColumnName]); } return binarySearch.search(aNeedle, aMappings, aComparator, aBias); }; BasicSourceMapConsumer.prototype.computeColumnSpans = function SourceMapConsumer_computeColumnSpans() { for (var index = 0; index < this._generatedMappings.length; ++index) { var mapping = this._generatedMappings[index]; if (index + 1 < this._generatedMappings.length) { var nextMapping = this._generatedMappings[index + 1]; if (mapping.generatedLine === nextMapping.generatedLine) { mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; continue; } } mapping.lastGeneratedColumn = Infinity; } }; BasicSourceMapConsumer.prototype.originalPositionFor = function SourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, "line"), generatedColumn: util.getArg(aArgs, "column") }; var index = this._findMapping( needle, this._generatedMappings, "generatedLine", "generatedColumn", util.compareByGeneratedPositionsDeflated, util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._generatedMappings[index]; if (mapping.generatedLine === needle.generatedLine) { var source = util.getArg(mapping, "source", null); if (source !== null) { source = this._sources.at(source); source = util.computeSourceURL(this.sourceRoot, source, this._sourceMapURL); } var name = util.getArg(mapping, "name", null); if (name !== null) { name = this._names.at(name); } return { source, line: util.getArg(mapping, "originalLine", null), column: util.getArg(mapping, "originalColumn", null), name }; } } return { source: null, line: null, column: null, name: null }; }; BasicSourceMapConsumer.prototype.hasContentsOfAllSources = function BasicSourceMapConsumer_hasContentsOfAllSources() { if (!this.sourcesContent) { return false; } return this.sourcesContent.length >= this._sources.size() && !this.sourcesContent.some(function(sc) { return sc == null; }); }; BasicSourceMapConsumer.prototype.sourceContentFor = function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { if (!this.sourcesContent) { return null; } var index = this._findSourceIndex(aSource); if (index >= 0) { return this.sourcesContent[index]; } var relativeSource = aSource; if (this.sourceRoot != null) { relativeSource = util.relative(this.sourceRoot, relativeSource); } var url; if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ""); if (url.scheme == "file" && this._sources.has(fileUriAbsPath)) { return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; } if ((!url.path || url.path == "/") && this._sources.has("/" + relativeSource)) { return this.sourcesContent[this._sources.indexOf("/" + relativeSource)]; } } if (nullOnMissing) { return null; } else { throw new Error('"' + relativeSource + '" is not in the SourceMap.'); } }; BasicSourceMapConsumer.prototype.generatedPositionFor = function SourceMapConsumer_generatedPositionFor(aArgs) { var source = util.getArg(aArgs, "source"); source = this._findSourceIndex(source); if (source < 0) { return { line: null, column: null, lastColumn: null }; } var needle = { source, originalLine: util.getArg(aArgs, "line"), originalColumn: util.getArg(aArgs, "column") }; var index = this._findMapping( needle, this._originalMappings, "originalLine", "originalColumn", util.compareByOriginalPositions, util.getArg(aArgs, "bias", SourceMapConsumer.GREATEST_LOWER_BOUND) ); if (index >= 0) { var mapping = this._originalMappings[index]; if (mapping.source === needle.source) { return { line: util.getArg(mapping, "generatedLine", null), column: util.getArg(mapping, "generatedColumn", null), lastColumn: util.getArg(mapping, "lastGeneratedColumn", null) }; } } return { line: null, column: null, lastColumn: null }; }; exports.BasicSourceMapConsumer = BasicSourceMapConsumer; function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { var sourceMap = aSourceMap; if (typeof aSourceMap === "string") { sourceMap = util.parseSourceMapInput(aSourceMap); } var version = util.getArg(sourceMap, "version"); var sections = util.getArg(sourceMap, "sections"); if (version != this._version) { throw new Error("Unsupported version: " + version); } this._sources = new ArraySet(); this._names = new ArraySet(); var lastOffset = { line: -1, column: 0 }; this._sections = sections.map(function(s) { if (s.url) { throw new Error("Support for url field in sections not implemented."); } var offset = util.getArg(s, "offset"); var offsetLine = util.getArg(offset, "line"); var offsetColumn = util.getArg(offset, "column"); if (offsetLine < lastOffset.line || offsetLine === lastOffset.line && offsetColumn < lastOffset.column) { throw new Error("Section offsets must be ordered and non-overlapping."); } lastOffset = offset; return { generatedOffset: { // The offset fields are 0-based, but we use 1-based indices when // encoding/decoding from VLQ. generatedLine: offsetLine + 1, generatedColumn: offsetColumn + 1 }, consumer: new SourceMapConsumer(util.getArg(s, "map"), aSourceMapURL) }; }); } IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; IndexedSourceMapConsumer.prototype._version = 3; Object.defineProperty(IndexedSourceMapConsumer.prototype, "sources", { get: function() { var sources = []; for (var i = 0; i < this._sections.length; i++) { for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { sources.push(this._sections[i].consumer.sources[j]); } } return sources; } }); IndexedSourceMapConsumer.prototype.originalPositionFor = function IndexedSourceMapConsumer_originalPositionFor(aArgs) { var needle = { generatedLine: util.getArg(aArgs, "line"), generatedColumn: util.getArg(aArgs, "column") }; var sectionIndex = binarySearch.search( needle, this._sections, function(needle2, section2) { var cmp = needle2.generatedLine - section2.generatedOffset.generatedLine; if (cmp) { return cmp; } return needle2.generatedColumn - section2.generatedOffset.generatedColumn; } ); var section = this._sections[sectionIndex]; if (!section) { return { source: null, line: null, column: null, name: null }; } return section.consumer.originalPositionFor({ line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), column: needle.generatedColumn - (section.generatedOffset.generatedLine === needle.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), bias: aArgs.bias }); }; IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = function IndexedSourceMapConsumer_hasContentsOfAllSources() { return this._sections.every(function(s) { return s.consumer.hasContentsOfAllSources(); }); }; IndexedSourceMapConsumer.prototype.sourceContentFor = function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var content = section.consumer.sourceContentFor(aSource, true); if (content) { return content; } } if (nullOnMissing) { return null; } else { throw new Error('"' + aSource + '" is not in the SourceMap.'); } }; IndexedSourceMapConsumer.prototype.generatedPositionFor = function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; if (section.consumer._findSourceIndex(util.getArg(aArgs, "source")) === -1) { continue; } var generatedPosition = section.consumer.generatedPositionFor(aArgs); if (generatedPosition) { var ret = { line: generatedPosition.line + (section.generatedOffset.generatedLine - 1), column: generatedPosition.column + (section.generatedOffset.generatedLine === generatedPosition.line ? section.generatedOffset.generatedColumn - 1 : 0) }; return ret; } } return { line: null, column: null }; }; IndexedSourceMapConsumer.prototype._parseMappings = function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { this.__generatedMappings = []; this.__originalMappings = []; for (var i = 0; i < this._sections.length; i++) { var section = this._sections[i]; var sectionMappings = section.consumer._generatedMappings; for (var j = 0; j < sectionMappings.length; j++) { var mapping = sectionMappings[j]; var source = section.consumer._sources.at(mapping.source); source = util.computeSourceURL(section.consumer.sourceRoot, source, this._sourceMapURL); this._sources.add(source); source = this._sources.indexOf(source); var name = null; if (mapping.name) { name = section.consumer._names.at(mapping.name); this._names.add(name); name = this._names.indexOf(name); } var adjustedMapping = { source, generatedLine: mapping.generatedLine + (section.generatedOffset.generatedLine - 1), generatedColumn: mapping.generatedColumn + (section.generatedOffset.generatedLine === mapping.generatedLine ? section.generatedOffset.generatedColumn - 1 : 0), originalLine: mapping.originalLine, originalColumn: mapping.originalColumn, name }; this.__generatedMappings.push(adjustedMapping); if (typeof adjustedMapping.originalLine === "number") { this.__originalMappings.push(adjustedMapping); } } } quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); quickSort(this.__originalMappings, util.compareByOriginalPositions); }; exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; } }); // node_modules/source-map/lib/source-node.js var require_source_node = __commonJS({ "node_modules/source-map/lib/source-node.js"(exports) { var SourceMapGenerator = require_source_map_generator().SourceMapGenerator; var util = require_util(); var REGEX_NEWLINE = /(\r?\n)/; var NEWLINE_CODE = 10; var isSourceNode = "$$$isSourceNode$$$"; function SourceNode(aLine, aColumn, aSource, aChunks, aName) { this.children = []; this.sourceContents = {}; this.line = aLine == null ? null : aLine; this.column = aColumn == null ? null : aColumn; this.source = aSource == null ? null : aSource; this.name = aName == null ? null : aName; this[isSourceNode] = true; if (aChunks != null) this.add(aChunks); } SourceNode.fromStringWithSourceMap = function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { var node = new SourceNode(); var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); var remainingLinesIndex = 0; var shiftNextLine = function() { var lineContents = getNextLine(); var newLine = getNextLine() || ""; return lineContents + newLine; function getNextLine() { return remainingLinesIndex < remainingLines.length ? remainingLines[remainingLinesIndex++] : void 0; } }; var lastGeneratedLine = 1, lastGeneratedColumn = 0; var lastMapping = null; aSourceMapConsumer.eachMapping(function(mapping) { if (lastMapping !== null) { if (lastGeneratedLine < mapping.generatedLine) { addMappingWithCode(lastMapping, shiftNextLine()); lastGeneratedLine++; lastGeneratedColumn = 0; } else { var nextLine = remainingLines[remainingLinesIndex] || ""; var code = nextLine.substr(0, mapping.generatedColumn - lastGeneratedColumn); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn - lastGeneratedColumn); lastGeneratedColumn = mapping.generatedColumn; addMappingWithCode(lastMapping, code); lastMapping = mapping; return; } } while (lastGeneratedLine < mapping.generatedLine) { node.add(shiftNextLine()); lastGeneratedLine++; } if (lastGeneratedColumn < mapping.generatedColumn) { var nextLine = remainingLines[remainingLinesIndex] || ""; node.add(nextLine.substr(0, mapping.generatedColumn)); remainingLines[remainingLinesIndex] = nextLine.substr(mapping.generatedColumn); lastGeneratedColumn = mapping.generatedColumn; } lastMapping = mapping; }, this); if (remainingLinesIndex < remainingLines.length) { if (lastMapping) { addMappingWithCode(lastMapping, shiftNextLine()); } node.add(remainingLines.splice(remainingLinesIndex).join("")); } aSourceMapConsumer.sources.forEach(function(sourceFile) { var content = aSourceMapConsumer.sourceContentFor(sourceFile); if (content != null) { if (aRelativePath != null) { sourceFile = util.join(aRelativePath, sourceFile); } node.setSourceContent(sourceFile, content); } }); return node; function addMappingWithCode(mapping, code) { if (mapping === null || mapping.source === void 0) { node.add(code); } else { var source = aRelativePath ? util.join(aRelativePath, mapping.source) : mapping.source; node.add(new SourceNode( mapping.originalLine, mapping.originalColumn, source, code, mapping.name )); } } }; SourceNode.prototype.add = function SourceNode_add(aChunk) { if (Array.isArray(aChunk)) { aChunk.forEach(function(chunk) { this.add(chunk); }, this); } else if (aChunk[isSourceNode] || typeof aChunk === "string") { if (aChunk) { this.children.push(aChunk); } } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { if (Array.isArray(aChunk)) { for (var i = aChunk.length - 1; i >= 0; i--) { this.prepend(aChunk[i]); } } else if (aChunk[isSourceNode] || typeof aChunk === "string") { this.children.unshift(aChunk); } else { throw new TypeError( "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk ); } return this; }; SourceNode.prototype.walk = function SourceNode_walk(aFn) { var chunk; for (var i = 0, len = this.children.length; i < len; i++) { chunk = this.children[i]; if (chunk[isSourceNode]) { chunk.walk(aFn); } else { if (chunk !== "") { aFn(chunk, { source: this.source, line: this.line, column: this.column, name: this.name }); } } } }; SourceNode.prototype.join = function SourceNode_join(aSep) { var newChildren; var i; var len = this.children.length; if (len > 0) { newChildren = []; for (i = 0; i < len - 1; i++) { newChildren.push(this.children[i]); newChildren.push(aSep); } newChildren.push(this.children[i]); this.children = newChildren; } return this; }; SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { var lastChild = this.children[this.children.length - 1]; if (lastChild[isSourceNode]) { lastChild.replaceRight(aPattern, aReplacement); } else if (typeof lastChild === "string") { this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); } else { this.children.push("".replace(aPattern, aReplacement)); } return this; }; SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent(aSourceFile, aSourceContent) { this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; }; SourceNode.prototype.walkSourceContents = function SourceNode_walkSourceContents(aFn) { for (var i = 0, len = this.children.length; i < len; i++) { if (this.children[i][isSourceNode]) { this.children[i].walkSourceContents(aFn); } } var sources = Object.keys(this.sourceContents); for (var i = 0, len = sources.length; i < len; i++) { aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); } }; SourceNode.prototype.toString = function SourceNode_toString() { var str2 = ""; this.walk(function(chunk) { str2 += chunk; }); return str2; }; SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { var generated = { code: "", line: 1, column: 0 }; var map2 = new SourceMapGenerator(aArgs); var sourceMappingActive = false; var lastOriginalSource = null; var lastOriginalLine = null; var lastOriginalColumn = null; var lastOriginalName = null; this.walk(function(chunk, original) { generated.code += chunk; if (original.source !== null && original.line !== null && original.column !== null) { if (lastOriginalSource !== original.source || lastOriginalLine !== original.line || lastOriginalColumn !== original.column || lastOriginalName !== original.name) { map2.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } lastOriginalSource = original.source; lastOriginalLine = original.line; lastOriginalColumn = original.column; lastOriginalName = original.name; sourceMappingActive = true; } else if (sourceMappingActive) { map2.addMapping({ generated: { line: generated.line, column: generated.column } }); lastOriginalSource = null; sourceMappingActive = false; } for (var idx = 0, length = chunk.length; idx < length; idx++) { if (chunk.charCodeAt(idx) === NEWLINE_CODE) { generated.line++; generated.column = 0; if (idx + 1 === length) { lastOriginalSource = null; sourceMappingActive = false; } else if (sourceMappingActive) { map2.addMapping({ source: original.source, original: { line: original.line, column: original.column }, generated: { line: generated.line, column: generated.column }, name: original.name }); } } else { generated.column++; } } }); this.walkSourceContents(function(sourceFile, sourceContent) { map2.setSourceContent(sourceFile, sourceContent); }); return { code: generated.code, map: map2 }; }; exports.SourceNode = SourceNode; } }); // node_modules/source-map/source-map.js var require_source_map = __commonJS({ "node_modules/source-map/source-map.js"(exports) { exports.SourceMapGenerator = require_source_map_generator().SourceMapGenerator; exports.SourceMapConsumer = require_source_map_consumer().SourceMapConsumer; exports.SourceNode = require_source_node().SourceNode; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/code-gen.js var require_code_gen = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/code-gen.js"(exports, module2) { "use strict"; exports.__esModule = true; var _utils = require_utils(); var SourceNode = void 0; try { if (typeof define !== "function" || !define.amd) { SourceMap = require_source_map(); SourceNode = SourceMap.SourceNode; } } catch (err) { } var SourceMap; if (!SourceNode) { SourceNode = function(line, column, srcFile, chunks) { this.src = ""; if (chunks) { this.add(chunks); } }; SourceNode.prototype = { add: function add(chunks) { if (_utils.isArray(chunks)) { chunks = chunks.join(""); } this.src += chunks; }, prepend: function prepend(chunks) { if (_utils.isArray(chunks)) { chunks = chunks.join(""); } this.src = chunks + this.src; }, toStringWithSourceMap: function toStringWithSourceMap() { return { code: this.toString() }; }, toString: function toString() { return this.src; } }; } function castChunk(chunk, codeGen, loc) { if (_utils.isArray(chunk)) { var ret = []; for (var i = 0, len = chunk.length; i < len; i++) { ret.push(codeGen.wrap(chunk[i], loc)); } return ret; } else if (typeof chunk === "boolean" || typeof chunk === "number") { return chunk + ""; } return chunk; } function CodeGen(srcFile) { this.srcFile = srcFile; this.source = []; } CodeGen.prototype = { isEmpty: function isEmpty() { return !this.source.length; }, prepend: function prepend(source, loc) { this.source.unshift(this.wrap(source, loc)); }, push: function push(source, loc) { this.source.push(this.wrap(source, loc)); }, merge: function merge() { var source = this.empty(); this.each(function(line) { source.add([" ", line, "\n"]); }); return source; }, each: function each(iter) { for (var i = 0, len = this.source.length; i < len; i++) { iter(this.source[i]); } }, empty: function empty() { var loc = this.currentLocation || { start: {} }; return new SourceNode(loc.start.line, loc.start.column, this.srcFile); }, wrap: function wrap3(chunk) { var loc = arguments.length <= 1 || arguments[1] === void 0 ? this.currentLocation || { start: {} } : arguments[1]; if (chunk instanceof SourceNode) { return chunk; } chunk = castChunk(chunk, this, loc); return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk); }, functionCall: function functionCall(fn, type2, params) { params = this.generateList(params); return this.wrap([fn, type2 ? "." + type2 + "(" : "(", params, ")"]); }, quotedString: function quotedString(str2) { return '"' + (str2 + "").replace(/\\/g, "\\\\").replace(/"/g, '\\"').replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029") + '"'; }, objectLiteral: function objectLiteral(obj) { var _this = this; var pairs = []; Object.keys(obj).forEach(function(key) { var value = castChunk(obj[key], _this); if (value !== "undefined") { pairs.push([_this.quotedString(key), ":", value]); } }); var ret = this.generateList(pairs); ret.prepend("{"); ret.add("}"); return ret; }, generateList: function generateList(entries) { var ret = this.empty(); for (var i = 0, len = entries.length; i < len; i++) { if (i) { ret.add(","); } ret.add(castChunk(entries[i], this)); } return ret; }, generateArray: function generateArray(entries) { var ret = this.generateList(entries); ret.prepend("["); ret.add("]"); return ret; } }; exports["default"] = CodeGen; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js var require_javascript_compiler = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars/compiler/javascript-compiler.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _base = require_base(); var _exception = require_exception(); var _exception2 = _interopRequireDefault(_exception); var _utils = require_utils(); var _codeGen = require_code_gen(); var _codeGen2 = _interopRequireDefault(_codeGen); function Literal(value) { this.value = value; } function JavaScriptCompiler() { } JavaScriptCompiler.prototype = { // PUBLIC API: You can override these methods in a subclass to provide // alternative compiled forms for name lookup and buffering semantics nameLookup: function nameLookup(parent, name) { return this.internalNameLookup(parent, name); }, depthedLookup: function depthedLookup(name) { return [this.aliasable("container.lookup"), "(depths, ", JSON.stringify(name), ")"]; }, compilerInfo: function compilerInfo() { var revision = _base.COMPILER_REVISION, versions = _base.REVISION_CHANGES[revision]; return [revision, versions]; }, appendToBuffer: function appendToBuffer(source, location, explicit) { if (!_utils.isArray(source)) { source = [source]; } source = this.source.wrap(source, location); if (this.environment.isSimple) { return ["return ", source, ";"]; } else if (explicit) { return ["buffer += ", source, ";"]; } else { source.appendToBuffer = true; return source; } }, initializeBuffer: function initializeBuffer() { return this.quotedString(""); }, // END PUBLIC API internalNameLookup: function internalNameLookup(parent, name) { this.lookupPropertyFunctionIsUsed = true; return ["lookupProperty(", parent, ",", JSON.stringify(name), ")"]; }, lookupPropertyFunctionIsUsed: false, compile: function compile(environment, options, context, asObject) { this.environment = environment; this.options = options; this.stringParams = this.options.stringParams; this.trackIds = this.options.trackIds; this.precompile = !asObject; this.name = this.environment.name; this.isChild = !!context; this.context = context || { decorators: [], programs: [], environments: [] }; this.preamble(); this.stackSlot = 0; this.stackVars = []; this.aliases = {}; this.registers = { list: [] }; this.hashes = []; this.compileStack = []; this.inlineStack = []; this.blockParams = []; this.compileChildren(environment, options); this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat; this.useBlockParams = this.useBlockParams || environment.useBlockParams; var opcodes = environment.opcodes, opcode = void 0, firstLoc = void 0, i = void 0, l = void 0; for (i = 0, l = opcodes.length; i < l; i++) { opcode = opcodes[i]; this.source.currentLocation = opcode.loc; firstLoc = firstLoc || opcode.loc; this[opcode.opcode].apply(this, opcode.args); } this.source.currentLocation = firstLoc; this.pushSource(""); if (this.stackSlot || this.inlineStack.length || this.compileStack.length) { throw new _exception2["default"]("Compile completed with content left on stack"); } if (!this.decorators.isEmpty()) { this.useDecorators = true; this.decorators.prepend(["var decorators = container.decorators, ", this.lookupPropertyFunctionVarDeclaration(), ";\n"]); this.decorators.push("return fn;"); if (asObject) { this.decorators = Function.apply(this, ["fn", "props", "container", "depth0", "data", "blockParams", "depths", this.decorators.merge()]); } else { this.decorators.prepend("function(fn, props, container, depth0, data, blockParams, depths) {\n"); this.decorators.push("}\n"); this.decorators = this.decorators.merge(); } } else { this.decorators = void 0; } var fn = this.createFunctionContext(asObject); if (!this.isChild) { var ret = { compiler: this.compilerInfo(), main: fn }; if (this.decorators) { ret.main_d = this.decorators; ret.useDecorators = true; } var _context = this.context; var programs = _context.programs; var decorators = _context.decorators; for (i = 0, l = programs.length; i < l; i++) { if (programs[i]) { ret[i] = programs[i]; if (decorators[i]) { ret[i + "_d"] = decorators[i]; ret.useDecorators = true; } } } if (this.environment.usePartial) { ret.usePartial = true; } if (this.options.data) { ret.useData = true; } if (this.useDepths) { ret.useDepths = true; } if (this.useBlockParams) { ret.useBlockParams = true; } if (this.options.compat) { ret.compat = true; } if (!asObject) { ret.compiler = JSON.stringify(ret.compiler); this.source.currentLocation = { start: { line: 1, column: 0 } }; ret = this.objectLiteral(ret); if (options.srcName) { ret = ret.toStringWithSourceMap({ file: options.destName }); ret.map = ret.map && ret.map.toString(); } else { ret = ret.toString(); } } else { ret.compilerOptions = this.options; } return ret; } else { return fn; } }, preamble: function preamble() { this.lastContext = 0; this.source = new _codeGen2["default"](this.options.srcName); this.decorators = new _codeGen2["default"](this.options.srcName); }, createFunctionContext: function createFunctionContext(asObject) { var _this = this; var varDeclarations = ""; var locals = this.stackVars.concat(this.registers.list); if (locals.length > 0) { varDeclarations += ", " + locals.join(", "); } var aliasCount = 0; Object.keys(this.aliases).forEach(function(alias) { var node = _this.aliases[alias]; if (node.children && node.referenceCount > 1) { varDeclarations += ", alias" + ++aliasCount + "=" + alias; node.children[0] = "alias" + aliasCount; } }); if (this.lookupPropertyFunctionIsUsed) { varDeclarations += ", " + this.lookupPropertyFunctionVarDeclaration(); } var params = ["container", "depth0", "helpers", "partials", "data"]; if (this.useBlockParams || this.useDepths) { params.push("blockParams"); } if (this.useDepths) { params.push("depths"); } var source = this.mergeSource(varDeclarations); if (asObject) { params.push(source); return Function.apply(this, params); } else { return this.source.wrap(["function(", params.join(","), ") {\n ", source, "}"]); } }, mergeSource: function mergeSource(varDeclarations) { var isSimple = this.environment.isSimple, appendOnly = !this.forceBuffer, appendFirst = void 0, sourceSeen = void 0, bufferStart = void 0, bufferEnd = void 0; this.source.each(function(line) { if (line.appendToBuffer) { if (bufferStart) { line.prepend(" + "); } else { bufferStart = line; } bufferEnd = line; } else { if (bufferStart) { if (!sourceSeen) { appendFirst = true; } else { bufferStart.prepend("buffer += "); } bufferEnd.add(";"); bufferStart = bufferEnd = void 0; } sourceSeen = true; if (!isSimple) { appendOnly = false; } } }); if (appendOnly) { if (bufferStart) { bufferStart.prepend("return "); bufferEnd.add(";"); } else if (!sourceSeen) { this.source.push('return "";'); } } else { varDeclarations += ", buffer = " + (appendFirst ? "" : this.initializeBuffer()); if (bufferStart) { bufferStart.prepend("return buffer + "); bufferEnd.add(";"); } else { this.source.push("return buffer;"); } } if (varDeclarations) { this.source.prepend("var " + varDeclarations.substring(2) + (appendFirst ? "" : ";\n")); } return this.source.merge(); }, lookupPropertyFunctionVarDeclaration: function lookupPropertyFunctionVarDeclaration() { return "\n lookupProperty = container.lookupProperty || function(parent, propertyName) {\n if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {\n return parent[propertyName];\n }\n return undefined\n }\n ".trim(); }, // [blockValue] // // On stack, before: hash, inverse, program, value // On stack, after: return value of blockHelperMissing // // The purpose of this opcode is to take a block of the form // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and // replace it on the stack with the result of properly // invoking blockHelperMissing. blockValue: function blockValue(name) { var blockHelperMissing = this.aliasable("container.hooks.blockHelperMissing"), params = [this.contextName(0)]; this.setupHelperArgs(name, 0, params); var blockName = this.popStack(); params.splice(1, 0, blockName); this.push(this.source.functionCall(blockHelperMissing, "call", params)); }, // [ambiguousBlockValue] // // On stack, before: hash, inverse, program, value // Compiler value, before: lastHelper=value of last found helper, if any // On stack, after, if no lastHelper: same as [blockValue] // On stack, after, if lastHelper: value ambiguousBlockValue: function ambiguousBlockValue() { var blockHelperMissing = this.aliasable("container.hooks.blockHelperMissing"), params = [this.contextName(0)]; this.setupHelperArgs("", 0, params, true); this.flushInline(); var current = this.topStack(); params.splice(1, 0, current); this.pushSource(["if (!", this.lastHelper, ") { ", current, " = ", this.source.functionCall(blockHelperMissing, "call", params), "}"]); }, // [appendContent] // // On stack, before: ... // On stack, after: ... // // Appends the string value of `content` to the current buffer appendContent: function appendContent(content) { if (this.pendingContent) { content = this.pendingContent + content; } else { this.pendingLocation = this.source.currentLocation; } this.pendingContent = content; }, // [append] // // On stack, before: value, ... // On stack, after: ... // // Coerces `value` to a String and appends it to the current buffer. // // If `value` is truthy, or 0, it is coerced into a string and appended // Otherwise, the empty string is appended append: function append() { if (this.isInline()) { this.replaceStack(function(current) { return [" != null ? ", current, ' : ""']; }); this.pushSource(this.appendToBuffer(this.popStack())); } else { var local = this.popStack(); this.pushSource(["if (", local, " != null) { ", this.appendToBuffer(local, void 0, true), " }"]); if (this.environment.isSimple) { this.pushSource(["else { ", this.appendToBuffer("''", void 0, true), " }"]); } } }, // [appendEscaped] // // On stack, before: value, ... // On stack, after: ... // // Escape `value` and append it to the buffer appendEscaped: function appendEscaped() { this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"), "(", this.popStack(), ")"])); }, // [getContext] // // On stack, before: ... // On stack, after: ... // Compiler value, after: lastContext=depth // // Set the value of the `lastContext` compiler value to the depth getContext: function getContext(depth) { this.lastContext = depth; }, // [pushContext] // // On stack, before: ... // On stack, after: currentContext, ... // // Pushes the value of the current context onto the stack. pushContext: function pushContext() { this.pushStackLiteral(this.contextName(this.lastContext)); }, // [lookupOnContext] // // On stack, before: ... // On stack, after: currentContext[name], ... // // Looks up the value of `name` on the current context and pushes // it onto the stack. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) { var i = 0; if (!scoped && this.options.compat && !this.lastContext) { this.push(this.depthedLookup(parts[i++])); } else { this.pushContext(); } this.resolvePath("context", parts, i, falsy, strict); }, // [lookupBlockParam] // // On stack, before: ... // On stack, after: blockParam[name], ... // // Looks up the value of `parts` on the given block param and pushes // it onto the stack. lookupBlockParam: function lookupBlockParam(blockParamId, parts) { this.useBlockParams = true; this.push(["blockParams[", blockParamId[0], "][", blockParamId[1], "]"]); this.resolvePath("context", parts, 1); }, // [lookupData] // // On stack, before: ... // On stack, after: data, ... // // Push the data lookup operator lookupData: function lookupData(depth, parts, strict) { if (!depth) { this.pushStackLiteral("data"); } else { this.pushStackLiteral("container.data(data, " + depth + ")"); } this.resolvePath("data", parts, 0, true, strict); }, resolvePath: function resolvePath(type2, parts, i, falsy, strict) { var _this2 = this; if (this.options.strict || this.options.assumeObjects) { this.push(strictLookup(this.options.strict && strict, this, parts, i, type2)); return; } var len = parts.length; for (; i < len; i++) { this.replaceStack(function(current) { var lookup = _this2.nameLookup(current, parts[i], type2); if (!falsy) { return [" != null ? ", lookup, " : ", current]; } else { return [" && ", lookup]; } }); } }, // [resolvePossibleLambda] // // On stack, before: value, ... // On stack, after: resolved value, ... // // If the `value` is a lambda, replace it on the stack by // the return value of the lambda resolvePossibleLambda: function resolvePossibleLambda() { this.push([this.aliasable("container.lambda"), "(", this.popStack(), ", ", this.contextName(0), ")"]); }, // [pushStringParam] // // On stack, before: ... // On stack, after: string, currentContext, ... // // This opcode is designed for use in string mode, which // provides the string value of a parameter along with its // depth rather than resolving it immediately. pushStringParam: function pushStringParam(string2, type2) { this.pushContext(); this.pushString(type2); if (type2 !== "SubExpression") { if (typeof string2 === "string") { this.pushString(string2); } else { this.pushStackLiteral(string2); } } }, emptyHash: function emptyHash(omitEmpty) { if (this.trackIds) { this.push("{}"); } if (this.stringParams) { this.push("{}"); this.push("{}"); } this.pushStackLiteral(omitEmpty ? "undefined" : "{}"); }, pushHash: function pushHash() { if (this.hash) { this.hashes.push(this.hash); } this.hash = { values: {}, types: [], contexts: [], ids: [] }; }, popHash: function popHash() { var hash = this.hash; this.hash = this.hashes.pop(); if (this.trackIds) { this.push(this.objectLiteral(hash.ids)); } if (this.stringParams) { this.push(this.objectLiteral(hash.contexts)); this.push(this.objectLiteral(hash.types)); } this.push(this.objectLiteral(hash.values)); }, // [pushString] // // On stack, before: ... // On stack, after: quotedString(string), ... // // Push a quoted version of `string` onto the stack pushString: function pushString(string2) { this.pushStackLiteral(this.quotedString(string2)); }, // [pushLiteral] // // On stack, before: ... // On stack, after: value, ... // // Pushes a value onto the stack. This operation prevents // the compiler from creating a temporary variable to hold // it. pushLiteral: function pushLiteral(value) { this.pushStackLiteral(value); }, // [pushProgram] // // On stack, before: ... // On stack, after: program(guid), ... // // Push a program expression onto the stack. This takes // a compile-time guid and converts it into a runtime-accessible // expression. pushProgram: function pushProgram(guid) { if (guid != null) { this.pushStackLiteral(this.programExpression(guid)); } else { this.pushStackLiteral(null); } }, // [registerDecorator] // // On stack, before: hash, program, params..., ... // On stack, after: ... // // Pops off the decorator's parameters, invokes the decorator, // and inserts the decorator into the decorators list. registerDecorator: function registerDecorator(paramSize, name) { var foundDecorator = this.nameLookup("decorators", name, "decorator"), options = this.setupHelperArgs(name, paramSize); this.decorators.push(["fn = ", this.decorators.functionCall(foundDecorator, "", ["fn", "props", "container", options]), " || fn;"]); }, // [invokeHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // Pops off the helper's parameters, invokes the helper, // and pushes the helper's return value onto the stack. // // If the helper is not found, `helperMissing` is called. invokeHelper: function invokeHelper(paramSize, name, isSimple) { var nonHelper = this.popStack(), helper = this.setupHelper(paramSize, name); var possibleFunctionCalls = []; if (isSimple) { possibleFunctionCalls.push(helper.name); } possibleFunctionCalls.push(nonHelper); if (!this.options.strict) { possibleFunctionCalls.push(this.aliasable("container.hooks.helperMissing")); } var functionLookupCode = ["(", this.itemsSeparatedBy(possibleFunctionCalls, "||"), ")"]; var functionCall = this.source.functionCall(functionLookupCode, "call", helper.callParams); this.push(functionCall); }, itemsSeparatedBy: function itemsSeparatedBy(items, separator) { var result = []; result.push(items[0]); for (var i = 1; i < items.length; i++) { result.push(separator, items[i]); } return result; }, // [invokeKnownHelper] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of helper invocation // // This operation is used when the helper is known to exist, // so a `helperMissing` fallback is not required. invokeKnownHelper: function invokeKnownHelper(paramSize, name) { var helper = this.setupHelper(paramSize, name); this.push(this.source.functionCall(helper.name, "call", helper.callParams)); }, // [invokeAmbiguous] // // On stack, before: hash, inverse, program, params..., ... // On stack, after: result of disambiguation // // This operation is used when an expression like `{{foo}}` // is provided, but we don't know at compile-time whether it // is a helper or a path. // // This operation emits more code than the other options, // and can be avoided by passing the `knownHelpers` and // `knownHelpersOnly` flags at compile-time. invokeAmbiguous: function invokeAmbiguous(name, helperCall) { this.useRegister("helper"); var nonHelper = this.popStack(); this.emptyHash(); var helper = this.setupHelper(0, name, helperCall); var helperName = this.lastHelper = this.nameLookup("helpers", name, "helper"); var lookup = ["(", "(helper = ", helperName, " || ", nonHelper, ")"]; if (!this.options.strict) { lookup[0] = "(helper = "; lookup.push(" != null ? helper : ", this.aliasable("container.hooks.helperMissing")); } this.push(["(", lookup, helper.paramsInit ? ["),(", helper.paramsInit] : [], "),", "(typeof helper === ", this.aliasable('"function"'), " ? ", this.source.functionCall("helper", "call", helper.callParams), " : helper))"]); }, // [invokePartial] // // On stack, before: context, ... // On stack after: result of partial invocation // // This operation pops off a context, invokes a partial with that context, // and pushes the result of the invocation back. invokePartial: function invokePartial(isDynamic, name, indent) { var params = [], options = this.setupParams(name, 1, params); if (isDynamic) { name = this.popStack(); delete options.name; } if (indent) { options.indent = JSON.stringify(indent); } options.helpers = "helpers"; options.partials = "partials"; options.decorators = "container.decorators"; if (!isDynamic) { params.unshift(this.nameLookup("partials", name, "partial")); } else { params.unshift(name); } if (this.options.compat) { options.depths = "depths"; } options = this.objectLiteral(options); params.push(options); this.push(this.source.functionCall("container.invokePartial", "", params)); }, // [assignToHash] // // On stack, before: value, ..., hash, ... // On stack, after: ..., hash, ... // // Pops a value off the stack and assigns it to the current hash assignToHash: function assignToHash(key) { var value = this.popStack(), context = void 0, type2 = void 0, id = void 0; if (this.trackIds) { id = this.popStack(); } if (this.stringParams) { type2 = this.popStack(); context = this.popStack(); } var hash = this.hash; if (context) { hash.contexts[key] = context; } if (type2) { hash.types[key] = type2; } if (id) { hash.ids[key] = id; } hash.values[key] = value; }, pushId: function pushId(type2, name, child) { if (type2 === "BlockParam") { this.pushStackLiteral("blockParams[" + name[0] + "].path[" + name[1] + "]" + (child ? " + " + JSON.stringify("." + child) : "")); } else if (type2 === "PathExpression") { this.pushString(name); } else if (type2 === "SubExpression") { this.pushStackLiteral("true"); } else { this.pushStackLiteral("null"); } }, // HELPERS compiler: JavaScriptCompiler, compileChildren: function compileChildren(environment, options) { var children = environment.children, child = void 0, compiler = void 0; for (var i = 0, l = children.length; i < l; i++) { child = children[i]; compiler = new this.compiler(); var existing = this.matchExistingProgram(child); if (existing == null) { this.context.programs.push(""); var index = this.context.programs.length; child.index = index; child.name = "program" + index; this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile); this.context.decorators[index] = compiler.decorators; this.context.environments[index] = child; this.useDepths = this.useDepths || compiler.useDepths; this.useBlockParams = this.useBlockParams || compiler.useBlockParams; child.useDepths = this.useDepths; child.useBlockParams = this.useBlockParams; } else { child.index = existing.index; child.name = "program" + existing.index; this.useDepths = this.useDepths || existing.useDepths; this.useBlockParams = this.useBlockParams || existing.useBlockParams; } } }, matchExistingProgram: function matchExistingProgram(child) { for (var i = 0, len = this.context.environments.length; i < len; i++) { var environment = this.context.environments[i]; if (environment && environment.equals(child)) { return environment; } } }, programExpression: function programExpression(guid) { var child = this.environment.children[guid], programParams = [child.index, "data", child.blockParams]; if (this.useBlockParams || this.useDepths) { programParams.push("blockParams"); } if (this.useDepths) { programParams.push("depths"); } return "container.program(" + programParams.join(", ") + ")"; }, useRegister: function useRegister(name) { if (!this.registers[name]) { this.registers[name] = true; this.registers.list.push(name); } }, push: function push(expr) { if (!(expr instanceof Literal)) { expr = this.source.wrap(expr); } this.inlineStack.push(expr); return expr; }, pushStackLiteral: function pushStackLiteral(item) { this.push(new Literal(item)); }, pushSource: function pushSource(source) { if (this.pendingContent) { this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation)); this.pendingContent = void 0; } if (source) { this.source.push(source); } }, replaceStack: function replaceStack(callback) { var prefix = ["("], stack = void 0, createdStack = void 0, usedLiteral = void 0; if (!this.isInline()) { throw new _exception2["default"]("replaceStack on non-inline"); } var top = this.popStack(true); if (top instanceof Literal) { stack = [top.value]; prefix = ["(", stack]; usedLiteral = true; } else { createdStack = true; var _name = this.incrStack(); prefix = ["((", this.push(_name), " = ", top, ")"]; stack = this.topStack(); } var item = callback.call(this, stack); if (!usedLiteral) { this.popStack(); } if (createdStack) { this.stackSlot--; } this.push(prefix.concat(item, ")")); }, incrStack: function incrStack() { this.stackSlot++; if (this.stackSlot > this.stackVars.length) { this.stackVars.push("stack" + this.stackSlot); } return this.topStackName(); }, topStackName: function topStackName() { return "stack" + this.stackSlot; }, flushInline: function flushInline() { var inlineStack = this.inlineStack; this.inlineStack = []; for (var i = 0, len = inlineStack.length; i < len; i++) { var entry = inlineStack[i]; if (entry instanceof Literal) { this.compileStack.push(entry); } else { var stack = this.incrStack(); this.pushSource([stack, " = ", entry, ";"]); this.compileStack.push(stack); } } }, isInline: function isInline() { return this.inlineStack.length; }, popStack: function popStack(wrapped) { var inline = this.isInline(), item = (inline ? this.inlineStack : this.compileStack).pop(); if (!wrapped && item instanceof Literal) { return item.value; } else { if (!inline) { if (!this.stackSlot) { throw new _exception2["default"]("Invalid stack pop"); } this.stackSlot--; } return item; } }, topStack: function topStack() { var stack = this.isInline() ? this.inlineStack : this.compileStack, item = stack[stack.length - 1]; if (item instanceof Literal) { return item.value; } else { return item; } }, contextName: function contextName(context) { if (this.useDepths && context) { return "depths[" + context + "]"; } else { return "depth" + context; } }, quotedString: function quotedString(str2) { return this.source.quotedString(str2); }, objectLiteral: function objectLiteral(obj) { return this.source.objectLiteral(obj); }, aliasable: function aliasable(name) { var ret = this.aliases[name]; if (ret) { ret.referenceCount++; return ret; } ret = this.aliases[name] = this.source.wrap(name); ret.aliasable = true; ret.referenceCount = 1; return ret; }, setupHelper: function setupHelper(paramSize, name, blockHelper) { var params = [], paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper); var foundHelper = this.nameLookup("helpers", name, "helper"), callContext = this.aliasable(this.contextName(0) + " != null ? " + this.contextName(0) + " : (container.nullContext || {})"); return { params, paramsInit, name: foundHelper, callParams: [callContext].concat(params) }; }, setupParams: function setupParams(helper, paramSize, params) { var options = {}, contexts = [], types2 = [], ids = [], objectArgs = !params, param = void 0; if (objectArgs) { params = []; } options.name = this.quotedString(helper); options.hash = this.popStack(); if (this.trackIds) { options.hashIds = this.popStack(); } if (this.stringParams) { options.hashTypes = this.popStack(); options.hashContexts = this.popStack(); } var inverse = this.popStack(), program = this.popStack(); if (program || inverse) { options.fn = program || "container.noop"; options.inverse = inverse || "container.noop"; } var i = paramSize; while (i--) { param = this.popStack(); params[i] = param; if (this.trackIds) { ids[i] = this.popStack(); } if (this.stringParams) { types2[i] = this.popStack(); contexts[i] = this.popStack(); } } if (objectArgs) { options.args = this.source.generateArray(params); } if (this.trackIds) { options.ids = this.source.generateArray(ids); } if (this.stringParams) { options.types = this.source.generateArray(types2); options.contexts = this.source.generateArray(contexts); } if (this.options.data) { options.data = "data"; } if (this.useBlockParams) { options.blockParams = "blockParams"; } return options; }, setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) { var options = this.setupParams(helper, paramSize, params); options.loc = JSON.stringify(this.source.currentLocation); options = this.objectLiteral(options); if (useRegister) { this.useRegister("options"); params.push("options"); return ["options=", options]; } else if (params) { params.push(options); return ""; } else { return options; } } }; (function() { var reservedWords = "break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "); var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {}; for (var i = 0, l = reservedWords.length; i < l; i++) { compilerWords[reservedWords[i]] = true; } })(); JavaScriptCompiler.isValidJavaScriptVariableName = function(name) { return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name); }; function strictLookup(requireTerminal, compiler, parts, i, type2) { var stack = compiler.popStack(), len = parts.length; if (requireTerminal) { len--; } for (; i < len; i++) { stack = compiler.nameLookup(stack, parts[i], type2); } if (requireTerminal) { return [compiler.aliasable("container.strict"), "(", stack, ", ", compiler.quotedString(parts[i]), ", ", JSON.stringify(compiler.source.currentLocation), " )"]; } else { return stack; } } exports["default"] = JavaScriptCompiler; module2.exports = exports["default"]; } }); // node_modules/handlebars/dist/cjs/handlebars.js var require_handlebars = __commonJS({ "node_modules/handlebars/dist/cjs/handlebars.js"(exports, module2) { "use strict"; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } var _handlebarsRuntime = require_handlebars_runtime(); var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime); var _handlebarsCompilerAst = require_ast(); var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst); var _handlebarsCompilerBase = require_base2(); var _handlebarsCompilerCompiler = require_compiler(); var _handlebarsCompilerJavascriptCompiler = require_javascript_compiler(); var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler); var _handlebarsCompilerVisitor = require_visitor(); var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor); var _handlebarsNoConflict = require_no_conflict(); var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict); var _create = _handlebarsRuntime2["default"].create; function create() { var hb = _create(); hb.compile = function(input, options) { return _handlebarsCompilerCompiler.compile(input, options, hb); }; hb.precompile = function(input, options) { return _handlebarsCompilerCompiler.precompile(input, options, hb); }; hb.AST = _handlebarsCompilerAst2["default"]; hb.Compiler = _handlebarsCompilerCompiler.Compiler; hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2["default"]; hb.Parser = _handlebarsCompilerBase.parser; hb.parse = _handlebarsCompilerBase.parse; hb.parseWithoutProcessing = _handlebarsCompilerBase.parseWithoutProcessing; return hb; } var inst = create(); inst.create = create; _handlebarsNoConflict2["default"](inst); inst.Visitor = _handlebarsCompilerVisitor2["default"]; inst["default"] = inst; exports["default"] = inst; module2.exports = exports["default"]; } }); // src/main.ts var main_exports = {}; __export(main_exports, { default: () => AIZhipuPlugin }); module.exports = __toCommonJS(main_exports); var import_handlebars = __toESM(require_handlebars()); var import_obsidian4 = require("obsidian"); // node_modules/fp-ts/es6/function.js var __spreadArray = function(to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; function identity(a) { return a; } function pipe(a, ab, bc, cd, de, ef, fg, gh, hi) { switch (arguments.length) { case 1: return a; case 2: return ab(a); case 3: return bc(ab(a)); case 4: return cd(bc(ab(a))); case 5: return de(cd(bc(ab(a)))); case 6: return ef(de(cd(bc(ab(a))))); case 7: return fg(ef(de(cd(bc(ab(a)))))); case 8: return gh(fg(ef(de(cd(bc(ab(a))))))); case 9: return hi(gh(fg(ef(de(cd(bc(ab(a)))))))); default: { var ret = arguments[0]; for (var i = 1; i < arguments.length; i++) { ret = arguments[i](ret); } return ret; } } } var dual = function(arity, body) { var isDataFirst = typeof arity === "number" ? function(args) { return args.length >= arity; } : arity; return function() { var args = Array.from(arguments); if (isDataFirst(arguments)) { return body.apply(this, args); } return function(self) { return body.apply(void 0, __spreadArray([self], args, false)); }; }; }; // node_modules/fp-ts/es6/internal.js var isLeft = function(ma) { return ma._tag === "Left"; }; var left = function(e) { return { _tag: "Left", left: e }; }; var right = function(a) { return { _tag: "Right", right: a }; }; // node_modules/fp-ts/es6/Functor.js function as(F) { return function(self, b) { return F.map(self, function() { return b; }); }; } function asUnit(F) { var asM = as(F); return function(self) { return asM(self, void 0); }; } // node_modules/fp-ts/es6/Chain.js function tap(M) { return function(first, f) { return M.chain(first, function(a) { return M.map(f(a), function() { return a; }); }); }; } // node_modules/fp-ts/es6/Either.js var left2 = left; var right2 = right; var flatMap = /* @__PURE__ */ dual(2, function(ma, f) { return isLeft2(ma) ? ma : f(ma.right); }); var _map = function(fa, f) { return pipe(fa, map(f)); }; var _ap = function(fab, fa) { return pipe(fab, ap(fa)); }; var URI = "Either"; var map = function(f) { return function(fa) { return isLeft2(fa) ? fa : right2(f(fa.right)); }; }; var Functor = { URI, map: _map }; var as2 = dual(2, as(Functor)); var asUnit2 = asUnit(Functor); var apW = function(fa) { return function(fab) { return isLeft2(fab) ? fab : isLeft2(fa) ? fa : right2(fab.right(fa.right)); }; }; var ap = apW; var Chain = { URI, map: _map, ap: _ap, chain: flatMap }; var FromEither = { URI, fromEither: identity }; var isLeft2 = isLeft; var matchW = function(onLeft, onRight) { return function(ma) { return isLeft2(ma) ? onLeft(ma.left) : onRight(ma.right); }; }; var match = matchW; var fold = match; var tap2 = /* @__PURE__ */ dual(2, tap(Chain)); var _FromEither = { fromEither: FromEither.fromEither }; // node_modules/io-ts/es6/index.js var __extends = function() { var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) { d2.__proto__ = b2; } || function(d2, b2) { for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p]; }; return extendStatics(d, b); }; return function(d, b) { if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; }(); var __assign = function() { __assign = Object.assign || function(t2) { 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)) t2[p] = s[p]; } return t2; }; return __assign.apply(this, arguments); }; var failures = left2; var failure = function(value, context, message2) { return failures([{ value, context, message: message2 }]); }; var success = right2; var Type = ( /** @class */ function() { function Type2(name, is, validate, encode3) { this.name = name; this.is = is; this.validate = validate; this.encode = encode3; this.decode = this.decode.bind(this); } Type2.prototype.pipe = function(ab, name) { var _this = this; if (name === void 0) { name = "pipe(".concat(this.name, ", ").concat(ab.name, ")"); } return new Type2(name, ab.is, function(i, c) { var e = _this.validate(i, c); if (isLeft2(e)) { return e; } return ab.validate(e.right, c); }, this.encode === identity2 && ab.encode === identity2 ? identity2 : function(b) { return _this.encode(ab.encode(b)); }); }; Type2.prototype.asDecoder = function() { return this; }; Type2.prototype.asEncoder = function() { return this; }; Type2.prototype.decode = function(i) { return this.validate(i, [{ key: "", type: this, actual: i }]); }; return Type2; }() ); var identity2 = function(a) { return a; }; function getFunctionName(f) { return f.displayName || f.name || ""); } function appendContext(c, key, decoder2, actual) { var len = c.length; var r = Array(len + 1); for (var i = 0; i < len; i++) { r[i] = c[i]; } r[len] = { key, type: decoder2, actual }; return r; } function pushAll(xs, ys) { var l = ys.length; for (var i = 0; i < l; i++) { xs.push(ys[i]); } } var hasOwnProperty = Object.prototype.hasOwnProperty; function getNameFromProps(props) { return Object.keys(props).map(function(k) { return "".concat(k, ": ").concat(props[k].name); }).join(", "); } function useIdentity(codecs) { for (var i = 0; i < codecs.length; i++) { if (codecs[i].encode !== identity2) { return false; } } return true; } function getInterfaceTypeName(props) { return "{ ".concat(getNameFromProps(props), " }"); } function getPartialTypeName(inner) { return "Partial<".concat(inner, ">"); } function getUnionName(codecs) { return "(" + codecs.map(function(type2) { return type2.name; }).join(" | ") + ")"; } function mergeAll(base, us) { var equal = true; var primitive = true; var baseIsNotADictionary = !UnknownRecord.is(base); for (var _i = 0, us_1 = us; _i < us_1.length; _i++) { var u = us_1[_i]; if (u !== base) { equal = false; } if (UnknownRecord.is(u)) { primitive = false; } } if (equal) { return base; } else if (primitive) { return us[us.length - 1]; } var r = {}; for (var _a3 = 0, us_2 = us; _a3 < us_2.length; _a3++) { var u = us_2[_a3]; for (var k in u) { if (!hasOwnProperty.call(r, k) || baseIsNotADictionary || u[k] !== base[k]) { r[k] = u[k]; } } } return r; } function isNonEmpty2(as3) { return as3.length > 0; } var emptyTags = {}; function intersect(a, b) { var r = []; for (var _i = 0, a_1 = a; _i < a_1.length; _i++) { var v = a_1[_i]; if (b.indexOf(v) !== -1) { r.push(v); } } return r; } function mergeTags(a, b) { if (a === emptyTags) { return b; } if (b === emptyTags) { return a; } var r = Object.assign({}, a); for (var k in b) { if (hasOwnProperty.call(a, k)) { var intersection_1 = intersect(a[k], b[k]); if (isNonEmpty2(intersection_1)) { r[k] = intersection_1; } else { r = emptyTags; break; } } else { r[k] = b[k]; } } return r; } function intersectTags(a, b) { if (a === emptyTags || b === emptyTags) { return emptyTags; } var r = emptyTags; for (var k in a) { if (hasOwnProperty.call(b, k)) { var intersection_2 = intersect(a[k], b[k]); if (intersection_2.length === 0) { if (r === emptyTags) { r = {}; } r[k] = a[k].concat(b[k]); } } } return r; } function isLiteralC(codec) { return codec._tag === "LiteralType"; } function isTypeC(codec) { return codec._tag === "InterfaceType"; } function isStrictC(codec) { return codec._tag === "StrictType"; } function isExactC(codec) { return codec._tag === "ExactType"; } function isRefinementC(codec) { return codec._tag === "RefinementType"; } function isIntersectionC(codec) { return codec._tag === "IntersectionType"; } function isUnionC(codec) { return codec._tag === "UnionType"; } function isRecursiveC(codec) { return codec._tag === "RecursiveType"; } var lazyCodecs = []; function getTags(codec) { if (lazyCodecs.indexOf(codec) !== -1) { return emptyTags; } if (isTypeC(codec) || isStrictC(codec)) { var index = emptyTags; for (var k in codec.props) { var prop = codec.props[k]; if (isLiteralC(prop)) { if (index === emptyTags) { index = {}; } index[k] = [prop.value]; } } return index; } else if (isExactC(codec) || isRefinementC(codec)) { return getTags(codec.type); } else if (isIntersectionC(codec)) { return codec.types.reduce(function(tags2, codec2) { return mergeTags(tags2, getTags(codec2)); }, emptyTags); } else if (isUnionC(codec)) { return codec.types.slice(1).reduce(function(tags2, codec2) { return intersectTags(tags2, getTags(codec2)); }, getTags(codec.types[0])); } else if (isRecursiveC(codec)) { lazyCodecs.push(codec); var tags = getTags(codec.type); lazyCodecs.pop(); return tags; } return emptyTags; } function getIndex(codecs) { var tags = getTags(codecs[0]); var keys = Object.keys(tags); var len = codecs.length; var _loop_1 = function(k2) { var all = tags[k2].slice(); var index = [tags[k2]]; for (var i = 1; i < len; i++) { var codec = codecs[i]; var ctags = getTags(codec); var values = ctags[k2]; if (values === void 0) { return "continue-keys"; } else { if (values.some(function(v) { return all.indexOf(v) !== -1; })) { return "continue-keys"; } else { all.push.apply(all, values); index.push(values); } } } return { value: [k2, index] }; }; keys: for (var _i = 0, keys_1 = keys; _i < keys_1.length; _i++) { var k = keys_1[_i]; var state_1 = _loop_1(k); if (typeof state_1 === "object") return state_1.value; switch (state_1) { case "continue-keys": continue keys; } } return void 0; } var NullType = ( /** @class */ function(_super) { __extends(NullType2, _super); function NullType2() { var _this = _super.call(this, "null", function(u) { return u === null; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "NullType"; return _this; } return NullType2; }(Type) ); var nullType = new NullType(); var UndefinedType = ( /** @class */ function(_super) { __extends(UndefinedType2, _super); function UndefinedType2() { var _this = _super.call(this, "undefined", function(u) { return u === void 0; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "UndefinedType"; return _this; } return UndefinedType2; }(Type) ); var undefinedType = new UndefinedType(); var VoidType = ( /** @class */ function(_super) { __extends(VoidType2, _super); function VoidType2() { var _this = _super.call(this, "void", undefinedType.is, undefinedType.validate, identity2) || this; _this._tag = "VoidType"; return _this; } return VoidType2; }(Type) ); var voidType = new VoidType(); var UnknownType = ( /** @class */ function(_super) { __extends(UnknownType2, _super); function UnknownType2() { var _this = _super.call(this, "unknown", function(_) { return true; }, success, identity2) || this; _this._tag = "UnknownType"; return _this; } return UnknownType2; }(Type) ); var unknown = new UnknownType(); var StringType = ( /** @class */ function(_super) { __extends(StringType2, _super); function StringType2() { var _this = _super.call(this, "string", function(u) { return typeof u === "string"; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "StringType"; return _this; } return StringType2; }(Type) ); var string = new StringType(); var NumberType = ( /** @class */ function(_super) { __extends(NumberType2, _super); function NumberType2() { var _this = _super.call(this, "number", function(u) { return typeof u === "number"; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "NumberType"; return _this; } return NumberType2; }(Type) ); var number = new NumberType(); var BigIntType = ( /** @class */ function(_super) { __extends(BigIntType2, _super); function BigIntType2() { var _this = _super.call( this, "bigint", // tslint:disable-next-line: valid-typeof function(u) { return typeof u === "bigint"; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2 ) || this; _this._tag = "BigIntType"; return _this; } return BigIntType2; }(Type) ); var bigint = new BigIntType(); var BooleanType = ( /** @class */ function(_super) { __extends(BooleanType2, _super); function BooleanType2() { var _this = _super.call(this, "boolean", function(u) { return typeof u === "boolean"; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "BooleanType"; return _this; } return BooleanType2; }(Type) ); var boolean = new BooleanType(); var AnyArrayType = ( /** @class */ function(_super) { __extends(AnyArrayType2, _super); function AnyArrayType2() { var _this = _super.call(this, "UnknownArray", Array.isArray, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "AnyArrayType"; return _this; } return AnyArrayType2; }(Type) ); var UnknownArray = new AnyArrayType(); var AnyDictionaryType = ( /** @class */ function(_super) { __extends(AnyDictionaryType2, _super); function AnyDictionaryType2() { var _this = _super.call(this, "UnknownRecord", function(u) { return u !== null && typeof u === "object" && !Array.isArray(u); }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "AnyDictionaryType"; return _this; } return AnyDictionaryType2; }(Type) ); var UnknownRecord = new AnyDictionaryType(); var LiteralType = ( /** @class */ function(_super) { __extends(LiteralType2, _super); function LiteralType2(name, is, validate, encode3, value) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.value = value; _this._tag = "LiteralType"; return _this; } return LiteralType2; }(Type) ); function literal(value, name) { if (name === void 0) { name = JSON.stringify(value); } var is = function(u) { return u === value; }; return new LiteralType(name, is, function(u, c) { return is(u) ? success(value) : failure(u, c); }, identity2, value); } var KeyofType = ( /** @class */ function(_super) { __extends(KeyofType2, _super); function KeyofType2(name, is, validate, encode3, keys) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.keys = keys; _this._tag = "KeyofType"; return _this; } return KeyofType2; }(Type) ); function keyof(keys, name) { if (name === void 0) { name = Object.keys(keys).map(function(k) { return JSON.stringify(k); }).join(" | "); } var is = function(u) { return string.is(u) && hasOwnProperty.call(keys, u); }; return new KeyofType(name, is, function(u, c) { return is(u) ? success(u) : failure(u, c); }, identity2, keys); } var RefinementType = ( /** @class */ function(_super) { __extends(RefinementType2, _super); function RefinementType2(name, is, validate, encode3, type2, predicate) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.type = type2; _this.predicate = predicate; _this._tag = "RefinementType"; return _this; } return RefinementType2; }(Type) ); function brand(codec, predicate, name) { return refinement(codec, predicate, name); } var Int = brand(number, function(n) { return Number.isInteger(n); }, "Int"); var RecursiveType = ( /** @class */ function(_super) { __extends(RecursiveType2, _super); function RecursiveType2(name, is, validate, encode3, runDefinition) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.runDefinition = runDefinition; _this._tag = "RecursiveType"; return _this; } return RecursiveType2; }(Type) ); Object.defineProperty(RecursiveType.prototype, "type", { get: function() { return this.runDefinition(); }, enumerable: true, configurable: true }); var ArrayType = ( /** @class */ function(_super) { __extends(ArrayType2, _super); function ArrayType2(name, is, validate, encode3, type2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.type = type2; _this._tag = "ArrayType"; return _this; } return ArrayType2; }(Type) ); var InterfaceType = ( /** @class */ function(_super) { __extends(InterfaceType2, _super); function InterfaceType2(name, is, validate, encode3, props) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.props = props; _this._tag = "InterfaceType"; return _this; } return InterfaceType2; }(Type) ); function type(props, name) { if (name === void 0) { name = getInterfaceTypeName(props); } var keys = Object.keys(props); var types2 = keys.map(function(key) { return props[key]; }); var len = keys.length; return new InterfaceType(name, function(u) { if (UnknownRecord.is(u)) { for (var i = 0; i < len; i++) { var k = keys[i]; var uk = u[k]; if (uk === void 0 && !hasOwnProperty.call(u, k) || !types2[i].is(uk)) { return false; } } return true; } return false; }, function(u, c) { var e = UnknownRecord.validate(u, c); if (isLeft2(e)) { return e; } var o = e.right; var a = o; var errors = []; for (var i = 0; i < len; i++) { var k = keys[i]; var ak = a[k]; var type_1 = types2[i]; var result = type_1.validate(ak, appendContext(c, k, type_1, ak)); if (isLeft2(result)) { pushAll(errors, result.left); } else { var vak = result.right; if (vak !== ak || vak === void 0 && !hasOwnProperty.call(a, k)) { if (a === o) { a = __assign({}, o); } a[k] = vak; } } } return errors.length > 0 ? failures(errors) : success(a); }, useIdentity(types2) ? identity2 : function(a) { var s = __assign({}, a); for (var i = 0; i < len; i++) { var k = keys[i]; var encode3 = types2[i].encode; if (encode3 !== identity2) { s[k] = encode3(a[k]); } } return s; }, props); } var PartialType = ( /** @class */ function(_super) { __extends(PartialType2, _super); function PartialType2(name, is, validate, encode3, props) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.props = props; _this._tag = "PartialType"; return _this; } return PartialType2; }(Type) ); function partial(props, name) { if (name === void 0) { name = getPartialTypeName(getInterfaceTypeName(props)); } var keys = Object.keys(props); var types2 = keys.map(function(key) { return props[key]; }); var len = keys.length; return new PartialType(name, function(u) { if (UnknownRecord.is(u)) { for (var i = 0; i < len; i++) { var k = keys[i]; var uk = u[k]; if (uk !== void 0 && !props[k].is(uk)) { return false; } } return true; } return false; }, function(u, c) { var e = UnknownRecord.validate(u, c); if (isLeft2(e)) { return e; } var o = e.right; var a = o; var errors = []; for (var i = 0; i < len; i++) { var k = keys[i]; var ak = a[k]; var type_2 = props[k]; var result = type_2.validate(ak, appendContext(c, k, type_2, ak)); if (isLeft2(result)) { if (ak !== void 0) { pushAll(errors, result.left); } } else { var vak = result.right; if (vak !== ak) { if (a === o) { a = __assign({}, o); } a[k] = vak; } } } return errors.length > 0 ? failures(errors) : success(a); }, useIdentity(types2) ? identity2 : function(a) { var s = __assign({}, a); for (var i = 0; i < len; i++) { var k = keys[i]; var ak = a[k]; if (ak !== void 0) { s[k] = types2[i].encode(ak); } } return s; }, props); } var DictionaryType = ( /** @class */ function(_super) { __extends(DictionaryType2, _super); function DictionaryType2(name, is, validate, encode3, domain, codomain) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.domain = domain; _this.codomain = codomain; _this._tag = "DictionaryType"; return _this; } return DictionaryType2; }(Type) ); var UnionType = ( /** @class */ function(_super) { __extends(UnionType2, _super); function UnionType2(name, is, validate, encode3, types2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.types = types2; _this._tag = "UnionType"; return _this; } return UnionType2; }(Type) ); function union(codecs, name) { if (name === void 0) { name = getUnionName(codecs); } var index = getIndex(codecs); if (index !== void 0 && codecs.length > 0) { var tag_1 = index[0], groups_1 = index[1]; var len_1 = groups_1.length; var find_1 = function(value) { for (var i = 0; i < len_1; i++) { if (groups_1[i].indexOf(value) !== -1) { return i; } } return void 0; }; return new TaggedUnionType(name, function(u) { if (UnknownRecord.is(u)) { var i = find_1(u[tag_1]); return i !== void 0 ? codecs[i].is(u) : false; } return false; }, function(u, c) { var e = UnknownRecord.validate(u, c); if (isLeft2(e)) { return e; } var r = e.right; var i = find_1(r[tag_1]); if (i === void 0) { return failure(u, c); } var codec = codecs[i]; return codec.validate(r, appendContext(c, String(i), codec, r)); }, useIdentity(codecs) ? identity2 : function(a) { var i = find_1(a[tag_1]); if (i === void 0) { throw new Error("no codec found to encode value in union codec ".concat(name)); } else { return codecs[i].encode(a); } }, codecs, tag_1); } else { return new UnionType(name, function(u) { return codecs.some(function(type2) { return type2.is(u); }); }, function(u, c) { var errors = []; for (var i = 0; i < codecs.length; i++) { var codec = codecs[i]; var result = codec.validate(u, appendContext(c, String(i), codec, u)); if (isLeft2(result)) { pushAll(errors, result.left); } else { return success(result.right); } } return failures(errors); }, useIdentity(codecs) ? identity2 : function(a) { for (var _i = 0, codecs_1 = codecs; _i < codecs_1.length; _i++) { var codec = codecs_1[_i]; if (codec.is(a)) { return codec.encode(a); } } throw new Error("no codec found to encode value in union type ".concat(name)); }, codecs); } } var IntersectionType = ( /** @class */ function(_super) { __extends(IntersectionType2, _super); function IntersectionType2(name, is, validate, encode3, types2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.types = types2; _this._tag = "IntersectionType"; return _this; } return IntersectionType2; }(Type) ); function intersection(codecs, name) { if (name === void 0) { name = "(".concat(codecs.map(function(type2) { return type2.name; }).join(" & "), ")"); } var len = codecs.length; return new IntersectionType(name, function(u) { return codecs.every(function(type2) { return type2.is(u); }); }, codecs.length === 0 ? success : function(u, c) { var us = []; var errors = []; for (var i = 0; i < len; i++) { var codec = codecs[i]; var result = codec.validate(u, appendContext(c, String(i), codec, u)); if (isLeft2(result)) { pushAll(errors, result.left); } else { us.push(result.right); } } return errors.length > 0 ? failures(errors) : success(mergeAll(u, us)); }, codecs.length === 0 ? identity2 : function(a) { return mergeAll(a, codecs.map(function(codec) { return codec.encode(a); })); }, codecs); } var TupleType = ( /** @class */ function(_super) { __extends(TupleType2, _super); function TupleType2(name, is, validate, encode3, types2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.types = types2; _this._tag = "TupleType"; return _this; } return TupleType2; }(Type) ); var ReadonlyType = ( /** @class */ function(_super) { __extends(ReadonlyType2, _super); function ReadonlyType2(name, is, validate, encode3, type2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.type = type2; _this._tag = "ReadonlyType"; return _this; } return ReadonlyType2; }(Type) ); var ReadonlyArrayType = ( /** @class */ function(_super) { __extends(ReadonlyArrayType2, _super); function ReadonlyArrayType2(name, is, validate, encode3, type2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.type = type2; _this._tag = "ReadonlyArrayType"; return _this; } return ReadonlyArrayType2; }(Type) ); var ExactType = ( /** @class */ function(_super) { __extends(ExactType2, _super); function ExactType2(name, is, validate, encode3, type2) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.type = type2; _this._tag = "ExactType"; return _this; } return ExactType2; }(Type) ); var FunctionType = ( /** @class */ function(_super) { __extends(FunctionType2, _super); function FunctionType2() { var _this = _super.call( this, "Function", // tslint:disable-next-line:strict-type-predicates function(u) { return typeof u === "function"; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2 ) || this; _this._tag = "FunctionType"; return _this; } return FunctionType2; }(Type) ); var Function2 = new FunctionType(); var NeverType = ( /** @class */ function(_super) { __extends(NeverType2, _super); function NeverType2() { var _this = _super.call( this, "never", function(_) { return false; }, function(u, c) { return failure(u, c); }, /* istanbul ignore next */ function() { throw new Error("cannot encode never"); } ) || this; _this._tag = "NeverType"; return _this; } return NeverType2; }(Type) ); var never = new NeverType(); var AnyType = ( /** @class */ function(_super) { __extends(AnyType2, _super); function AnyType2() { var _this = _super.call(this, "any", function(_) { return true; }, success, identity2) || this; _this._tag = "AnyType"; return _this; } return AnyType2; }(Type) ); var any = new AnyType(); function refinement(codec, predicate, name) { if (name === void 0) { name = "(".concat(codec.name, " | ").concat(getFunctionName(predicate), ")"); } return new RefinementType(name, function(u) { return codec.is(u) && predicate(u); }, function(i, c) { var e = codec.validate(i, c); if (isLeft2(e)) { return e; } var a = e.right; return predicate(a) ? success(a) : failure(a, c); }, codec.encode, codec, predicate); } var Integer = refinement(number, Number.isInteger, "Integer"); var TaggedUnionType = ( /** @class */ function(_super) { __extends(TaggedUnionType2, _super); function TaggedUnionType2(name, is, validate, encode3, codecs, tag) { var _this = _super.call(this, name, is, validate, encode3, codecs) || this; _this.tag = tag; return _this; } return TaggedUnionType2; }(UnionType) ); var ObjectType = ( /** @class */ function(_super) { __extends(ObjectType2, _super); function ObjectType2() { var _this = _super.call(this, "object", function(u) { return u !== null && typeof u === "object"; }, function(u, c) { return _this.is(u) ? success(u) : failure(u, c); }, identity2) || this; _this._tag = "ObjectType"; return _this; } return ObjectType2; }(Type) ); var object = new ObjectType(); var StrictType = ( /** @class */ function(_super) { __extends(StrictType2, _super); function StrictType2(name, is, validate, encode3, props) { var _this = _super.call(this, name, is, validate, encode3) || this; _this.props = props; _this._tag = "StrictType"; return _this; } return StrictType2; }(Type) ); // node_modules/io-ts/es6/PathReporter.js function stringify(v) { if (typeof v === "function") { return getFunctionName(v); } if (typeof v === "number" && !isFinite(v)) { if (isNaN(v)) { return "NaN"; } return v > 0 ? "Infinity" : "-Infinity"; } return JSON.stringify(v); } function getContextPath(context) { return context.map(function(_a3) { var key = _a3.key, type2 = _a3.type; return "".concat(key, ": ").concat(type2.name); }).join("/"); } function getMessage(e) { return e.message !== void 0 ? e.message : "Invalid value ".concat(stringify(e.value), " supplied to ").concat(getContextPath(e.context)); } function failure2(es) { return es.map(getMessage); } function success2() { return ["No errors!"]; } var PathReporter = { report: fold(failure2, success2) }; // src/prompt.ts var import_obsidian = require("obsidian"); // src/mark.ts var LINE_BREAK = " \n"; var USER_MARK_START = "\u2728\u{1F4A1}"; var USER_MARK_END = "\u{1F4A1}\u2728"; var ASSISTANT_MARK_START = "\u2728\u{1F4AC}"; var ASSISTANT_MARK_END = "\u{1F4AC}\u2728"; var ERROR_MARK = "\u274C"; var isUserMarkStart = (line) => line.trim() === USER_MARK_START && line.length - line.trimStart().length <= 2; var isUserMarkEnd = (line) => line.trim() === USER_MARK_END && line.length - line.trimStart().length <= 2; var isAssistantMarkStart = (line) => line.trim() === ASSISTANT_MARK_START && line.length - line.trimStart().length <= 2; var isAssistantMarkEnd = (line) => line.trim() === ASSISTANT_MARK_END && line.length - line.trimStart().length <= 2; var isMarkStart = (line) => isUserMarkStart(line) || isAssistantMarkStart(line); var isMarkEnd = (line) => isUserMarkEnd(line) || isAssistantMarkEnd(line); var isMark = (line) => isMarkStart(line) || isMarkEnd(line); var isHorizontalRuler = (line) => /^[ ]{0,3}([-*_])\s*(?:\1\s*){2,}$/gm.test(line); // src/prompt.ts var Glm4 = "glm-4"; var ImageGenerateParams = type({ model: literal("cogview-3") }); var ChatParams = partial({ multiRound: boolean, model: keyof({ "glm-4": null, "glm-4-0520": null, "glm-4-air": null, "glm-4-flash": null, "glm-3-turbo": null }), temperature: number, top_p: number, max_tokens: number }); var KnowledgeChatParams = intersection([ ChatParams, type({ knowledge_id: string, prompt_template: string }) ]); var ApiParams = union([ImageGenerateParams, ChatParams, KnowledgeChatParams]); var getTemplates = (fileContent) => { const lines = fileContent.split("\n").map((el, index) => { return { content: el, index }; }); const dividers = lines.filter((line) => isHorizontalRuler(line.content)); const slidesLines = dividers.map( (divider, index) => lines.slice(divider.index + 1, dividers[index + 1] ? dividers[index + 1].index : void 0) ); const templates = slidesLines.map((slide) => parseTemplate(slide)).filter((el) => el !== null); return templates; }; var parseTemplate = (lines) => { const headerIndex = lines.findIndex((line) => line.content.startsWith("## ")); if (headerIndex === -1) { return null; } const title = lines.slice(headerIndex, headerIndex + 1).map((line) => line.content.slice(3)).join("\n").trim(); const commentStart = lines.findIndex((line) => line.content === "%%"); const commentEnd = lines.findLastIndex((line) => line.content === "%%"); let commentRaw = void 0; if (commentStart != -1 && commentEnd > commentStart + 1) { commentRaw = lines.slice(commentStart + 1, commentEnd).map((line) => line.content).join("\n").trim(); } console.debug("commentRaw", commentRaw); const defaultParams = { model: Glm4, multiRound: false }; const params = commentRaw ? parseComment(commentRaw) || defaultParams : defaultParams; if (!params.model) { params.model = Glm4; } const promptStart = lines.findIndex((line) => isUserMarkStart(line.content)); const promptEnd = lines.findLastIndex((line) => isUserMarkEnd(line.content)); if (promptStart === -1 || promptEnd === -1 || promptEnd <= promptStart) { return null; } const prompt = lines.slice(promptStart + 1, promptEnd).map((line) => line.content).join("\n").trim(); return { title, params, template: prompt }; }; var parseComment = (comment) => { try { const commentObject = (0, import_obsidian.parseYaml)(comment); const decoded = ApiParams.decode(commentObject); if (isLeft2(decoded)) { throw Error(`Could not validate data: ${PathReporter.report(decoded).join("\n")}`); } return decoded.right; } catch (e) { console.error("parseComment", e); return void 0; } }; // src/apiCall.ts var newApiCallInfo = (template, messages) => { return { template, messages, result: null, error: null, usage: null, startTime: new Date(), endTime: null }; }; var toChatCompletionStreamParams = (info) => { if (info.template.params.model === "cogview-3") { throw new Error("Not supported"); } const { model = Glm4, temperature, top_p, max_tokens } = info.template.params; return { model, messages: info.messages, temperature, top_p, max_tokens }; }; // src/lang/locale/ar.ts var ar_default = {}; // src/lang/locale/cz.ts var cz_default = {}; // src/lang/locale/da.ts var da_default = {}; // src/lang/locale/de.ts var de_default = {}; // node_modules/ts-dedent/esm/index.js function dedent(templ) { var values = []; for (var _i = 1; _i < arguments.length; _i++) { values[_i - 1] = arguments[_i]; } var strings = Array.from(typeof templ === "string" ? [templ] : templ); strings[strings.length - 1] = strings[strings.length - 1].replace(/\r?\n([\t ]*)$/, ""); var indentLengths = strings.reduce(function(arr, str2) { var matches = str2.match(/\n([\t ]+|(?!\s).)/g); if (matches) { return arr.concat(matches.map(function(match2) { var _a3, _b2; return (_b2 = (_a3 = match2.match(/[\t ]/g)) === null || _a3 === void 0 ? void 0 : _a3.length) !== null && _b2 !== void 0 ? _b2 : 0; })); } return arr; }, []); if (indentLengths.length) { var pattern_1 = new RegExp("\n[ ]{" + Math.min.apply(Math, indentLengths) + "}", "g"); strings = strings.map(function(str2) { return str2.replace(pattern_1, "\n"); }); } strings[0] = strings[0].replace(/^\r?\n/, ""); var string2 = strings[0]; values.forEach(function(value, i) { var endentations = string2.match(/(?:^|\n)( *)$/); var endentation = endentations ? endentations[1] : ""; var indentedValue = value; if (typeof value === "string" && value.includes("\n")) { indentedValue = String(value).split("\n").map(function(str2, i2) { return i2 === 0 ? str2 : "" + endentation + str2; }).join("\n"); } string2 += indentedValue + strings[i + 1]; }); return string2; } var esm_default = dedent; // src/lang/locale/en.ts var en_default = { // command "Generate from the selected text / line / block": "Generate from the selected text / line / block", "Select \u2728block\u2728": "Select \u2728block\u2728", "Show the chat details": "Show the chat details", "Open prompt template file": "Open prompt template file", // block.ts "Expect start mark, but found end mark at line ": "Expect start mark, but found end mark at line ", // main.ts "Cannot find a valid block.": "Cannot find a valid block.", "No chat in this session yet.": "No chat in this session yet.", "Cannot find prompt template file.": "Cannot find prompt template file.", "Create template folder": "Create template folder", "Create template file": "Create template file", "ZhipuAI API Key is not provided.": "ZhipuAI API Key is not provided.", "Nothing was selected": "Nothing was selected", "This is the block for generating content. Copy the selected text outside of this block, and then execute the command.": "This is the block for generating content. Copy the selected text outside of this block, and then execute the command.", "Block is empty": "Block is empty", "Regenerate block": "Regenerate block", "Failed to generate image": "Failed to generate image", Round: "Round", "generate content": "generate content", // settingTab.ts "Zhipu API key": "Zhipu API key", "Obtain key from https://open.bigmodel.cn": "Obtain key from https://open.bigmodel.cn", "Enter your key": "Enter your key", "Single Round Conversation": "Single Round Conversation", "Prompt template file": "Prompt template file", "Template file support both Chinese and English languages, with the default being the software's language setting.": "Template file support both Chinese and English languages, with the default being the software's language setting.", PromptTemplates: "PromptTemplates", 'The starting mark of Multi-round conversation is two consecutive lines of horizontal dashes, such as two lines of "---", and the ending mark is a single line of horizontal dashes.': 'The starting mark of Multi-round conversation is two consecutive lines of horizontal dashes, such as two lines of "---", and the ending mark is a single line of horizontal dashes.', "Sampling temperature controls the randomness of the output. A higher value makes the output more random and creative; a lower value makes the output more stable or deterministic.": "Sampling temperature controls the randomness of the output. A higher value makes the output more random and creative; a lower value makes the output more stable or deterministic.", "0.1 means that the model decoder only considers taking tokens from the candidate set of the top 10% probability.": "0.1 means that the model decoder only considers taking tokens from the candidate set of the top 10% probability.", "The maximum number of tokens to generate in the completion": "The maximum number of tokens to generate in the completion", // modal.ts Messages: "Messages", "Multi-round Conversation": "Multi-round Conversation", "Generate content": "Generate content", "Last used": "Last used", TimeInfoTemplate: esm_default` 🚀 Begin : \${startTime} 🏁 Finish: \${endTime} ⌛ Total : \${duration}`, UsageInfoTemplate: esm_default` 💡 Prompt tokens: \${prompt_tokens} 💬 Comp. tokens: \${completion_tokens} ✨ Total tokens: \${total_tokens}` }; // src/lang/locale/es.ts var es_default = {}; // src/lang/locale/fr.ts var fr_default = {}; // src/lang/locale/hi.ts var hi_default = {}; // src/lang/locale/id.ts var id_default = {}; // src/lang/locale/it.ts var it_default = {}; // src/lang/locale/ja.ts var ja_default = {}; // src/lang/locale/ko.ts var ko_default = {}; // src/lang/locale/nl.ts var nl_default = {}; // src/lang/locale/no.ts var no_default = {}; // src/lang/locale/pl.ts var pl_default = {}; // src/lang/locale/pt.ts var pt_default = {}; // src/lang/locale/pt-br.ts var pt_br_default = {}; // src/lang/locale/ro.ts var ro_default = {}; // src/lang/locale/ru.ts var ru_default = {}; // src/lang/locale/sq.ts var sq_default = {}; // src/lang/locale/tr.ts var tr_default = {}; // src/lang/locale/zh-cn.ts var zh_cn_default = { // command "Generate from the selected text / line / block": "\u751F\u6210\u5185\u5BB9\uFF08\u57FA\u4E8E\u9009\u4E2D\u7684\u6587\u672C\u3001\u884C\u3001\u533A\u5757\uFF09", "Select \u2728block\u2728": "\u9009\u53D6 \u2728\u533A\u5757\u2728", "Show the chat details": "\u663E\u793A\u5BF9\u8BDD\u8BE6\u60C5", "Open prompt template file": "\u6253\u5F00\u63D0\u793A\u8BCD\u6A21\u677F\u6587\u4EF6", // block.ts "Expect start mark, but found end mark at line ": "\u8981\u627E\u5F00\u59CB\u6807\u8BB0\uFF0C\u7136\u800C\u662F\u7ED3\u675F\u6807\u8BB0\uFF0C\u884C\u53F7\uFF1A", // main.ts "Cannot find a valid block.": "\u627E\u4E0D\u5230\u6709\u6548\u7684\u533A\u5757", "No chat in this session yet.": "\u672C\u6B21\u4F1A\u8BDD\u4E2D\u8FD8\u6CA1\u6709\u5BF9\u8BDD", "Cannot find prompt template file.": "\u627E\u4E0D\u5230\u63D0\u793A\u8BCD\u6A21\u677F\u6587\u4EF6", "Create template folder": "\u521B\u5EFA\u6A21\u7248\u6587\u4EF6\u5939", "Create template file": "\u521B\u5EFA\u6A21\u677F\u6587\u4EF6", "ZhipuAI API Key is not provided.": "\u8BF7\u5148\u8BBE\u7F6E\u667A\u8C31AI\u7684 API Key", "Nothing was selected": "\u8BF7\u5148\u9009\u5B9A\u6587\u672C", "This is the block for generating content. Copy the selected text outside of this block, and then execute the command.": "\u8FD9\u662F\u751F\u6210\u5185\u5BB9\u7684\u533A\u5757\u3002\u628A\u9009\u4E2D\u7684\u6587\u672C\u590D\u5236\u5230\u8FD9\u4E2A\u533A\u5757\u5916\u9762\uFF0C\u518D\u6267\u884C\u547D\u4EE4\u3002", "Block is empty": "\u533A\u5757\u662F\u7A7A\u7684", "Regenerate block": "\u91CD\u65B0\u751F\u6210\u533A\u5757", "Failed to generate image": "\u751F\u6210\u56FE\u7247\u5931\u8D25", Round: "\u7B2C", "generate content": "\u8F6E\u751F\u6210\u5185\u5BB9", // settingTab.ts "Zhipu API key": "\u667A\u8C31 API key", "Obtain key from https://open.bigmodel.cn": "\u4ECE https://open.bigmodel.cn \u83B7\u53D6 key", "Enter your key": "\u8F93\u5165\u4F60\u7684 key", "Single Round Conversation": "\u5355\u8F6E\u4F1A\u8BDD", "Prompt template file": "\u63D0\u793A\u8BCD\u6A21\u677F\u6587\u4EF6", "Template file support both Chinese and English languages, with the default being the software's language setting.": "\u6A21\u7248\u6587\u4EF6\u652F\u6301\u4E2D\u6587\u8BED\u8A00\u548C\u82F1\u6587\u8BED\u8A00\uFF0C\u9ED8\u8BA4\u662F\u8F6F\u4EF6\u7684\u8BED\u8A00\u8BBE\u7F6E", PromptTemplates: "\u63D0\u793A\u8BCD\u6A21\u677F", 'The starting mark of Multi-round conversation is two consecutive lines of horizontal dashes, such as two lines of "---", and the ending mark is a single line of horizontal dashes.': "\u591A\u8F6E\u4F1A\u8BDD\u7684\u5F00\u59CB\u6807\u8BB0\u662F\u8FDE\u7EED\u4E24\u884C\u7684\u6C34\u5E73\u7EBF\uFF0C\u4F8B\u5982\u4E24\u884C\u7684\u201C---\u201D\uFF0C\u7ED3\u675F\u6807\u8BB0\u662F\u4E00\u884C\u6C34\u5E73\u7EBF", "Sampling temperature controls the randomness of the output. A higher value makes the output more random and creative; a lower value makes the output more stable or deterministic.": "\u91C7\u6837\u6E29\u5EA6\uFF0C\u63A7\u5236\u8F93\u51FA\u7684\u968F\u673A\u6027\u3002\u503C\u8D8A\u5927\uFF0C\u4F1A\u4F7F\u8F93\u51FA\u66F4\u968F\u673A\uFF0C\u66F4\u5177\u521B\u9020\u6027\uFF1B\u503C\u8D8A\u5C0F\uFF0C\u8F93\u51FA\u4F1A\u66F4\u52A0\u7A33\u5B9A\u6216\u786E\u5B9A", "0.1 means that the model decoder only considers taking tokens from the candidate set of the top 10% probability.": "\u6838\u53D6\u6837\u30020.1 \u610F\u5473\u7740\u6A21\u578B\u89E3\u7801\u5668\u53EA\u8003\u8651\u4ECE\u524D 10% \u7684\u6982\u7387\u7684\u5019\u9009\u96C6\u4E2D\u53D6 tokens", "The maximum number of tokens to generate in the completion": "\u6A21\u578B\u8F93\u51FA\u6700\u5927 tokens", // modal.ts Messages: "\u53D1\u9001\u6D88\u606F", "Multi-round Conversation": "\u591A\u8F6E\u4F1A\u8BDD", "Generate content": "\u751F\u6210\u5185\u5BB9", "Last used": "\u4E0A\u6B21\u4F7F\u7528", TimeInfoTemplate: esm_default` 🚀 开始:\${startTime} 🏁 结束:\${endTime} ⌛ 耗时:\${duration}`, UsageInfoTemplate: esm_default` 💡 用户输入 tokens:\${prompt_tokens} 💬 模型输入 tokens:\${completion_tokens} ✨ 合计数量 tokens:\${total_tokens}` }; // src/lang/locale/zh-tw.ts var zh_tw_default = {}; // src/lang/helper.ts var localeMap = { ar: ar_default, cz: cz_default, da: da_default, de: de_default, en: en_default, es: es_default, fr: fr_default, hi: hi_default, id: id_default, it: it_default, ja: ja_default, ko: ko_default, nl: nl_default, no: no_default, pl: pl_default, "pt-BR": pt_br_default, pt: pt_default, ro: ro_default, ru: ru_default, sq: sq_default, tr: tr_default, uk: tr_default, "zh-TW": zh_tw_default, zh: zh_cn_default }; var lang = window.localStorage.getItem("language"); var locale = localeMap[lang || "en"]; function t(str2) { if (!locale) { console.error("Error: ai zhipu locale not found", lang); } return locale && locale[str2] || en_default[str2]; } var promptEnFileName = en_default["PromptTemplates"]; var promptZhFileName = zh_cn_default["PromptTemplates"]; // src/block.ts var findMultiRoundRange = (lines, end) => { let l = end; for (; l >= 0; l--) { if (isHorizontalRuler(lines[l])) break; } if (l >= 1 && isHorizontalRuler(lines[l - 1])) { return { _tag: "multiRoundRange", start: l + 1, end: end - 1 }; } return null; }; var findPreMsgBlocks = (lines, start, end) => { let i = start; for (; i < lines.length; i++) { if (isMark(lines[i])) { if (isMarkEnd(lines[i])) { throw new Error(t("Expect start mark, but found end mark at line ") + (i + 1)); } break; } } const blocks = []; do { const block = findMsgBlock(lines, i, end); if (block === null) break; blocks.push(block); i = block.end + 1; } while (i < end); return blocks; }; var findMsgBlock = (lines, start, end) => { let l = start; for (; l < end; l++) { if (isMarkStart(lines[l])) break; if (isMarkEnd(lines[l])) return null; } if (l === end) return null; const blockStart = l; l++; for (; l < end; l++) { if (isMarkEnd(lines[l])) break; if (isMarkStart(lines[l])) return null; } if (l === end || l <= blockStart + 1) return null; const content = lines.slice(blockStart + 1, l).join("\n"); if (isUserMarkStart(lines[blockStart]) && isUserMarkEnd(lines[l])) return { _tag: "user", content, start: blockStart, end: l }; if (isAssistantMarkStart(lines[blockStart]) && isAssistantMarkEnd(lines[l])) return { _tag: "assistant", content, start: blockStart, end: l }; return null; }; var findBlockByCurrentLine = (lines, current) => { let start = isMarkEnd(lines[current]) ? current - 1 : current; for (; start >= 0; start--) { if (isMarkStart(lines[start])) break; if (isMarkEnd(lines[start])) return null; } console.debug("start", start, lines[start]); let end = start === current ? current + 1 : current; for (; end < lines.length; end++) { if (isMarkEnd(lines[end])) break; if (isMarkStart(lines[end])) return null; } console.debug("end", end, lines[end]); if (start === -1 || end === lines.length) { return null; } const content = lines.slice(start + 1, end).join("\n"); if (isUserMarkStart(lines[start]) && isUserMarkEnd(lines[end])) return { _tag: "user", content, start, end }; if (isAssistantMarkStart(lines[start]) && isAssistantMarkEnd(lines[end])) return { _tag: "assistant", content, start, end }; return null; }; var findNextEmptyAssistBlock = (lines, from) => { let l = from; let start = -1; for (; l < lines.length; l++) { if (isAssistantMarkStart(lines[l])) { start = l; break; } if (lines[l].trim().length > 0) { return null; } if (l > from + 2) { return null; } } if (start === -1) return null; console.debug("start", start, lines[start]); let end = -1; for (l = start + 1; l < lines.length; l++) { if (isAssistantMarkEnd(lines[l])) { end = l; break; } if (lines[l].trim().length > 0) { return null; } if (l > start + 3) { return null; } } if (end > start) return { start, end }; return null; }; // node_modules/openai/version.mjs var VERSION = "4.25.0"; // node_modules/openai/_shims/registry.mjs var auto = false; var kind = void 0; var fetch2 = void 0; var Request2 = void 0; var Response2 = void 0; var Headers2 = void 0; var FormData2 = void 0; var Blob2 = void 0; var File2 = void 0; var ReadableStream2 = void 0; var getMultipartRequestOptions = void 0; var getDefaultAgent = void 0; var fileFromPath = void 0; var isFsReadStream = void 0; function setShims(shims, options = { auto: false }) { if (auto) { throw new Error(`you must \`import 'openai/shims/${shims.kind}'\` before importing anything else from openai`); } if (kind) { throw new Error(`can't \`import 'openai/shims/${shims.kind}'\` after \`import 'openai/shims/${kind}'\``); } auto = options.auto; kind = shims.kind; fetch2 = shims.fetch; Request2 = shims.Request; Response2 = shims.Response; Headers2 = shims.Headers; FormData2 = shims.FormData; Blob2 = shims.Blob; File2 = shims.File; ReadableStream2 = shims.ReadableStream; getMultipartRequestOptions = shims.getMultipartRequestOptions; getDefaultAgent = shims.getDefaultAgent; fileFromPath = shims.fileFromPath; isFsReadStream = shims.isFsReadStream; } // node_modules/openai/_shims/MultipartBody.mjs var MultipartBody = class { constructor(body) { this.body = body; } get [Symbol.toStringTag]() { return "MultipartBody"; } }; // node_modules/openai/_shims/web-runtime.mjs function getRuntime({ manuallyImported } = {}) { const recommendation = manuallyImported ? `You may need to use polyfills` : `Add one of these imports before your first \`import \u2026 from 'openai'\`: - \`import 'openai/shims/node'\` (if you're running on Node) - \`import 'openai/shims/web'\` (otherwise) `; let _fetch, _Request, _Response, _Headers; try { _fetch = fetch; _Request = Request; _Response = Response; _Headers = Headers; } catch (error) { throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`); } return { kind: "web", fetch: _fetch, Request: _Request, Response: _Response, Headers: _Headers, FormData: ( // @ts-ignore typeof FormData !== "undefined" ? FormData : class FormData { // @ts-ignore constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`); } } ), Blob: typeof Blob !== "undefined" ? Blob : class Blob { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`); } }, File: ( // @ts-ignore typeof File !== "undefined" ? File : class File { // @ts-ignore constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`); } } ), ReadableStream: ( // @ts-ignore typeof ReadableStream !== "undefined" ? ReadableStream : class ReadableStream { // @ts-ignore constructor() { throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`); } } ), getMultipartRequestOptions: async (form, opts) => ({ ...opts, body: new MultipartBody(form) }), getDefaultAgent: (url) => void 0, fileFromPath: () => { throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads"); }, isFsReadStream: (value) => false }; } // node_modules/openai/_shims/index.mjs if (!kind) setShims(getRuntime(), { auto: true }); // node_modules/openai/error.mjs var error_exports = {}; __export(error_exports, { APIConnectionError: () => APIConnectionError, APIConnectionTimeoutError: () => APIConnectionTimeoutError, APIError: () => APIError, APIUserAbortError: () => APIUserAbortError, AuthenticationError: () => AuthenticationError, BadRequestError: () => BadRequestError, ConflictError: () => ConflictError, InternalServerError: () => InternalServerError, NotFoundError: () => NotFoundError, OpenAIError: () => OpenAIError, PermissionDeniedError: () => PermissionDeniedError, RateLimitError: () => RateLimitError, UnprocessableEntityError: () => UnprocessableEntityError }); var OpenAIError = class extends Error { }; var APIError = class extends OpenAIError { constructor(status, error, message2, headers) { super(`${APIError.makeMessage(status, error, message2)}`); this.status = status; this.headers = headers; const data = error; this.error = data; this.code = data == null ? void 0 : data["code"]; this.param = data == null ? void 0 : data["param"]; this.type = data == null ? void 0 : data["type"]; } static makeMessage(status, error, message2) { const msg = (error == null ? void 0 : error.message) ? typeof error.message === "string" ? error.message : JSON.stringify(error.message) : error ? JSON.stringify(error) : message2; if (status && msg) { return `${status} ${msg}`; } if (status) { return `${status} status code (no body)`; } if (msg) { return msg; } return "(no status code or body)"; } static generate(status, errorResponse, message2, headers) { if (!status) { return new APIConnectionError({ cause: castToError(errorResponse) }); } const error = errorResponse == null ? void 0 : errorResponse["error"]; if (status === 400) { return new BadRequestError(status, error, message2, headers); } if (status === 401) { return new AuthenticationError(status, error, message2, headers); } if (status === 403) { return new PermissionDeniedError(status, error, message2, headers); } if (status === 404) { return new NotFoundError(status, error, message2, headers); } if (status === 409) { return new ConflictError(status, error, message2, headers); } if (status === 422) { return new UnprocessableEntityError(status, error, message2, headers); } if (status === 429) { return new RateLimitError(status, error, message2, headers); } if (status >= 500) { return new InternalServerError(status, error, message2, headers); } return new APIError(status, error, message2, headers); } }; var APIUserAbortError = class extends APIError { constructor({ message: message2 } = {}) { super(void 0, void 0, message2 || "Request was aborted.", void 0); this.status = void 0; } }; var APIConnectionError = class extends APIError { constructor({ message: message2, cause }) { super(void 0, void 0, message2 || "Connection error.", void 0); this.status = void 0; if (cause) this.cause = cause; } }; var APIConnectionTimeoutError = class extends APIConnectionError { constructor({ message: message2 } = {}) { super({ message: message2 != null ? message2 : "Request timed out." }); } }; var BadRequestError = class extends APIError { constructor() { super(...arguments); this.status = 400; } }; var AuthenticationError = class extends APIError { constructor() { super(...arguments); this.status = 401; } }; var PermissionDeniedError = class extends APIError { constructor() { super(...arguments); this.status = 403; } }; var NotFoundError = class extends APIError { constructor() { super(...arguments); this.status = 404; } }; var ConflictError = class extends APIError { constructor() { super(...arguments); this.status = 409; } }; var UnprocessableEntityError = class extends APIError { constructor() { super(...arguments); this.status = 422; } }; var RateLimitError = class extends APIError { constructor() { super(...arguments); this.status = 429; } }; var InternalServerError = class extends APIError { }; // node_modules/openai/streaming.mjs var Stream = class { constructor(iterator, controller) { this.iterator = iterator; this.controller = controller; } static fromSSEResponse(response, controller) { let consumed = false; const decoder2 = new SSEDecoder(); async function* iterMessages() { if (!response.body) { controller.abort(); throw new OpenAIError(`Attempted to iterate over a response with no body`); } const lineDecoder = new LineDecoder(); const iter = readableStreamAsyncIterable(response.body); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { const sse = decoder2.decode(line); if (sse) yield sse; } } for (const line of lineDecoder.flush()) { const sse = decoder2.decode(line); if (sse) yield sse; } } async function* iterator() { if (consumed) { throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); } consumed = true; let done = false; try { for await (const sse of iterMessages()) { if (done) continue; if (sse.data.startsWith("[DONE]")) { done = true; continue; } if (sse.event === null) { let data; try { data = JSON.parse(sse.data); } catch (e) { console.error(`Could not parse message into JSON:`, sse.data); console.error(`From chunk:`, sse.raw); throw e; } if (data && data.error) { throw new APIError(void 0, data.error, void 0, void 0); } yield data; } } done = true; } catch (e) { if (e instanceof Error && e.name === "AbortError") return; throw e; } finally { if (!done) controller.abort(); } } return new Stream(iterator, controller); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ static fromReadableStream(readableStream, controller) { let consumed = false; async function* iterLines() { const lineDecoder = new LineDecoder(); const iter = readableStreamAsyncIterable(readableStream); for await (const chunk of iter) { for (const line of lineDecoder.decode(chunk)) { yield line; } } for (const line of lineDecoder.flush()) { yield line; } } async function* iterator() { if (consumed) { throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); } consumed = true; let done = false; try { for await (const line of iterLines()) { if (done) continue; if (line) yield JSON.parse(line); } done = true; } catch (e) { if (e instanceof Error && e.name === "AbortError") return; throw e; } finally { if (!done) controller.abort(); } } return new Stream(iterator, controller); } [Symbol.asyncIterator]() { return this.iterator(); } /** * Splits the stream into two streams which can be * independently read from at different speeds. */ tee() { const left3 = []; const right3 = []; const iterator = this.iterator(); const teeIterator = (queue) => { return { next: () => { if (queue.length === 0) { const result = iterator.next(); left3.push(result); right3.push(result); } return queue.shift(); } }; }; return [ new Stream(() => teeIterator(left3), this.controller), new Stream(() => teeIterator(right3), this.controller) ]; } /** * Converts this stream to a newline-separated ReadableStream of * JSON stringified values in the stream * which can be turned back into a Stream with `Stream.fromReadableStream()`. */ toReadableStream() { const self = this; let iter; const encoder2 = new TextEncoder(); return new ReadableStream2({ async start() { iter = self[Symbol.asyncIterator](); }, async pull(ctrl) { try { const { value, done } = await iter.next(); if (done) return ctrl.close(); const bytes = encoder2.encode(JSON.stringify(value) + "\n"); ctrl.enqueue(bytes); } catch (err) { ctrl.error(err); } }, async cancel() { var _a3; await ((_a3 = iter.return) == null ? void 0 : _a3.call(iter)); } }); } }; var SSEDecoder = class { constructor() { this.event = null; this.data = []; this.chunks = []; } decode(line) { if (line.endsWith("\r")) { line = line.substring(0, line.length - 1); } if (!line) { if (!this.event && !this.data.length) return null; const sse = { event: this.event, data: this.data.join("\n"), raw: this.chunks }; this.event = null; this.data = []; this.chunks = []; return sse; } this.chunks.push(line); if (line.startsWith(":")) { return null; } let [fieldname, _, value] = partition(line, ":"); if (value.startsWith(" ")) { value = value.substring(1); } if (fieldname === "event") { this.event = value; } else if (fieldname === "data") { this.data.push(value); } return null; } }; var LineDecoder = class { constructor() { this.buffer = []; this.trailingCR = false; } decode(chunk) { let text = this.decodeText(chunk); if (this.trailingCR) { text = "\r" + text; this.trailingCR = false; } if (text.endsWith("\r")) { this.trailingCR = true; text = text.slice(0, -1); } if (!text) { return []; } const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || ""); let lines = text.split(LineDecoder.NEWLINE_REGEXP); if (lines.length === 1 && !trailingNewline) { this.buffer.push(lines[0]); return []; } if (this.buffer.length > 0) { lines = [this.buffer.join("") + lines[0], ...lines.slice(1)]; this.buffer = []; } if (!trailingNewline) { this.buffer = [lines.pop() || ""]; } return lines; } decodeText(bytes) { var _a3; if (bytes == null) return ""; if (typeof bytes === "string") return bytes; if (typeof Buffer !== "undefined") { if (bytes instanceof Buffer) { return bytes.toString(); } if (bytes instanceof Uint8Array) { return Buffer.from(bytes).toString(); } throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`); } if (typeof TextDecoder !== "undefined") { if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) { (_a3 = this.textDecoder) != null ? _a3 : this.textDecoder = new TextDecoder("utf8"); return this.textDecoder.decode(bytes); } throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`); } throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`); } flush() { if (!this.buffer.length && !this.trailingCR) { return []; } const lines = [this.buffer.join("")]; this.buffer = []; this.trailingCR = false; return lines; } }; LineDecoder.NEWLINE_CHARS = /* @__PURE__ */ new Set(["\n", "\r", "\v", "\f", "", "", "", "\x85", "\u2028", "\u2029"]); LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g; function partition(str2, delimiter) { const index = str2.indexOf(delimiter); if (index !== -1) { return [str2.substring(0, index), delimiter, str2.substring(index + delimiter.length)]; } return [str2, "", ""]; } function readableStreamAsyncIterable(stream) { if (stream[Symbol.asyncIterator]) return stream; const reader = stream.getReader(); return { async next() { try { const result = await reader.read(); if (result == null ? void 0 : result.done) reader.releaseLock(); return result; } catch (e) { reader.releaseLock(); throw e; } }, async return() { const cancelPromise = reader.cancel(); reader.releaseLock(); await cancelPromise; return { done: true, value: void 0 }; }, [Symbol.asyncIterator]() { return this; } }; } // node_modules/openai/uploads.mjs var isResponseLike = (value) => value != null && typeof value === "object" && typeof value.url === "string" && typeof value.blob === "function"; var isFileLike = (value) => value != null && typeof value === "object" && typeof value.name === "string" && typeof value.lastModified === "number" && isBlobLike(value); var isBlobLike = (value) => value != null && typeof value === "object" && typeof value.size === "number" && typeof value.type === "string" && typeof value.text === "function" && typeof value.slice === "function" && typeof value.arrayBuffer === "function"; var isUploadable = (value) => { return isFileLike(value) || isResponseLike(value) || isFsReadStream(value); }; async function toFile(value, name, options = {}) { var _a3, _b2, _c; value = await value; if (isResponseLike(value)) { const blob = await value.blob(); name || (name = (_a3 = new URL(value.url).pathname.split(/[\\/]/).pop()) != null ? _a3 : "unknown_file"); return new File2([blob], name, options); } const bits = await getBytes(value); name || (name = (_b2 = getName(value)) != null ? _b2 : "unknown_file"); if (!options.type) { const type2 = (_c = bits[0]) == null ? void 0 : _c.type; if (typeof type2 === "string") { options = { ...options, type: type2 }; } } return new File2(bits, name, options); } async function getBytes(value) { var _a3; let parts = []; if (typeof value === "string" || ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. value instanceof ArrayBuffer) { parts.push(value); } else if (isBlobLike(value)) { parts.push(await value.arrayBuffer()); } else if (isAsyncIterableIterator(value)) { for await (const chunk of value) { parts.push(chunk); } } else { throw new Error(`Unexpected data type: ${typeof value}; constructor: ${(_a3 = value == null ? void 0 : value.constructor) == null ? void 0 : _a3.name}; props: ${propsForError(value)}`); } return parts; } function propsForError(value) { const props = Object.getOwnPropertyNames(value); return `[${props.map((p) => `"${p}"`).join(", ")}]`; } function getName(value) { var _a3; return getStringFromMaybeBuffer(value.name) || getStringFromMaybeBuffer(value.filename) || // For fs.ReadStream ((_a3 = getStringFromMaybeBuffer(value.path)) == null ? void 0 : _a3.split(/[\\/]/).pop()); } var getStringFromMaybeBuffer = (x) => { if (typeof x === "string") return x; if (typeof Buffer !== "undefined" && x instanceof Buffer) return String(x); return void 0; }; var isAsyncIterableIterator = (value) => value != null && typeof value === "object" && typeof value[Symbol.asyncIterator] === "function"; var isMultipartBody = (body) => body && typeof body === "object" && body.body && body[Symbol.toStringTag] === "MultipartBody"; var multipartFormRequestOptions = async (opts) => { const form = await createForm(opts.body); return getMultipartRequestOptions(form, opts); }; var createForm = async (body) => { const form = new FormData2(); await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); return form; }; var addFormValue = async (form, key, value) => { if (value === void 0) return; if (value == null) { throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); } if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { form.append(key, String(value)); } else if (isUploadable(value)) { const file = await toFile(value); form.append(key, file); } else if (Array.isArray(value)) { await Promise.all(value.map((entry) => addFormValue(form, key + "[]", entry))); } else if (typeof value === "object") { await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); } else { throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); } }; // node_modules/openai/core.mjs var __classPrivateFieldSet = function(receiver, state, value, kind2, f) { if (kind2 === "m") throw new TypeError("Private method is not writable"); if (kind2 === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var __classPrivateFieldGet = function(receiver, state, kind2, f) { if (kind2 === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _AbstractPage_client; async function defaultParseResponse(props) { const { response } = props; if (props.options.stream) { debug("response", response.status, response.url, response.headers, response.body); return Stream.fromSSEResponse(response, props.controller); } if (response.status === 204) { return null; } if (props.options.__binaryResponse) { return response; } const contentType = response.headers.get("content-type"); if (contentType == null ? void 0 : contentType.includes("application/json")) { const json = await response.json(); debug("response", response.status, response.url, response.headers, json); return json; } const text = await response.text(); debug("response", response.status, response.url, response.headers, text); return text; } var APIPromise = class extends Promise { constructor(responsePromise, parseResponse = defaultParseResponse) { super((resolve) => { resolve(null); }); this.responsePromise = responsePromise; this.parseResponse = parseResponse; } _thenUnwrap(transform) { return new APIPromise(this.responsePromise, async (props) => transform(await this.parseResponse(props))); } /** * Gets the raw `Response` instance instead of parsing the response * data. * * If you want to parse the response body but still get the `Response` * instance, you can use {@link withResponse()}. * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */ asResponse() { return this.responsePromise.then((p) => p.response); } /** * Gets the parsed response data and the raw `Response` instance. * * If you just want to get the raw `Response` instance without parsing it, * you can use {@link asResponse()}. * * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */ async withResponse() { const [data, response] = await Promise.all([this.parse(), this.asResponse()]); return { data, response }; } parse() { if (!this.parsedPromise) { this.parsedPromise = this.responsePromise.then(this.parseResponse); } return this.parsedPromise; } then(onfulfilled, onrejected) { return this.parse().then(onfulfilled, onrejected); } catch(onrejected) { return this.parse().catch(onrejected); } finally(onfinally) { return this.parse().finally(onfinally); } }; var APIClient = class { constructor({ baseURL, maxRetries = 2, timeout = 6e5, // 10 minutes httpAgent, fetch: overridenFetch }) { this.baseURL = baseURL; this.maxRetries = validatePositiveInteger("maxRetries", maxRetries); this.timeout = validatePositiveInteger("timeout", timeout); this.httpAgent = httpAgent; this.fetch = overridenFetch != null ? overridenFetch : fetch2; } authHeaders(opts) { return {}; } /** * Override this to add your own default headers, for example: * * { * ...super.defaultHeaders(), * Authorization: 'Bearer 123', * } */ defaultHeaders(opts) { return { Accept: "application/json", "Content-Type": "application/json", "User-Agent": this.getUserAgent(), ...getPlatformHeaders(), ...this.authHeaders(opts) }; } /** * Override this to add your own headers validation: */ validateHeaders(headers, customHeaders) { } defaultIdempotencyKey() { return `stainless-node-retry-${uuid4()}`; } get(path, opts) { return this.methodRequest("get", path, opts); } post(path, opts) { return this.methodRequest("post", path, opts); } patch(path, opts) { return this.methodRequest("patch", path, opts); } put(path, opts) { return this.methodRequest("put", path, opts); } delete(path, opts) { return this.methodRequest("delete", path, opts); } methodRequest(method, path, opts) { return this.request(Promise.resolve(opts).then((opts2) => ({ method, path, ...opts2 }))); } getAPIList(path, Page2, opts) { return this.requestAPIList(Page2, { method: "get", path, ...opts }); } calculateContentLength(body) { if (typeof body === "string") { if (typeof Buffer !== "undefined") { return Buffer.byteLength(body, "utf8").toString(); } if (typeof TextEncoder !== "undefined") { const encoder2 = new TextEncoder(); const encoded = encoder2.encode(body); return encoded.length.toString(); } } return null; } buildRequest(options) { var _a3, _b2, _c, _d, _e, _f; const { method, path, query, headers = {} } = options; const body = isMultipartBody(options.body) ? options.body.body : options.body ? JSON.stringify(options.body, null, 2) : null; const contentLength = this.calculateContentLength(body); const url = this.buildURL(path, query); if ("timeout" in options) validatePositiveInteger("timeout", options.timeout); const timeout = (_a3 = options.timeout) != null ? _a3 : this.timeout; const httpAgent = (_c = (_b2 = options.httpAgent) != null ? _b2 : this.httpAgent) != null ? _c : getDefaultAgent(url); const minAgentTimeout = timeout + 1e3; if (typeof ((_d = httpAgent == null ? void 0 : httpAgent.options) == null ? void 0 : _d.timeout) === "number" && minAgentTimeout > ((_e = httpAgent.options.timeout) != null ? _e : 0)) { httpAgent.options.timeout = minAgentTimeout; } if (this.idempotencyHeader && method !== "get") { if (!options.idempotencyKey) options.idempotencyKey = this.defaultIdempotencyKey(); headers[this.idempotencyHeader] = options.idempotencyKey; } const reqHeaders = this.buildHeaders({ options, headers, contentLength }); const req = { method, ...body && { body }, headers: reqHeaders, ...httpAgent && { agent: httpAgent }, // @ts-ignore node-fetch uses a custom AbortSignal type that is // not compatible with standard web types signal: (_f = options.signal) != null ? _f : null }; return { req, url, timeout }; } buildHeaders({ options, headers, contentLength }) { const reqHeaders = {}; if (contentLength) { reqHeaders["content-length"] = contentLength; } const defaultHeaders = this.defaultHeaders(options); applyHeadersMut(reqHeaders, defaultHeaders); applyHeadersMut(reqHeaders, headers); if (isMultipartBody(options.body) && kind !== "node") { delete reqHeaders["content-type"]; } this.validateHeaders(reqHeaders, headers); return reqHeaders; } /** * Used as a callback for mutating the given `RequestInit` object. * * This is useful for cases where you want to add certain headers based off of * the request properties, e.g. `method` or `url`. */ async prepareRequest(request, { url, options }) { } parseHeaders(headers) { return !headers ? {} : Symbol.iterator in headers ? Object.fromEntries(Array.from(headers).map((header) => [...header])) : { ...headers }; } makeStatusError(status, error, message2, headers) { return APIError.generate(status, error, message2, headers); } request(options, remainingRetries = null) { return new APIPromise(this.makeRequest(options, remainingRetries)); } async makeRequest(optionsInput, retriesRemaining) { var _a3, _b2, _c; const options = await optionsInput; if (retriesRemaining == null) { retriesRemaining = (_a3 = options.maxRetries) != null ? _a3 : this.maxRetries; } const { req, url, timeout } = this.buildRequest(options); await this.prepareRequest(req, { url, options }); debug("request", url, options, req.headers); if ((_b2 = options.signal) == null ? void 0 : _b2.aborted) { throw new APIUserAbortError(); } const controller = new AbortController(); const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); if (response instanceof Error) { if ((_c = options.signal) == null ? void 0 : _c.aborted) { throw new APIUserAbortError(); } if (retriesRemaining) { return this.retryRequest(options, retriesRemaining); } if (response.name === "AbortError") { throw new APIConnectionTimeoutError(); } throw new APIConnectionError({ cause: response }); } const responseHeaders = createResponseHeaders(response.headers); if (!response.ok) { if (retriesRemaining && this.shouldRetry(response)) { const retryMessage2 = `retrying, ${retriesRemaining} attempts remaining`; debug(`response (error; ${retryMessage2})`, response.status, url, responseHeaders); return this.retryRequest(options, retriesRemaining, responseHeaders); } const errText = await response.text().catch((e) => castToError(e).message); const errJSON = safeJSON(errText); const errMessage = errJSON ? void 0 : errText; const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`; debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage); const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders); throw err; } return { response, options, controller }; } requestAPIList(Page2, options) { const request = this.makeRequest(options, null); return new PagePromise(this, request, Page2); } buildURL(path, query) { const url = isAbsoluteURL(path) ? new URL(path) : new URL(this.baseURL + (this.baseURL.endsWith("/") && path.startsWith("/") ? path.slice(1) : path)); const defaultQuery = this.defaultQuery(); if (!isEmptyObj(defaultQuery)) { query = { ...defaultQuery, ...query }; } if (typeof query === "object" && query && !Array.isArray(query)) { url.search = this.stringifyQuery(query); } return url.toString(); } stringifyQuery(query) { return Object.entries(query).filter(([_, value]) => typeof value !== "undefined").map(([key, value]) => { if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; } if (value === null) { return `${encodeURIComponent(key)}=`; } throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); }).join("&"); } async fetchWithTimeout(url, init, ms, controller) { const { signal, ...options } = init || {}; if (signal) signal.addEventListener("abort", () => controller.abort()); const timeout = setTimeout(() => controller.abort(), ms); return this.getRequestClient().fetch.call(void 0, url, { signal: controller.signal, ...options }).finally(() => { clearTimeout(timeout); }); } getRequestClient() { return { fetch: this.fetch }; } shouldRetry(response) { const shouldRetryHeader = response.headers.get("x-should-retry"); if (shouldRetryHeader === "true") return true; if (shouldRetryHeader === "false") return false; if (response.status === 408) return true; if (response.status === 409) return true; if (response.status === 429) return true; if (response.status >= 500) return true; return false; } async retryRequest(options, retriesRemaining, responseHeaders) { var _a3; let timeoutMillis; const retryAfterMillisHeader = responseHeaders == null ? void 0 : responseHeaders["retry-after-ms"]; if (retryAfterMillisHeader) { const timeoutMs = parseFloat(retryAfterMillisHeader); if (!Number.isNaN(timeoutMs)) { timeoutMillis = timeoutMs; } } const retryAfterHeader = responseHeaders == null ? void 0 : responseHeaders["retry-after"]; if (retryAfterHeader && !timeoutMillis) { const timeoutSeconds = parseFloat(retryAfterHeader); if (!Number.isNaN(timeoutSeconds)) { timeoutMillis = timeoutSeconds * 1e3; } else { timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); } } if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1e3)) { const maxRetries = (_a3 = options.maxRetries) != null ? _a3 : this.maxRetries; timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); } await sleep(timeoutMillis); return this.makeRequest(options, retriesRemaining - 1); } calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { const initialRetryDelay = 0.5; const maxRetryDelay = 8; const numRetries = maxRetries - retriesRemaining; const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); const jitter = 1 - Math.random() * 0.25; return sleepSeconds * jitter * 1e3; } getUserAgent() { return `${this.constructor.name}/JS ${VERSION}`; } }; var AbstractPage = class { constructor(client, response, body, options) { _AbstractPage_client.set(this, void 0); __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); this.options = options; this.response = response; this.body = body; } hasNextPage() { const items = this.getPaginatedItems(); if (!items.length) return false; return this.nextPageInfo() != null; } async getNextPage() { const nextInfo = this.nextPageInfo(); if (!nextInfo) { throw new OpenAIError("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); } const nextOptions = { ...this.options }; if ("params" in nextInfo && typeof nextOptions.query === "object") { nextOptions.query = { ...nextOptions.query, ...nextInfo.params }; } else if ("url" in nextInfo) { const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()]; for (const [key, value] of params) { nextInfo.url.searchParams.set(key, value); } nextOptions.query = void 0; nextOptions.path = nextInfo.url.toString(); } return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); } async *iterPages() { let page = this; yield page; while (page.hasNextPage()) { page = await page.getNextPage(); yield page; } } async *[(_AbstractPage_client = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { for await (const page of this.iterPages()) { for (const item of page.getPaginatedItems()) { yield item; } } } }; var PagePromise = class extends APIPromise { constructor(client, request, Page2) { super(request, async (props) => new Page2(client, props.response, await defaultParseResponse(props), props.options)); } /** * Allow auto-paginating iteration on an unawaited list call, eg: * * for await (const item of client.items.list()) { * console.log(item) * } */ async *[Symbol.asyncIterator]() { const page = await this; for await (const item of page) { yield item; } } }; var createResponseHeaders = (headers) => { return new Proxy(Object.fromEntries( // @ts-ignore headers.entries() ), { get(target, name) { const key = name.toString(); return target[key.toLowerCase()] || target[key]; } }); }; var requestOptionsKeys = { method: true, path: true, query: true, body: true, headers: true, maxRetries: true, stream: true, timeout: true, httpAgent: true, signal: true, idempotencyKey: true, __binaryResponse: true }; var isRequestOptions = (obj) => { return typeof obj === "object" && obj !== null && !isEmptyObj(obj) && Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)); }; var getPlatformProperties = () => { if (typeof Deno !== "undefined" && Deno.build != null) { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": normalizePlatform(Deno.build.os), "X-Stainless-Arch": normalizeArch(Deno.build.arch), "X-Stainless-Runtime": "deno", "X-Stainless-Runtime-Version": Deno.version }; } if (typeof EdgeRuntime !== "undefined") { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": `other:${EdgeRuntime}`, "X-Stainless-Runtime": "edge", "X-Stainless-Runtime-Version": process.version }; } if (Object.prototype.toString.call(typeof process !== "undefined" ? process : 0) === "[object process]") { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": normalizePlatform(process.platform), "X-Stainless-Arch": normalizeArch(process.arch), "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": process.version }; } const browserInfo = getBrowserInfo(); if (browserInfo) { return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": `browser:${browserInfo.browser}`, "X-Stainless-Runtime-Version": browserInfo.version }; } return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": VERSION, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": "unknown", "X-Stainless-Runtime-Version": "unknown" }; }; function getBrowserInfo() { if (typeof navigator === "undefined" || !navigator) { return null; } const browserPatterns = [ { key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ } ]; for (const { key, pattern } of browserPatterns) { const match2 = pattern.exec(navigator.userAgent); if (match2) { const major = match2[1] || 0; const minor = match2[2] || 0; const patch = match2[3] || 0; return { browser: key, version: `${major}.${minor}.${patch}` }; } } return null; } var normalizeArch = (arch) => { if (arch === "x32") return "x32"; if (arch === "x86_64" || arch === "x64") return "x64"; if (arch === "arm") return "arm"; if (arch === "aarch64" || arch === "arm64") return "arm64"; if (arch) return `other:${arch}`; return "unknown"; }; var normalizePlatform = (platform) => { platform = platform.toLowerCase(); if (platform.includes("ios")) return "iOS"; if (platform === "android") return "Android"; if (platform === "darwin") return "MacOS"; if (platform === "win32") return "Windows"; if (platform === "freebsd") return "FreeBSD"; if (platform === "openbsd") return "OpenBSD"; if (platform === "linux") return "Linux"; if (platform) return `Other:${platform}`; return "Unknown"; }; var _platformHeaders; var getPlatformHeaders = () => { return _platformHeaders != null ? _platformHeaders : _platformHeaders = getPlatformProperties(); }; var safeJSON = (text) => { try { return JSON.parse(text); } catch (err) { return void 0; } }; var startsWithSchemeRegexp = new RegExp("^(?:[a-z]+:)?//", "i"); var isAbsoluteURL = (url) => { return startsWithSchemeRegexp.test(url); }; var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); var validatePositiveInteger = (name, n) => { if (typeof n !== "number" || !Number.isInteger(n)) { throw new OpenAIError(`${name} must be an integer`); } if (n < 0) { throw new OpenAIError(`${name} must be a positive integer`); } return n; }; var castToError = (err) => { if (err instanceof Error) return err; return new Error(err); }; var readEnv = (env) => { var _a3, _b2, _c, _d, _e, _f; if (typeof process !== "undefined") { return (_c = (_b2 = (_a3 = process.env) == null ? void 0 : _a3[env]) == null ? void 0 : _b2.trim()) != null ? _c : void 0; } if (typeof Deno !== "undefined") { return (_f = (_e = (_d = Deno.env) == null ? void 0 : _d.get) == null ? void 0 : _e.call(_d, env)) == null ? void 0 : _f.trim(); } return void 0; }; function isEmptyObj(obj) { if (!obj) return true; for (const _k in obj) return false; return true; } function hasOwn(obj, key) { return Object.prototype.hasOwnProperty.call(obj, key); } function applyHeadersMut(targetHeaders, newHeaders) { for (const k in newHeaders) { if (!hasOwn(newHeaders, k)) continue; const lowerKey = k.toLowerCase(); if (!lowerKey) continue; const val = newHeaders[k]; if (val === null) { delete targetHeaders[lowerKey]; } else if (val !== void 0) { targetHeaders[lowerKey] = val; } } } function debug(action, ...args) { if (typeof process !== "undefined" && process.env["DEBUG"] === "true") { console.log(`OpenAI:DEBUG:${action}`, ...args); } } var uuid4 = () => { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === "x" ? r : r & 3 | 8; return v.toString(16); }); }; var isRunningInBrowser = () => { return ( // @ts-ignore typeof window !== "undefined" && // @ts-ignore typeof window.document !== "undefined" && // @ts-ignore typeof navigator !== "undefined" ); }; // node_modules/openai/pagination.mjs var Page = class extends AbstractPage { constructor(client, response, body, options) { super(client, response, body, options); this.data = body.data || []; this.object = body.object; } getPaginatedItems() { var _a3; return (_a3 = this.data) != null ? _a3 : []; } // @deprecated Please use `nextPageInfo()` instead /** * This page represents a response that isn't actually paginated at the API level * so there will never be any next page params. */ nextPageParams() { return null; } nextPageInfo() { return null; } }; var CursorPage = class extends AbstractPage { constructor(client, response, body, options) { super(client, response, body, options); this.data = body.data || []; } getPaginatedItems() { var _a3; return (_a3 = this.data) != null ? _a3 : []; } // @deprecated Please use `nextPageInfo()` instead nextPageParams() { const info = this.nextPageInfo(); if (!info) return null; if ("params" in info) return info.params; const params = Object.fromEntries(info.url.searchParams); if (!Object.keys(params).length) return null; return params; } nextPageInfo() { var _a3; const data = this.getPaginatedItems(); if (!data.length) { return null; } const id = (_a3 = data[data.length - 1]) == null ? void 0 : _a3.id; if (!id) { return null; } return { params: { after: id } }; } }; // node_modules/openai/resource.mjs var APIResource = class { constructor(client) { this._client = client; } }; // node_modules/openai/resources/chat/completions.mjs var Completions = class extends APIResource { create(body, options) { var _a3; return this._client.post("/chat/completions", { body, ...options, stream: (_a3 = body.stream) != null ? _a3 : false }); } }; (function(Completions4) { })(Completions || (Completions = {})); // node_modules/openai/resources/chat/chat.mjs var Chat = class extends APIResource { constructor() { super(...arguments); this.completions = new Completions(this._client); } }; (function(Chat3) { Chat3.Completions = Completions; })(Chat || (Chat = {})); // node_modules/openai/resources/audio/speech.mjs var Speech = class extends APIResource { /** * Generates audio from the input text. */ create(body, options) { return this._client.post("/audio/speech", { body, ...options, __binaryResponse: true }); } }; (function(Speech2) { })(Speech || (Speech = {})); // node_modules/openai/resources/audio/transcriptions.mjs var Transcriptions = class extends APIResource { /** * Transcribes audio into the input language. */ create(body, options) { return this._client.post("/audio/transcriptions", multipartFormRequestOptions({ body, ...options })); } }; (function(Transcriptions2) { })(Transcriptions || (Transcriptions = {})); // node_modules/openai/resources/audio/translations.mjs var Translations = class extends APIResource { /** * Translates audio into English. */ create(body, options) { return this._client.post("/audio/translations", multipartFormRequestOptions({ body, ...options })); } }; (function(Translations2) { })(Translations || (Translations = {})); // node_modules/openai/resources/audio/audio.mjs var Audio = class extends APIResource { constructor() { super(...arguments); this.transcriptions = new Transcriptions(this._client); this.translations = new Translations(this._client); this.speech = new Speech(this._client); } }; (function(Audio2) { Audio2.Transcriptions = Transcriptions; Audio2.Translations = Translations; Audio2.Speech = Speech; })(Audio || (Audio = {})); // node_modules/openai/resources/beta/assistants/files.mjs var Files = class extends APIResource { /** * Create an assistant file by attaching a * [File](https://platform.openai.com/docs/api-reference/files) to an * [assistant](https://platform.openai.com/docs/api-reference/assistants). */ create(assistantId, body, options) { return this._client.post(`/assistants/${assistantId}/files`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Retrieves an AssistantFile. */ retrieve(assistantId, fileId, options) { return this._client.get(`/assistants/${assistantId}/files/${fileId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } list(assistantId, query = {}, options) { if (isRequestOptions(query)) { return this.list(assistantId, {}, query); } return this._client.getAPIList(`/assistants/${assistantId}/files`, AssistantFilesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Delete an assistant file. */ del(assistantId, fileId, options) { return this._client.delete(`/assistants/${assistantId}/files/${fileId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; var AssistantFilesPage = class extends CursorPage { }; (function(Files4) { Files4.AssistantFilesPage = AssistantFilesPage; })(Files || (Files = {})); // node_modules/openai/resources/beta/assistants/assistants.mjs var Assistants = class extends APIResource { constructor() { super(...arguments); this.files = new Files(this._client); } /** * Create an assistant with a model and instructions. */ create(body, options) { return this._client.post("/assistants", { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Retrieves an assistant. */ retrieve(assistantId, options) { return this._client.get(`/assistants/${assistantId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Modifies an assistant. */ update(assistantId, body, options) { return this._client.post(`/assistants/${assistantId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } list(query = {}, options) { if (isRequestOptions(query)) { return this.list({}, query); } return this._client.getAPIList("/assistants", AssistantsPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Delete an assistant. */ del(assistantId, options) { return this._client.delete(`/assistants/${assistantId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; var AssistantsPage = class extends CursorPage { }; (function(Assistants2) { Assistants2.AssistantsPage = AssistantsPage; Assistants2.Files = Files; Assistants2.AssistantFilesPage = AssistantFilesPage; })(Assistants || (Assistants = {})); // node_modules/openai/lib/RunnableFunction.mjs function isRunnableFunctionWithParse(fn) { return typeof fn.parse === "function"; } // node_modules/openai/lib/chatCompletionUtils.mjs var isAssistantMessage = (message2) => { return (message2 == null ? void 0 : message2.role) === "assistant"; }; var isFunctionMessage = (message2) => { return (message2 == null ? void 0 : message2.role) === "function"; }; var isToolMessage = (message2) => { return (message2 == null ? void 0 : message2.role) === "tool"; }; // node_modules/openai/lib/AbstractChatCompletionRunner.mjs var __classPrivateFieldSet2 = function(receiver, state, value, kind2, f) { if (kind2 === "m") throw new TypeError("Private method is not writable"); if (kind2 === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var __classPrivateFieldGet2 = function(receiver, state, kind2, f) { if (kind2 === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var _AbstractChatCompletionRunner_instances; var _AbstractChatCompletionRunner_connectedPromise; var _AbstractChatCompletionRunner_resolveConnectedPromise; var _AbstractChatCompletionRunner_rejectConnectedPromise; var _AbstractChatCompletionRunner_endPromise; var _AbstractChatCompletionRunner_resolveEndPromise; var _AbstractChatCompletionRunner_rejectEndPromise; var _AbstractChatCompletionRunner_listeners; var _AbstractChatCompletionRunner_ended; var _AbstractChatCompletionRunner_errored; var _AbstractChatCompletionRunner_aborted; var _AbstractChatCompletionRunner_catchingPromiseCreated; var _AbstractChatCompletionRunner_getFinalContent; var _AbstractChatCompletionRunner_getFinalMessage; var _AbstractChatCompletionRunner_getFinalFunctionCall; var _AbstractChatCompletionRunner_getFinalFunctionCallResult; var _AbstractChatCompletionRunner_calculateTotalUsage; var _AbstractChatCompletionRunner_handleError; var _AbstractChatCompletionRunner_validateParams; var _AbstractChatCompletionRunner_stringifyFunctionCallResult; var DEFAULT_MAX_CHAT_COMPLETIONS = 10; var AbstractChatCompletionRunner = class { constructor() { _AbstractChatCompletionRunner_instances.add(this); this.controller = new AbortController(); _AbstractChatCompletionRunner_connectedPromise.set(this, void 0); _AbstractChatCompletionRunner_resolveConnectedPromise.set(this, () => { }); _AbstractChatCompletionRunner_rejectConnectedPromise.set(this, () => { }); _AbstractChatCompletionRunner_endPromise.set(this, void 0); _AbstractChatCompletionRunner_resolveEndPromise.set(this, () => { }); _AbstractChatCompletionRunner_rejectEndPromise.set(this, () => { }); _AbstractChatCompletionRunner_listeners.set(this, {}); this._chatCompletions = []; this.messages = []; _AbstractChatCompletionRunner_ended.set(this, false); _AbstractChatCompletionRunner_errored.set(this, false); _AbstractChatCompletionRunner_aborted.set(this, false); _AbstractChatCompletionRunner_catchingPromiseCreated.set(this, false); _AbstractChatCompletionRunner_handleError.set(this, (error) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_errored, true, "f"); if (error instanceof Error && error.name === "AbortError") { error = new APIUserAbortError(); } if (error instanceof APIUserAbortError) { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_aborted, true, "f"); return this._emit("abort", error); } if (error instanceof OpenAIError) { return this._emit("error", error); } if (error instanceof Error) { const openAIError = new OpenAIError(error.message); openAIError.cause = error; return this._emit("error", openAIError); } return this._emit("error", new OpenAIError(String(error))); }); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_connectedPromise, new Promise((resolve, reject) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_resolveConnectedPromise, resolve, "f"); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_rejectConnectedPromise, reject, "f"); }), "f"); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_endPromise, new Promise((resolve, reject) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_resolveEndPromise, resolve, "f"); __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_rejectEndPromise, reject, "f"); }), "f"); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_connectedPromise, "f").catch(() => { }); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_endPromise, "f").catch(() => { }); } _run(executor) { setTimeout(() => { executor().then(() => { this._emitFinal(); this._emit("end"); }, __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_handleError, "f")); }, 0); } _addChatCompletion(chatCompletion) { var _a3; this._chatCompletions.push(chatCompletion); this._emit("chatCompletion", chatCompletion); const message2 = (_a3 = chatCompletion.choices[0]) == null ? void 0 : _a3.message; if (message2) this._addMessage(message2); return chatCompletion; } _addMessage(message2, emit = true) { if (!("content" in message2)) message2.content = null; this.messages.push(message2); if (emit) { this._emit("message", message2); if ((isFunctionMessage(message2) || isToolMessage(message2)) && message2.content) { this._emit("functionCallResult", message2.content); } else if (isAssistantMessage(message2) && message2.function_call) { this._emit("functionCall", message2.function_call); } else if (isAssistantMessage(message2) && message2.tool_calls) { for (const tool_call of message2.tool_calls) { if (tool_call.type === "function") { this._emit("functionCall", tool_call.function); } } } } } _connected() { if (this.ended) return; __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_resolveConnectedPromise, "f").call(this); this._emit("connect"); } get ended() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_ended, "f"); } get errored() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_errored, "f"); } get aborted() { return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_aborted, "f"); } abort() { this.controller.abort(); } /** * Adds the listener function to the end of the listeners array for the event. * No checks are made to see if the listener has already been added. Multiple calls passing * the same combination of event and listener will result in the listener being added, and * called, multiple times. * @returns this ChatCompletionStream, so that calls can be chained */ on(event, listener) { const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); listeners.push({ listener }); return this; } /** * Removes the specified listener from the listener array for the event. * off() will remove, at most, one instance of a listener from the listener array. If any single * listener has been added multiple times to the listener array for the specified event, then * off() must be called multiple times to remove each instance. * @returns this ChatCompletionStream, so that calls can be chained */ off(event, listener) { const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event]; if (!listeners) return this; const index = listeners.findIndex((l) => l.listener === listener); if (index >= 0) listeners.splice(index, 1); return this; } /** * Adds a one-time listener function for the event. The next time the event is triggered, * this listener is removed and then invoked. * @returns this ChatCompletionStream, so that calls can be chained */ once(event, listener) { const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event] || (__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event] = []); listeners.push({ listener, once: true }); return this; } /** * This is similar to `.once()`, but returns a Promise that resolves the next time * the event is triggered, instead of calling a listener callback. * @returns a Promise that resolves the next time given event is triggered, * or rejects if an error is emitted. (If you request the 'error' event, * returns a promise that resolves with the error). * * Example: * * const message = await stream.emitted('message') // rejects if the stream errors */ emitted(event) { return new Promise((resolve, reject) => { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); if (event !== "error") this.once("error", reject); this.once(event, resolve); }); } async done() { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, true, "f"); await __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_endPromise, "f"); } /** * @returns a promise that resolves with the final ChatCompletion, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletion. */ async finalChatCompletion() { await this.done(); const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (!completion) throw new OpenAIError("stream ended without producing a ChatCompletion"); return completion; } /** * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ async finalContent() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); } /** * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ async finalMessage() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); } /** * @returns a promise that resolves with the content of the final FunctionCall, or rejects * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. */ async finalFunctionCall() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); } async finalFunctionCallResult() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); } async totalUsage() { await this.done(); return __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); } allChatCompletions() { return [...this._chatCompletions]; } _emit(event, ...args) { if (__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_ended, "f")) { return; } if (event === "end") { __classPrivateFieldSet2(this, _AbstractChatCompletionRunner_ended, true, "f"); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_resolveEndPromise, "f").call(this); } const listeners = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event]; if (listeners) { __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_listeners, "f")[event] = listeners.filter((l) => !l.once); listeners.forEach(({ listener }) => listener(...args)); } if (event === "abort") { const error = args[0]; if (!__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !(listeners == null ? void 0 : listeners.length)) { Promise.reject(error); } __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); this._emit("end"); return; } if (event === "error") { const error = args[0]; if (!__classPrivateFieldGet2(this, _AbstractChatCompletionRunner_catchingPromiseCreated, "f") && !(listeners == null ? void 0 : listeners.length)) { Promise.reject(error); } __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectConnectedPromise, "f").call(this, error); __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_rejectEndPromise, "f").call(this, error); this._emit("end"); } } _emitFinal() { const completion = this._chatCompletions[this._chatCompletions.length - 1]; if (completion) this._emit("finalChatCompletion", completion); const finalMessage = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); if (finalMessage) this._emit("finalMessage", finalMessage); const finalContent = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); if (finalContent) this._emit("finalContent", finalContent); const finalFunctionCall = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this); if (finalFunctionCall) this._emit("finalFunctionCall", finalFunctionCall); const finalFunctionCallResult = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this); if (finalFunctionCallResult != null) this._emit("finalFunctionCallResult", finalFunctionCallResult); if (this._chatCompletions.some((c) => c.usage)) { this._emit("totalUsage", __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); } } async _createChatCompletion(completions, params, options) { const signal = options == null ? void 0 : options.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); const chatCompletion = await completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); this._connected(); return this._addChatCompletion(chatCompletion); } async _runChatCompletion(completions, params, options) { for (const message2 of params.messages) { this._addMessage(message2, false); } return await this._createChatCompletion(completions, params, options); } async _runFunctions(completions, params, options) { var _a3; const role = "function"; const { function_call = "auto", stream, ...restParams } = params; const singleFunctionToCall = typeof function_call !== "string" && (function_call == null ? void 0 : function_call.name); const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; const functionsByName = {}; for (const f of params.functions) { functionsByName[f.name || f.function.name] = f; } const functions = params.functions.map((f) => ({ name: f.name || f.function.name, parameters: f.parameters, description: f.description })); for (const message2 of params.messages) { this._addMessage(message2, false); } for (let i = 0; i < maxChatCompletions; ++i) { const chatCompletion = await this._createChatCompletion(completions, { ...restParams, function_call, functions, messages: [...this.messages] }, options); const message2 = (_a3 = chatCompletion.choices[0]) == null ? void 0 : _a3.message; if (!message2) { throw new OpenAIError(`missing message in ChatCompletion response`); } if (!message2.function_call) return; const { name, arguments: args } = message2.function_call; const fn = functionsByName[name]; if (!fn) { const content2 = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions.map((f) => JSON.stringify(f.name)).join(", ")}. Please try again`; this._addMessage({ role, name, content: content2 }); continue; } else if (singleFunctionToCall && singleFunctionToCall !== name) { const content2 = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; this._addMessage({ role, name, content: content2 }); continue; } let parsed; try { parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; } catch (error) { this._addMessage({ role, name, content: error instanceof Error ? error.message : String(error) }); continue; } const rawContent = await fn.function(parsed, this); const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, name, content }); if (singleFunctionToCall) return; } } async _runTools(completions, params, options) { var _a3, _b2; const role = "tool"; const { tool_choice = "auto", stream, ...restParams } = params; const singleFunctionToCall = typeof tool_choice !== "string" && ((_a3 = tool_choice == null ? void 0 : tool_choice.function) == null ? void 0 : _a3.name); const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; const functionsByName = {}; for (const f of params.tools) { if (f.type === "function") { functionsByName[f.function.name || f.function.function.name] = f.function; } } const tools = "tools" in params ? params.tools.map((t2) => t2.type === "function" ? { type: "function", function: { name: t2.function.name || t2.function.function.name, parameters: t2.function.parameters, description: t2.function.description } } : t2) : void 0; for (const message2 of params.messages) { this._addMessage(message2, false); } for (let i = 0; i < maxChatCompletions; ++i) { const chatCompletion = await this._createChatCompletion(completions, { ...restParams, tool_choice, tools, messages: [...this.messages] }, options); const message2 = (_b2 = chatCompletion.choices[0]) == null ? void 0 : _b2.message; if (!message2) { throw new OpenAIError(`missing message in ChatCompletion response`); } if (!message2.tool_calls) { return; } for (const tool_call of message2.tool_calls) { if (tool_call.type !== "function") continue; const tool_call_id = tool_call.id; const { name, arguments: args } = tool_call.function; const fn = functionsByName[name]; if (!fn) { const content2 = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${tools.map((f) => JSON.stringify(f.function.name)).join(", ")}. Please try again`; this._addMessage({ role, tool_call_id, content: content2 }); continue; } else if (singleFunctionToCall && singleFunctionToCall !== name) { const content2 = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; this._addMessage({ role, tool_call_id, content: content2 }); continue; } let parsed; try { parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; } catch (error) { const content2 = error instanceof Error ? error.message : String(error); this._addMessage({ role, tool_call_id, content: content2 }); continue; } const rawContent = await fn.function(parsed, this); const content = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); this._addMessage({ role, tool_call_id, content }); if (singleFunctionToCall) { return; } } } return; } }; _AbstractChatCompletionRunner_connectedPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_resolveConnectedPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_rejectConnectedPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_endPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_resolveEndPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_rejectEndPromise = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_listeners = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_ended = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_errored = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_aborted = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_catchingPromiseCreated = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_handleError = /* @__PURE__ */ new WeakMap(), _AbstractChatCompletionRunner_instances = /* @__PURE__ */ new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent2() { var _a3; return (_a3 = __classPrivateFieldGet2(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content) != null ? _a3 : null; }, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage2() { var _a3; let i = this.messages.length; while (i-- > 0) { const message2 = this.messages[i]; if (isAssistantMessage(message2)) { return { ...message2, content: (_a3 = message2.content) != null ? _a3 : null }; } } throw new OpenAIError("stream ended without producing a ChatCompletionMessage with role=assistant"); }, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall2() { var _a3, _b2; for (let i = this.messages.length - 1; i >= 0; i--) { const message2 = this.messages[i]; if (isAssistantMessage(message2) && (message2 == null ? void 0 : message2.function_call)) { return message2.function_call; } if (isAssistantMessage(message2) && ((_a3 = message2 == null ? void 0 : message2.tool_calls) == null ? void 0 : _a3.length)) { return (_b2 = message2.tool_calls.at(-1)) == null ? void 0 : _b2.function; } } return; }, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult2() { for (let i = this.messages.length - 1; i >= 0; i--) { const message2 = this.messages[i]; if (isFunctionMessage(message2) && message2.content != null) { return message2.content; } if (isToolMessage(message2) && message2.content != null && this.messages.some((x) => { var _a3; return x.role === "assistant" && ((_a3 = x.tool_calls) == null ? void 0 : _a3.some((y) => y.type === "function" && y.id === message2.tool_call_id)); })) { return message2.content; } } return; }, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage2() { const total = { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0 }; for (const { usage } of this._chatCompletions) { if (usage) { total.completion_tokens += usage.completion_tokens; total.prompt_tokens += usage.prompt_tokens; total.total_tokens += usage.total_tokens; } } return total; }, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams2(params) { if (params.n != null && params.n > 1) { throw new OpenAIError("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly."); } }, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult2(rawContent) { return typeof rawContent === "string" ? rawContent : rawContent === void 0 ? "undefined" : JSON.stringify(rawContent); }; // node_modules/openai/lib/ChatCompletionRunner.mjs var ChatCompletionRunner = class extends AbstractChatCompletionRunner { /** @deprecated - please use `runTools` instead. */ static runFunctions(completions, params, options) { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runFunctions" } }; runner._run(() => runner._runFunctions(completions, params, opts)); return runner; } static runTools(completions, params, options) { const runner = new ChatCompletionRunner(); const opts = { ...options, headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runTools" } }; runner._run(() => runner._runTools(completions, params, opts)); return runner; } _addMessage(message2) { super._addMessage(message2); if (isAssistantMessage(message2) && message2.content) { this._emit("content", message2.content); } } }; // node_modules/openai/lib/ChatCompletionStream.mjs var __classPrivateFieldGet3 = function(receiver, state, kind2, f) { if (kind2 === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return kind2 === "m" ? f : kind2 === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); }; var __classPrivateFieldSet3 = function(receiver, state, value, kind2, f) { if (kind2 === "m") throw new TypeError("Private method is not writable"); if (kind2 === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return kind2 === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value; }; var _ChatCompletionStream_instances; var _ChatCompletionStream_currentChatCompletionSnapshot; var _ChatCompletionStream_beginRequest; var _ChatCompletionStream_addChunk; var _ChatCompletionStream_endRequest; var _ChatCompletionStream_accumulateChatCompletion; var ChatCompletionStream = class extends AbstractChatCompletionRunner { constructor() { super(...arguments); _ChatCompletionStream_instances.add(this); _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); } get currentChatCompletionSnapshot() { return __classPrivateFieldGet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); } /** * Intended for use on the frontend, consuming a stream produced with * `.toReadableStream()` on the backend. * * Note that messages sent to the model do not appear in `.on('message')` * in this context. */ static fromReadableStream(stream) { const runner = new ChatCompletionStream(); runner._run(() => runner._fromReadableStream(stream)); return runner; } static createChatCompletion(completions, params, options) { const runner = new ChatCompletionStream(); runner._run(() => runner._runChatCompletion(completions, { ...params, stream: true }, { ...options, headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "stream" } })); return runner; } async _createChatCompletion(completions, params, options) { var _a3; const signal = options == null ? void 0 : options.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); const stream = await completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); this._connected(); for await (const chunk of stream) { __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); } if ((_a3 = stream.controller.signal) == null ? void 0 : _a3.aborted) { throw new APIUserAbortError(); } return this._addChatCompletion(__classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } async _fromReadableStream(readableStream, options) { var _a3; const signal = options == null ? void 0 : options.signal; if (signal) { if (signal.aborted) this.controller.abort(); signal.addEventListener("abort", () => this.controller.abort()); } __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); this._connected(); const stream = Stream.fromReadableStream(readableStream, this.controller); let chatId; for await (const chunk of stream) { if (chatId && chatId !== chunk.id) { this._addChatCompletion(__classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); chatId = chunk.id; } if ((_a3 = stream.controller.signal) == null ? void 0 : _a3.aborted) { throw new APIUserAbortError(); } return this._addChatCompletion(__classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); } [(_ChatCompletionStream_currentChatCompletionSnapshot = /* @__PURE__ */ new WeakMap(), _ChatCompletionStream_instances = /* @__PURE__ */ new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest2() { if (this.ended) return; __classPrivateFieldSet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk2(chunk) { var _a3, _b2, _c; if (this.ended) return; const completion = __classPrivateFieldGet3(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); this._emit("chunk", chunk, completion); const delta = (_b2 = (_a3 = chunk.choices[0]) == null ? void 0 : _a3.delta) == null ? void 0 : _b2.content; const snapshot = (_c = completion.choices[0]) == null ? void 0 : _c.message; if (delta != null && (snapshot == null ? void 0 : snapshot.role) === "assistant" && (snapshot == null ? void 0 : snapshot.content)) { this._emit("content", delta, snapshot.content); } }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest2() { if (this.ended) { throw new OpenAIError(`stream has ended, this shouldn't happen`); } const snapshot = __classPrivateFieldGet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); if (!snapshot) { throw new OpenAIError(`request ended without sending any chunks`); } __classPrivateFieldSet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, void 0, "f"); return finalizeChatCompletion(snapshot); }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion2(chunk) { var _a4, _b3, _c2, _d; var _a3, _b2, _c; let snapshot = __classPrivateFieldGet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); const { choices, ...rest } = chunk; if (!snapshot) { snapshot = __classPrivateFieldSet3(this, _ChatCompletionStream_currentChatCompletionSnapshot, { ...rest, choices: [] }, "f"); } else { Object.assign(snapshot, rest); } for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { let choice = snapshot.choices[index]; if (!choice) { choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; } if (logprobs) { if (!choice.logprobs) { choice.logprobs = Object.assign({}, logprobs); } else { const { content: content2, ...rest3 } = logprobs; Object.assign(choice.logprobs, rest3); if (content2) { (_a4 = (_a3 = choice.logprobs).content) != null ? _a4 : _a3.content = []; choice.logprobs.content.push(...content2); } } } if (finish_reason) choice.finish_reason = finish_reason; Object.assign(choice, other); if (!delta) continue; const { content, function_call, role, tool_calls, ...rest2 } = delta; Object.assign(choice.message, rest2); if (content) choice.message.content = (choice.message.content || "") + content; if (role) choice.message.role = role; if (function_call) { if (!choice.message.function_call) { choice.message.function_call = function_call; } else { if (function_call.name) choice.message.function_call.name = function_call.name; if (function_call.arguments) { (_b3 = (_b2 = choice.message.function_call).arguments) != null ? _b3 : _b2.arguments = ""; choice.message.function_call.arguments += function_call.arguments; } } } if (tool_calls) { if (!choice.message.tool_calls) choice.message.tool_calls = []; for (const { index: index2, id, type: type2, function: fn, ...rest3 } of tool_calls) { const tool_call = (_c2 = (_c = choice.message.tool_calls)[index2]) != null ? _c2 : _c[index2] = {}; Object.assign(tool_call, rest3); if (id) tool_call.id = id; if (type2) tool_call.type = type2; if (fn) (_d = tool_call.function) != null ? _d : tool_call.function = { arguments: "" }; if (fn == null ? void 0 : fn.name) tool_call.function.name = fn.name; if (fn == null ? void 0 : fn.arguments) tool_call.function.arguments += fn.arguments; } } } return snapshot; }, Symbol.asyncIterator)]() { const pushQueue = []; const readQueue = []; let done = false; this.on("chunk", (chunk) => { const reader = readQueue.shift(); if (reader) { reader(chunk); } else { pushQueue.push(chunk); } }); this.on("end", () => { done = true; for (const reader of readQueue) { reader(void 0); } readQueue.length = 0; }); return { next: async () => { if (!pushQueue.length) { if (done) { return { value: void 0, done: true }; } return new Promise((resolve) => readQueue.push(resolve)).then((chunk2) => chunk2 ? { value: chunk2, done: false } : { value: void 0, done: true }); } const chunk = pushQueue.shift(); return { value: chunk, done: false }; } }; } toReadableStream() { const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); return stream.toReadableStream(); } }; function finalizeChatCompletion(snapshot) { const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; return { ...rest, id, choices: choices.map(({ message: message2, finish_reason, index, logprobs, ...choiceRest }) => { if (!finish_reason) throw new OpenAIError(`missing finish_reason for choice ${index}`); const { content = null, function_call, tool_calls, ...messageRest } = message2; const role = message2.role; if (!role) throw new OpenAIError(`missing role for choice ${index}`); if (function_call) { const { arguments: args, name } = function_call; if (args == null) throw new OpenAIError(`missing function_call.arguments for choice ${index}`); if (!name) throw new OpenAIError(`missing function_call.name for choice ${index}`); return { ...choiceRest, message: { content, function_call: { arguments: args, name }, role }, finish_reason, index, logprobs }; } if (tool_calls) { return { ...choiceRest, index, finish_reason, logprobs, message: { ...messageRest, role, content, tool_calls: tool_calls.map((tool_call, i) => { const { function: fn, type: type2, id: id2, ...toolRest } = tool_call; const { arguments: args, name, ...fnRest } = fn || {}; if (id2 == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id ${str(snapshot)}`); if (type2 == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type ${str(snapshot)}`); if (name == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name ${str(snapshot)}`); if (args == null) throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments ${str(snapshot)}`); return { ...toolRest, id: id2, type: type2, function: { ...fnRest, name, arguments: args } }; }) } }; } return { ...choiceRest, message: { ...messageRest, content, role }, finish_reason, index, logprobs }; }), created, model, object: "chat.completion", ...system_fingerprint ? { system_fingerprint } : {} }; } function str(x) { return JSON.stringify(x); } // node_modules/openai/lib/ChatCompletionStreamingRunner.mjs var ChatCompletionStreamingRunner = class extends ChatCompletionStream { static fromReadableStream(stream) { const runner = new ChatCompletionStreamingRunner(); runner._run(() => runner._fromReadableStream(stream)); return runner; } /** @deprecated - please use `runTools` instead. */ static runFunctions(completions, params, options) { const runner = new ChatCompletionStreamingRunner(); const opts = { ...options, headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runFunctions" } }; runner._run(() => runner._runFunctions(completions, params, opts)); return runner; } static runTools(completions, params, options) { const runner = new ChatCompletionStreamingRunner(); const opts = { ...options, headers: { ...options == null ? void 0 : options.headers, "X-Stainless-Helper-Method": "runTools" } }; runner._run(() => runner._runTools(completions, params, opts)); return runner; } }; // node_modules/openai/resources/beta/chat/completions.mjs var Completions2 = class extends APIResource { runFunctions(body, options) { if (body.stream) { return ChatCompletionStreamingRunner.runFunctions(this._client.chat.completions, body, options); } return ChatCompletionRunner.runFunctions(this._client.chat.completions, body, options); } runTools(body, options) { if (body.stream) { return ChatCompletionStreamingRunner.runTools(this._client.chat.completions, body, options); } return ChatCompletionRunner.runTools(this._client.chat.completions, body, options); } /** * Creates a chat completion stream */ stream(body, options) { return ChatCompletionStream.createChatCompletion(this._client.chat.completions, body, options); } }; // node_modules/openai/resources/beta/chat/chat.mjs var Chat2 = class extends APIResource { constructor() { super(...arguments); this.completions = new Completions2(this._client); } }; (function(Chat3) { Chat3.Completions = Completions2; })(Chat2 || (Chat2 = {})); // node_modules/openai/resources/beta/threads/messages/files.mjs var Files2 = class extends APIResource { /** * Retrieves a message file. */ retrieve(threadId, messageId, fileId, options) { return this._client.get(`/threads/${threadId}/messages/${messageId}/files/${fileId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } list(threadId, messageId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, messageId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/messages/${messageId}/files`, MessageFilesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; var MessageFilesPage = class extends CursorPage { }; (function(Files4) { Files4.MessageFilesPage = MessageFilesPage; })(Files2 || (Files2 = {})); // node_modules/openai/resources/beta/threads/messages/messages.mjs var Messages = class extends APIResource { constructor() { super(...arguments); this.files = new Files2(this._client); } /** * Create a message. */ create(threadId, body, options) { return this._client.post(`/threads/${threadId}/messages`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Retrieve a message. */ retrieve(threadId, messageId, options) { return this._client.get(`/threads/${threadId}/messages/${messageId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Modifies a message. */ update(threadId, messageId, body, options) { return this._client.post(`/threads/${threadId}/messages/${messageId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } list(threadId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/messages`, ThreadMessagesPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; var ThreadMessagesPage = class extends CursorPage { }; (function(Messages2) { Messages2.ThreadMessagesPage = ThreadMessagesPage; Messages2.Files = Files2; Messages2.MessageFilesPage = MessageFilesPage; })(Messages || (Messages = {})); // node_modules/openai/resources/beta/threads/runs/steps.mjs var Steps = class extends APIResource { /** * Retrieves a run step. */ retrieve(threadId, runId, stepId, options) { return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } list(threadId, runId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, runId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; var RunStepsPage = class extends CursorPage { }; (function(Steps2) { Steps2.RunStepsPage = RunStepsPage; })(Steps || (Steps = {})); // node_modules/openai/resources/beta/threads/runs/runs.mjs var Runs = class extends APIResource { constructor() { super(...arguments); this.steps = new Steps(this._client); } /** * Create a run. */ create(threadId, body, options) { return this._client.post(`/threads/${threadId}/runs`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Retrieves a run. */ retrieve(threadId, runId, options) { return this._client.get(`/threads/${threadId}/runs/${runId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Modifies a run. */ update(threadId, runId, body, options) { return this._client.post(`/threads/${threadId}/runs/${runId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } list(threadId, query = {}, options) { if (isRequestOptions(query)) { return this.list(threadId, {}, query); } return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, { query, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Cancels a run that is `in_progress`. */ cancel(threadId, runId, options) { return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * When a run has the `status: "requires_action"` and `required_action.type` is * `submit_tool_outputs`, this endpoint can be used to submit the outputs from the * tool calls once they're all completed. All outputs must be submitted in a single * request. */ submitToolOutputs(threadId, runId, body, options) { return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; var RunsPage = class extends CursorPage { }; (function(Runs2) { Runs2.RunsPage = RunsPage; Runs2.Steps = Steps; Runs2.RunStepsPage = RunStepsPage; })(Runs || (Runs = {})); // node_modules/openai/resources/beta/threads/threads.mjs var Threads = class extends APIResource { constructor() { super(...arguments); this.runs = new Runs(this._client); this.messages = new Messages(this._client); } create(body = {}, options) { if (isRequestOptions(body)) { return this.create({}, body); } return this._client.post("/threads", { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Retrieves a thread. */ retrieve(threadId, options) { return this._client.get(`/threads/${threadId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Modifies a thread. */ update(threadId, body, options) { return this._client.post(`/threads/${threadId}`, { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Delete a thread. */ del(threadId, options) { return this._client.delete(`/threads/${threadId}`, { ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } /** * Create a thread and run it in one request. */ createAndRun(body, options) { return this._client.post("/threads/runs", { body, ...options, headers: { "OpenAI-Beta": "assistants=v1", ...options == null ? void 0 : options.headers } }); } }; (function(Threads2) { Threads2.Runs = Runs; Threads2.RunsPage = RunsPage; Threads2.Messages = Messages; Threads2.ThreadMessagesPage = ThreadMessagesPage; })(Threads || (Threads = {})); // node_modules/openai/resources/beta/beta.mjs var Beta = class extends APIResource { constructor() { super(...arguments); this.chat = new Chat2(this._client); this.assistants = new Assistants(this._client); this.threads = new Threads(this._client); } }; (function(Beta2) { Beta2.Chat = Chat2; Beta2.Assistants = Assistants; Beta2.AssistantsPage = AssistantsPage; Beta2.Threads = Threads; })(Beta || (Beta = {})); // node_modules/openai/resources/completions.mjs var Completions3 = class extends APIResource { create(body, options) { var _a3; return this._client.post("/completions", { body, ...options, stream: (_a3 = body.stream) != null ? _a3 : false }); } }; (function(Completions4) { })(Completions3 || (Completions3 = {})); // node_modules/openai/resources/embeddings.mjs var Embeddings = class extends APIResource { /** * Creates an embedding vector representing the input text. */ create(body, options) { return this._client.post("/embeddings", { body, ...options }); } }; (function(Embeddings2) { })(Embeddings || (Embeddings = {})); // node_modules/openai/resources/files.mjs var Files3 = class extends APIResource { /** * Upload a file that can be used across various endpoints. The size of all the * files uploaded by one organization can be up to 100 GB. * * The size of individual files can be a maximum of 512 MB or 2 million tokens for * Assistants. See the * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) to * learn more about the types of files supported. The Fine-tuning API only supports * `.jsonl` files. * * Please [contact us](https://help.openai.com/) if you need to increase these * storage limits. */ create(body, options) { return this._client.post("/files", multipartFormRequestOptions({ body, ...options })); } /** * Returns information about a specific file. */ retrieve(fileId, options) { return this._client.get(`/files/${fileId}`, options); } list(query = {}, options) { if (isRequestOptions(query)) { return this.list({}, query); } return this._client.getAPIList("/files", FileObjectsPage, { query, ...options }); } /** * Delete a file. */ del(fileId, options) { return this._client.delete(`/files/${fileId}`, options); } /** * Returns the contents of the specified file. */ content(fileId, options) { return this._client.get(`/files/${fileId}/content`, { ...options, __binaryResponse: true }); } /** * Returns the contents of the specified file. * * @deprecated The `.content()` method should be used instead */ retrieveContent(fileId, options) { return this._client.get(`/files/${fileId}/content`, { ...options, headers: { Accept: "application/json", ...options == null ? void 0 : options.headers } }); } /** * Waits for the given file to be processed, default timeout is 30 mins. */ async waitForProcessing(id, { pollInterval = 5e3, maxWait = 30 * 60 * 1e3 } = {}) { const TERMINAL_STATES = /* @__PURE__ */ new Set(["processed", "error", "deleted"]); const start = Date.now(); let file = await this.retrieve(id); while (!file.status || !TERMINAL_STATES.has(file.status)) { await sleep(pollInterval); file = await this.retrieve(id); if (Date.now() - start > maxWait) { throw new APIConnectionTimeoutError({ message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.` }); } } return file; } }; var FileObjectsPage = class extends Page { }; (function(Files4) { Files4.FileObjectsPage = FileObjectsPage; })(Files3 || (Files3 = {})); // node_modules/openai/resources/fine-tuning/jobs.mjs var Jobs = class extends APIResource { /** * Creates a fine-tuning job which begins the process of creating a new 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](https://platform.openai.com/docs/guides/fine-tuning) */ create(body, options) { return this._client.post("/fine_tuning/jobs", { body, ...options }); } /** * Get info about a fine-tuning job. * * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning) */ retrieve(fineTuningJobId, options) { return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options); } list(query = {}, options) { if (isRequestOptions(query)) { return this.list({}, query); } return this._client.getAPIList("/fine_tuning/jobs", FineTuningJobsPage, { query, ...options }); } /** * Immediately cancel a fine-tune job. */ cancel(fineTuningJobId, options) { return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options); } listEvents(fineTuningJobId, query = {}, options) { if (isRequestOptions(query)) { return this.listEvents(fineTuningJobId, {}, query); } return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, { query, ...options }); } }; var FineTuningJobsPage = class extends CursorPage { }; var FineTuningJobEventsPage = class extends CursorPage { }; (function(Jobs2) { Jobs2.FineTuningJobsPage = FineTuningJobsPage; Jobs2.FineTuningJobEventsPage = FineTuningJobEventsPage; })(Jobs || (Jobs = {})); // node_modules/openai/resources/fine-tuning/fine-tuning.mjs var FineTuning = class extends APIResource { constructor() { super(...arguments); this.jobs = new Jobs(this._client); } }; (function(FineTuning2) { FineTuning2.Jobs = Jobs; FineTuning2.FineTuningJobsPage = FineTuningJobsPage; FineTuning2.FineTuningJobEventsPage = FineTuningJobEventsPage; })(FineTuning || (FineTuning = {})); // node_modules/openai/resources/images.mjs var Images = class extends APIResource { /** * Creates a variation of a given image. */ createVariation(body, options) { return this._client.post("/images/variations", multipartFormRequestOptions({ body, ...options })); } /** * Creates an edited or extended image given an original image and a prompt. */ edit(body, options) { return this._client.post("/images/edits", multipartFormRequestOptions({ body, ...options })); } /** * Creates an image given a prompt. */ generate(body, options) { return this._client.post("/images/generations", { body, ...options }); } }; (function(Images2) { })(Images || (Images = {})); // node_modules/openai/resources/models.mjs var Models = class extends APIResource { /** * Retrieves a model instance, providing basic information about the model such as * the owner and permissioning. */ retrieve(model, options) { return this._client.get(`/models/${model}`, options); } /** * Lists the currently available models, and provides basic information about each * one such as the owner and availability. */ list(options) { return this._client.getAPIList("/models", ModelsPage, options); } /** * Delete a fine-tuned model. You must have the Owner role in your organization to * delete a model. */ del(model, options) { return this._client.delete(`/models/${model}`, options); } }; var ModelsPage = class extends Page { }; (function(Models2) { Models2.ModelsPage = ModelsPage; })(Models || (Models = {})); // node_modules/openai/resources/moderations.mjs var Moderations = class extends APIResource { /** * Classifies if text violates OpenAI's Content Policy */ create(body, options) { return this._client.post("/moderations", { body, ...options }); } }; (function(Moderations2) { })(Moderations || (Moderations = {})); // node_modules/openai/index.mjs var _a; var OpenAI = class extends APIClient { /** * API Client for interfacing with the OpenAI API. * * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API. * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. */ constructor({ baseURL = readEnv("OPENAI_BASE_URL"), apiKey = readEnv("OPENAI_API_KEY"), organization = ((_a3) => (_a3 = readEnv("OPENAI_ORG_ID")) != null ? _a3 : null)(), ...opts } = {}) { var _a4; if (apiKey === void 0) { throw new OpenAIError("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); } const options = { apiKey, organization, ...opts, baseURL: baseURL || `https://api.openai.com/v1` }; if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { throw new OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); } super({ baseURL: options.baseURL, timeout: (_a4 = options.timeout) != null ? _a4 : 6e5, httpAgent: options.httpAgent, maxRetries: options.maxRetries, fetch: options.fetch }); this.completions = new Completions3(this); this.chat = new Chat(this); this.embeddings = new Embeddings(this); this.files = new Files3(this); this.images = new Images(this); this.audio = new Audio(this); this.moderations = new Moderations(this); this.models = new Models(this); this.fineTuning = new FineTuning(this); this.beta = new Beta(this); this._options = options; this.apiKey = apiKey; this.organization = organization; } defaultQuery() { return this._options.defaultQuery; } defaultHeaders(opts) { return { ...super.defaultHeaders(opts), "OpenAI-Organization": this.organization, ...this._options.defaultHeaders }; } authHeaders(opts) { return { Authorization: `Bearer ${this.apiKey}` }; } }; _a = OpenAI; OpenAI.OpenAI = _a; OpenAI.OpenAIError = OpenAIError; OpenAI.APIError = APIError; OpenAI.APIConnectionError = APIConnectionError; OpenAI.APIConnectionTimeoutError = APIConnectionTimeoutError; OpenAI.APIUserAbortError = APIUserAbortError; OpenAI.NotFoundError = NotFoundError; OpenAI.ConflictError = ConflictError; OpenAI.RateLimitError = RateLimitError; OpenAI.BadRequestError = BadRequestError; OpenAI.AuthenticationError = AuthenticationError; OpenAI.InternalServerError = InternalServerError; OpenAI.PermissionDeniedError = PermissionDeniedError; OpenAI.UnprocessableEntityError = UnprocessableEntityError; var { OpenAIError: OpenAIError2, APIError: APIError2, APIConnectionError: APIConnectionError2, APIConnectionTimeoutError: APIConnectionTimeoutError2, APIUserAbortError: APIUserAbortError2, NotFoundError: NotFoundError2, ConflictError: ConflictError2, RateLimitError: RateLimitError2, BadRequestError: BadRequestError2, AuthenticationError: AuthenticationError2, InternalServerError: InternalServerError2, PermissionDeniedError: PermissionDeniedError2, UnprocessableEntityError: UnprocessableEntityError2 } = error_exports; (function(OpenAI2) { OpenAI2.toFile = toFile; OpenAI2.fileFromPath = fileFromPath; OpenAI2.Page = Page; OpenAI2.CursorPage = CursorPage; OpenAI2.Completions = Completions3; OpenAI2.Chat = Chat; OpenAI2.Embeddings = Embeddings; OpenAI2.Files = Files3; OpenAI2.FileObjectsPage = FileObjectsPage; OpenAI2.Images = Images; OpenAI2.Audio = Audio; OpenAI2.Moderations = Moderations; OpenAI2.Models = Models; OpenAI2.ModelsPage = ModelsPage; OpenAI2.FineTuning = FineTuning; OpenAI2.Beta = Beta; })(OpenAI || (OpenAI = {})); var openai_default = OpenAI; // src/client.ts var ZhipuAI = class extends openai_default { authHeaders() { return { Authorization: `${this.apiKey}` }; } constructor(apiToken, baseUrl) { super({ apiKey: apiToken, baseURL: baseUrl, dangerouslyAllowBrowser: true }); this.apiKey = apiToken; } }; // src/modal.ts var import_obsidian2 = require("obsidian"); var PromptTemplatesModal = class extends import_obsidian2.FuzzySuggestModal { constructor(app, templates, onChoose, lastApiCall) { super(app); this.templates = templates; this.onChoose = onChoose; this.lastApiCall = lastApiCall; } getItems() { return this.templates; } getItemText(template) { return template.title; } renderSuggestion(template, el) { var _a3; const title = template.item.title; let lastIndex = 0; const div = el.createEl("div"); for (const match2 of template.match.matches) { const before = title.slice(lastIndex, match2[0]); const matched = title.slice(match2[0], match2[0] + match2[1]); div.createEl("span", { text: before }); div.createEl("span", { text: matched, attr: { style: "font-weight: bold;" } }); lastIndex = match2[0] + match2[1]; } div.createEl("span", { text: title.slice(lastIndex) }); if (title === ((_a3 = this.lastApiCall) == null ? void 0 : _a3.template.title)) { el.createEl("small", { text: t("Last used") }); } } onChooseItem(template, evt) { this.onChoose(template); } }; var ApiCallInfoModal = class extends import_obsidian2.Modal { constructor(app, info) { super(app); this.info = info; } onOpen() { const { template, messages, startTime, endTime, result, error, usage } = this.info; const { contentEl } = this; let round = 1; const isMultiRound = "multiRound" in template.params && template.params.multiRound; contentEl.createEl("h1", { text: isMultiRound ? t("Multi-round Conversation") : template.title }); for (const msg of messages) { if (msg.content) { if (msg.role === "assistant") { contentEl.createEl("h4", { text: t("Round") + " " + round + " " + t("generate content") }); round++; } contentEl.createEl("textarea", { text: msg.content.toString(), attr: { style: "width: 100%;", readonly: true, rows: msg.role === "assistant" ? 3 : 1 } }); } } const timeInfoFn = new Function("startTime", "endTime", "duration", `return \`${t("TimeInfoTemplate")}\`;`); contentEl.createEl("div").createEl("p", { text: timeInfoFn( formatDate(startTime), endTime ? formatDate(endTime) : "N/A", endTime ? formatDuration(endTime.getTime() - startTime.getTime()) : "N/A" ), attr: { style: "white-space: pre-wrap; font-family: monospace;" } }); if (result) { contentEl.createEl("h4", { text: isMultiRound ? t("Round") + " " + round + " " + t("generate content") : t("Generate content") }); contentEl.createEl("textarea", { text: result, attr: { style: "width: 100%;", readonly: true, rows: 3 } }); } if (error) { contentEl.createEl("h4", { text: ERROR_MARK + " Error" }); contentEl.createEl("textarea", { text: error, attr: { style: "width: 100%;", readonly: true, rows: 3 } }); } if (usage) { const usageTemplateFn = new Function( "prompt_tokens", "completion_tokens", "total_tokens", `return \`${t("UsageInfoTemplate")}\`;` ); const { prompt_tokens, completion_tokens, total_tokens } = usage; contentEl.createEl("div").createEl("p", { text: usageTemplateFn( formatTokenNumber(prompt_tokens), formatTokenNumber(completion_tokens), formatTokenNumber(total_tokens) ), attr: { style: "white-space: pre-wrap; font-family: monospace;" } }); } const detailsEl = contentEl.createEl("details"); detailsEl.createEl("p", { text: JSON.stringify(template.params, null, 2) }); detailsEl.createEl("summary", { text: "Params" }); } onClose() { const { contentEl } = this; contentEl.empty(); } }; var formatDate = (d) => { const hours = d.getHours().toString().padStart(2, "0"); const minutes = d.getMinutes().toString().padStart(2, "0"); const seconds = d.getSeconds().toString().padStart(2, "0"); return `${hours}:${minutes}:${seconds}`; }; var formatDuration = (d) => `${(d / 1e3).toFixed(2)}s`; var formatTokenNumber = (n) => n.toString().padStart(4); // src/promptEn.ts var promptEn = esm_default` - 如果你想使用中文版本的提示词模板,请在插件设置中修改。 - This document is formatted according to Obsidian's slide format, using "---" to separate the content of each page. - The first page is an explanation; each subsequent page is a prompt template. - \`##\` is the title. When the 'Generate from...' command is activated, the title appears in the dropdown list. - \`%%\` contains technical parameters, referring to the documentation of [Zhipu AI](https://open.bigmodel.cn/dev/api). - The text between ✨💡 and 💡✨ is the template content. The plugin will replace \`{{selection}}\` with the selected text to obtain the final prompt. - If you want to check whether the final prompt of the chat meets expectations, or for more technical parameters, use the command "Show the chat details". --- ## ✨ Generate Content ✨💡 {{selection}} 💡✨ --- ## 🖼️ Generate Image %% model: cogview-3 %% ✨💡 {{selection}} 💡✨ --- ## 📚 Knowledge %% knowledge_id: "your-knowledge-id" prompt_template: | Search for the answer to the question """ {{question}} """ in the document """ {{knowledge}} """ . If you find the answer, respond to the question using only the statements from the document. If the answer is not found, use your own knowledge to respond and inform the user that the information does not come from the document. Do not repeat the question; start answering directly. %% ✨💡 {{selection}} 💡✨ `; // src/promptZh.ts var promptZh = esm_default` - If you wish to use English prompts, please adjust the settings accordingly. - 本文件按照 obsidian 的幻灯片格式,用“---”来分隔每一页的内容 - 第一页是说明,后面的每一页都是一个提示词模板 - \`##\` 是标题。当启动命令“生成内容”,标题显示在弹窗列表中 - \`%%\`里面是技术参数,参考[智谱AI的接口文档](https://open.bigmodel.cn/dev/api) - 在✨💡和💡✨之间的文本是模板内容,插件会把 \`{{selection}}\`替换为选中的文本,得到最终的提示词 - 如果你想查看对话的最终提示词是否符合预期,或者更多技术参数,启动命令“显示对话详情” --- ## ✨ 生成内容 ✨💡 {{selection}} 💡✨ --- ## 🖼️ 文生图 %% model: cogview-3 %% ✨💡 {{selection}} 💡✨ --- ## 📚 知识库 %% knowledge_id: "你的知识库id" prompt_template: | 从文档 """ {{knowledge}} """ 中找问题 """ {{question}} """ 的答案,找到答案就仅使用文档语句回答问题,找不到答案就用自身知识回答并且告诉用户该信息不是来自文档。 不要复述问题,直接开始回答。 %% ✨💡 {{selection}} 💡✨ --- ## 🔠 翻译 ✨💡 把以下文本翻译为中文:{{selection}} 💡✨ `; // src/settingTab.ts var import_obsidian3 = require("obsidian"); // src/settings.ts var DEFAULT_SETTINGS = { apiKey: "", baseURL: "https://open.bigmodel.cn/api/paas/v4/", tokenExpireInMinutes: 60, rootFolder: "Aizhipu", multiRoundTemplate: { title: "multi-round", template: "", params: { model: "glm-4", multiRound: true, temperature: 0.95, top_p: 0.7, max_tokens: 8192 } } }; // src/settingTab.ts var AIZhipuSettingTab = class extends import_obsidian3.PluginSettingTab { constructor(app, plugin) { super(app, plugin); this.plugin = plugin; } display() { const { containerEl } = this; containerEl.empty(); new import_obsidian3.Setting(containerEl).setName(t("Zhipu API key")).setDesc(t("Obtain key from https://open.bigmodel.cn")).addText( (text) => text.setPlaceholder(t("Enter your key")).setValue(this.plugin.settings.apiKey).onChange(async (value) => { this.plugin.settings.apiKey = value; await this.plugin.saveSettings(); }) ); containerEl.createEl("br"); containerEl.createEl("h3", { text: t("Single Round Conversation") }); new import_obsidian3.Setting(containerEl).setName(t("Prompt template file")).setDesc( t( "Template file support both Chinese and English languages, with the default being the software's language setting." ) ).addDropdown( (dropdown) => dropdown.addOption(promptZhFileName, `${DEFAULT_SETTINGS.rootFolder}/${promptZhFileName}`).addOption(promptEnFileName, `${DEFAULT_SETTINGS.rootFolder}/${promptEnFileName}`).setValue(this.plugin.settings.promptFileName ? this.plugin.settings.promptFileName : t("PromptTemplates")).onChange(async (value) => { this.plugin.settings.promptFileName = value; await this.plugin.saveSettings(); }) ); containerEl.createEl("br"); containerEl.createEl("h3", { text: t("Multi-round Conversation") }); containerEl.createEl("p", { text: t('The starting mark of Multi-round conversation is two consecutive lines of horizontal dashes, such as two lines of "---", and the ending mark is a single line of horizontal dashes.') }); new import_obsidian3.Setting(containerEl).setName("temperature").setDesc(t("Sampling temperature controls the randomness of the output. A higher value makes the output more random and creative; a lower value makes the output more stable or deterministic.")).addSlider( (slider) => slider.setLimits(0.01, 1, 0.01).setValue(this.plugin.settings.multiRoundTemplate.params.temperature).setDynamicTooltip().onChange(async (value) => { this.plugin.settings.multiRoundTemplate.params.temperature = value; await this.plugin.saveSettings(); }) ); new import_obsidian3.Setting(containerEl).setName("top_p").setDesc(t("0.1 means that the model decoder only considers taking tokens from the candidate set of the top 10% probability.")).addSlider( (slider) => slider.setLimits(0.01, 0.99, 0.01).setValue(this.plugin.settings.multiRoundTemplate.params.top_p).setDynamicTooltip().onChange(async (value) => { this.plugin.settings.multiRoundTemplate.params.top_p = value; await this.plugin.saveSettings(); }) ); new import_obsidian3.Setting(containerEl).setName("max_tokens").setDesc(t("The maximum number of tokens to generate in the completion")).addSlider( (slider) => slider.setLimits(1024, 8192, 64).setValue(this.plugin.settings.multiRoundTemplate.params.max_tokens).setDynamicTooltip().onChange(async (value) => { this.plugin.settings.multiRoundTemplate.params.max_tokens = value; await this.plugin.saveSettings(); }) ); } }; // node_modules/jose/dist/browser/runtime/webcrypto.js var webcrypto_default = crypto; var isCryptoKey = (key) => key instanceof CryptoKey; // node_modules/jose/dist/browser/lib/buffer_utils.js var encoder = new TextEncoder(); var decoder = new TextDecoder(); var MAX_INT32 = 2 ** 32; function concat(...buffers) { const size = buffers.reduce((acc, { length }) => acc + length, 0); const buf = new Uint8Array(size); let i = 0; buffers.forEach((buffer) => { buf.set(buffer, i); i += buffer.length; }); return buf; } // node_modules/jose/dist/browser/runtime/base64url.js var encodeBase64 = (input) => { let unencoded = input; if (typeof unencoded === "string") { unencoded = encoder.encode(unencoded); } const CHUNK_SIZE = 32768; const arr = []; for (let i = 0; i < unencoded.length; i += CHUNK_SIZE) { arr.push(String.fromCharCode.apply(null, unencoded.subarray(i, i + CHUNK_SIZE))); } return btoa(arr.join("")); }; var encode = (input) => { return encodeBase64(input).replace(/=/g, "").replace(/\+/g, "-").replace(/\//g, "_"); }; var decodeBase64 = (encoded) => { const binary = atob(encoded); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } return bytes; }; var decode = (input) => { let encoded = input; if (encoded instanceof Uint8Array) { encoded = decoder.decode(encoded); } encoded = encoded.replace(/-/g, "+").replace(/_/g, "/").replace(/\s/g, ""); try { return decodeBase64(encoded); } catch (e) { throw new TypeError("The input to be decoded is not correctly encoded."); } }; // node_modules/jose/dist/browser/util/errors.js var errors_exports = {}; __export(errors_exports, { JOSEAlgNotAllowed: () => JOSEAlgNotAllowed, JOSEError: () => JOSEError, JOSENotSupported: () => JOSENotSupported, JWEDecryptionFailed: () => JWEDecryptionFailed, JWEInvalid: () => JWEInvalid, JWKInvalid: () => JWKInvalid, JWKSInvalid: () => JWKSInvalid, JWKSMultipleMatchingKeys: () => JWKSMultipleMatchingKeys, JWKSNoMatchingKey: () => JWKSNoMatchingKey, JWKSTimeout: () => JWKSTimeout, JWSInvalid: () => JWSInvalid, JWSSignatureVerificationFailed: () => JWSSignatureVerificationFailed, JWTClaimValidationFailed: () => JWTClaimValidationFailed, JWTExpired: () => JWTExpired, JWTInvalid: () => JWTInvalid }); var JOSEError = class extends Error { static get code() { return "ERR_JOSE_GENERIC"; } constructor(message2) { var _a3; super(message2); this.code = "ERR_JOSE_GENERIC"; this.name = this.constructor.name; (_a3 = Error.captureStackTrace) == null ? void 0 : _a3.call(Error, this, this.constructor); } }; var JWTClaimValidationFailed = class extends JOSEError { static get code() { return "ERR_JWT_CLAIM_VALIDATION_FAILED"; } constructor(message2, claim = "unspecified", reason = "unspecified") { super(message2); this.code = "ERR_JWT_CLAIM_VALIDATION_FAILED"; this.claim = claim; this.reason = reason; } }; var JWTExpired = class extends JOSEError { static get code() { return "ERR_JWT_EXPIRED"; } constructor(message2, claim = "unspecified", reason = "unspecified") { super(message2); this.code = "ERR_JWT_EXPIRED"; this.claim = claim; this.reason = reason; } }; var JOSEAlgNotAllowed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_ALG_NOT_ALLOWED"; } static get code() { return "ERR_JOSE_ALG_NOT_ALLOWED"; } }; var JOSENotSupported = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JOSE_NOT_SUPPORTED"; } static get code() { return "ERR_JOSE_NOT_SUPPORTED"; } }; var JWEDecryptionFailed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_DECRYPTION_FAILED"; this.message = "decryption operation failed"; } static get code() { return "ERR_JWE_DECRYPTION_FAILED"; } }; var JWEInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWE_INVALID"; } static get code() { return "ERR_JWE_INVALID"; } }; var JWSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_INVALID"; } static get code() { return "ERR_JWS_INVALID"; } }; var JWTInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWT_INVALID"; } static get code() { return "ERR_JWT_INVALID"; } }; var JWKInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWK_INVALID"; } static get code() { return "ERR_JWK_INVALID"; } }; var JWKSInvalid = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_INVALID"; } static get code() { return "ERR_JWKS_INVALID"; } }; var JWKSNoMatchingKey = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_NO_MATCHING_KEY"; this.message = "no applicable key found in the JSON Web Key Set"; } static get code() { return "ERR_JWKS_NO_MATCHING_KEY"; } }; var JWKSMultipleMatchingKeys = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; this.message = "multiple matching keys found in the JSON Web Key Set"; } static get code() { return "ERR_JWKS_MULTIPLE_MATCHING_KEYS"; } }; var JWKSTimeout = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWKS_TIMEOUT"; this.message = "request timed out"; } static get code() { return "ERR_JWKS_TIMEOUT"; } }; var JWSSignatureVerificationFailed = class extends JOSEError { constructor() { super(...arguments); this.code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; this.message = "signature verification failed"; } static get code() { return "ERR_JWS_SIGNATURE_VERIFICATION_FAILED"; } }; // node_modules/jose/dist/browser/runtime/random.js var random_default = webcrypto_default.getRandomValues.bind(webcrypto_default); // node_modules/jose/dist/browser/lib/crypto_key.js function unusable(name, prop = "algorithm.name") { return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`); } function isAlgorithm(algorithm, name) { return algorithm.name === name; } function getHashLength(hash) { return parseInt(hash.name.slice(4), 10); } function getNamedCurve(alg) { switch (alg) { case "ES256": return "P-256"; case "ES384": return "P-384"; case "ES512": return "P-521"; default: throw new Error("unreachable"); } } function checkUsage(key, usages) { if (usages.length && !usages.some((expected) => key.usages.includes(expected))) { let msg = "CryptoKey does not support this operation, its usages must include "; if (usages.length > 2) { const last = usages.pop(); msg += `one of ${usages.join(", ")}, or ${last}.`; } else if (usages.length === 2) { msg += `one of ${usages[0]} or ${usages[1]}.`; } else { msg += `${usages[0]}.`; } throw new TypeError(msg); } } function checkSigCryptoKey(key, alg, ...usages) { switch (alg) { case "HS256": case "HS384": case "HS512": { if (!isAlgorithm(key.algorithm, "HMAC")) throw unusable("HMAC"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "RS256": case "RS384": case "RS512": { if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5")) throw unusable("RSASSA-PKCS1-v1_5"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "PS256": case "PS384": case "PS512": { if (!isAlgorithm(key.algorithm, "RSA-PSS")) throw unusable("RSA-PSS"); const expected = parseInt(alg.slice(2), 10); const actual = getHashLength(key.algorithm.hash); if (actual !== expected) throw unusable(`SHA-${expected}`, "algorithm.hash"); break; } case "EdDSA": { if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") { throw unusable("Ed25519 or Ed448"); } break; } case "ES256": case "ES384": case "ES512": { if (!isAlgorithm(key.algorithm, "ECDSA")) throw unusable("ECDSA"); const expected = getNamedCurve(alg); const actual = key.algorithm.namedCurve; if (actual !== expected) throw unusable(expected, "algorithm.namedCurve"); break; } default: throw new TypeError("CryptoKey does not support this operation"); } checkUsage(key, usages); } // node_modules/jose/dist/browser/lib/invalid_key_input.js function message(msg, actual, ...types2) { if (types2.length > 2) { const last = types2.pop(); msg += `one of type ${types2.join(", ")}, or ${last}.`; } else if (types2.length === 2) { msg += `one of type ${types2[0]} or ${types2[1]}.`; } else { msg += `of type ${types2[0]}.`; } if (actual == null) { msg += ` Received ${actual}`; } else if (typeof actual === "function" && actual.name) { msg += ` Received function ${actual.name}`; } else if (typeof actual === "object" && actual != null) { if (actual.constructor && actual.constructor.name) { msg += ` Received an instance of ${actual.constructor.name}`; } } return msg; } var invalid_key_input_default = (actual, ...types2) => { return message("Key must be ", actual, ...types2); }; function withAlg(alg, actual, ...types2) { return message(`Key for the ${alg} algorithm must be `, actual, ...types2); } // node_modules/jose/dist/browser/runtime/is_key_like.js var is_key_like_default = (key) => { return isCryptoKey(key); }; var types = ["CryptoKey"]; // node_modules/jose/dist/browser/lib/is_disjoint.js var isDisjoint = (...headers) => { const sources = headers.filter(Boolean); if (sources.length === 0 || sources.length === 1) { return true; } let acc; for (const header of sources) { const parameters = Object.keys(header); if (!acc || acc.size === 0) { acc = new Set(parameters); continue; } for (const parameter of parameters) { if (acc.has(parameter)) { return false; } acc.add(parameter); } } return true; }; var is_disjoint_default = isDisjoint; // node_modules/jose/dist/browser/lib/is_object.js function isObjectLike(value) { return typeof value === "object" && value !== null; } function isObject(input) { if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") { return false; } if (Object.getPrototypeOf(input) === null) { return true; } let proto = input; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(input) === proto; } // node_modules/jose/dist/browser/runtime/check_key_length.js var check_key_length_default = (alg, key) => { if (alg.startsWith("RS") || alg.startsWith("PS")) { const { modulusLength } = key.algorithm; if (typeof modulusLength !== "number" || modulusLength < 2048) { throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`); } } }; // node_modules/jose/dist/browser/lib/check_key_type.js var symmetricTypeCheck = (alg, key) => { if (key instanceof Uint8Array) return; if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types, "Uint8Array")); } if (key.type !== "secret") { throw new TypeError(`${types.join(" or ")} instances for symmetric algorithms must be of type "secret"`); } }; var asymmetricTypeCheck = (alg, key, usage) => { if (!is_key_like_default(key)) { throw new TypeError(withAlg(alg, key, ...types)); } if (key.type === "secret") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`); } if (usage === "sign" && key.type === "public") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`); } if (usage === "decrypt" && key.type === "public") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`); } if (key.algorithm && usage === "verify" && key.type === "private") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`); } if (key.algorithm && usage === "encrypt" && key.type === "private") { throw new TypeError(`${types.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`); } }; var checkKeyType = (alg, key, usage) => { const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg); if (symmetric) { symmetricTypeCheck(alg, key); } else { asymmetricTypeCheck(alg, key, usage); } }; var check_key_type_default = checkKeyType; // node_modules/jose/dist/browser/lib/validate_crit.js function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) { if (joseHeader.crit !== void 0 && protectedHeader.crit === void 0) { throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected'); } if (!protectedHeader || protectedHeader.crit === void 0) { return /* @__PURE__ */ new Set(); } if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) { throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present'); } let recognized; if (recognizedOption !== void 0) { recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]); } else { recognized = recognizedDefault; } for (const parameter of protectedHeader.crit) { if (!recognized.has(parameter)) { throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`); } if (joseHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" is missing`); } else if (recognized.get(parameter) && protectedHeader[parameter] === void 0) { throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`); } } return new Set(protectedHeader.crit); } var validate_crit_default = validateCrit; // node_modules/jose/dist/browser/jwe/flattened/encrypt.js var unprotected = Symbol(); // node_modules/jose/dist/browser/runtime/subtle_dsa.js function subtleDsa(alg, algorithm) { const hash = `SHA-${alg.slice(-3)}`; switch (alg) { case "HS256": case "HS384": case "HS512": return { hash, name: "HMAC" }; case "PS256": case "PS384": case "PS512": return { hash, name: "RSA-PSS", saltLength: alg.slice(-3) >> 3 }; case "RS256": case "RS384": case "RS512": return { hash, name: "RSASSA-PKCS1-v1_5" }; case "ES256": case "ES384": case "ES512": return { hash, name: "ECDSA", namedCurve: algorithm.namedCurve }; case "EdDSA": return { name: algorithm.name }; default: throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`); } } // node_modules/jose/dist/browser/runtime/get_sign_verify_key.js function getCryptoKey(alg, key, usage) { if (isCryptoKey(key)) { checkSigCryptoKey(key, alg, usage); return key; } if (key instanceof Uint8Array) { if (!alg.startsWith("HS")) { throw new TypeError(invalid_key_input_default(key, ...types)); } return webcrypto_default.subtle.importKey("raw", key, { hash: `SHA-${alg.slice(-3)}`, name: "HMAC" }, false, [usage]); } throw new TypeError(invalid_key_input_default(key, ...types, "Uint8Array")); } // node_modules/jose/dist/browser/lib/epoch.js var epoch_default = (date) => Math.floor(date.getTime() / 1e3); // node_modules/jose/dist/browser/lib/secs.js var minute = 60; var hour = minute * 60; var day = hour * 24; var week = day * 7; var year = day * 365.25; var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i; var secs_default = (str2) => { const matched = REGEX.exec(str2); if (!matched || matched[4] && matched[1]) { throw new TypeError("Invalid time period format"); } const value = parseFloat(matched[2]); const unit = matched[3].toLowerCase(); let numericDate; switch (unit) { case "sec": case "secs": case "second": case "seconds": case "s": numericDate = Math.round(value); break; case "minute": case "minutes": case "min": case "mins": case "m": numericDate = Math.round(value * minute); break; case "hour": case "hours": case "hr": case "hrs": case "h": numericDate = Math.round(value * hour); break; case "day": case "days": case "d": numericDate = Math.round(value * day); break; case "week": case "weeks": case "w": numericDate = Math.round(value * week); break; default: numericDate = Math.round(value * year); break; } if (matched[1] === "-" || matched[4] === "ago") { return -numericDate; } return numericDate; }; // node_modules/jose/dist/browser/runtime/sign.js var sign = async (alg, key, data) => { const cryptoKey = await getCryptoKey(alg, key, "sign"); check_key_length_default(alg, cryptoKey); const signature = await webcrypto_default.subtle.sign(subtleDsa(alg, cryptoKey.algorithm), cryptoKey, data); return new Uint8Array(signature); }; var sign_default = sign; // node_modules/jose/dist/browser/jws/flattened/sign.js var FlattenedSign = class { constructor(payload) { if (!(payload instanceof Uint8Array)) { throw new TypeError("payload must be an instance of Uint8Array"); } this._payload = payload; } setProtectedHeader(protectedHeader) { if (this._protectedHeader) { throw new TypeError("setProtectedHeader can only be called once"); } this._protectedHeader = protectedHeader; return this; } setUnprotectedHeader(unprotectedHeader) { if (this._unprotectedHeader) { throw new TypeError("setUnprotectedHeader can only be called once"); } this._unprotectedHeader = unprotectedHeader; return this; } async sign(key, options) { if (!this._protectedHeader && !this._unprotectedHeader) { throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()"); } if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) { throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint"); } const joseHeader = { ...this._protectedHeader, ...this._unprotectedHeader }; const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options == null ? void 0 : options.crit, this._protectedHeader, joseHeader); let b64 = true; if (extensions.has("b64")) { b64 = this._protectedHeader.b64; if (typeof b64 !== "boolean") { throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean'); } } const { alg } = joseHeader; if (typeof alg !== "string" || !alg) { throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid'); } check_key_type_default(alg, key, "sign"); let payload = this._payload; if (b64) { payload = encoder.encode(encode(payload)); } let protectedHeader; if (this._protectedHeader) { protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader))); } else { protectedHeader = encoder.encode(""); } const data = concat(protectedHeader, encoder.encode("."), payload); const signature = await sign_default(alg, key, data); const jws = { signature: encode(signature), payload: "" }; if (b64) { jws.payload = decoder.decode(payload); } if (this._unprotectedHeader) { jws.header = this._unprotectedHeader; } if (this._protectedHeader) { jws.protected = decoder.decode(protectedHeader); } return jws; } }; // node_modules/jose/dist/browser/jws/compact/sign.js var CompactSign = class { constructor(payload) { this._flattened = new FlattenedSign(payload); } setProtectedHeader(protectedHeader) { this._flattened.setProtectedHeader(protectedHeader); return this; } async sign(key, options) { const jws = await this._flattened.sign(key, options); if (jws.payload === void 0) { throw new TypeError("use the flattened module for creating JWS with b64: false"); } return `${jws.protected}.${jws.payload}.${jws.signature}`; } }; // node_modules/jose/dist/browser/jwt/produce.js function validateInput(label, input) { if (!Number.isFinite(input)) { throw new TypeError(`Invalid ${label} input`); } return input; } var ProduceJWT = class { constructor(payload = {}) { if (!isObject(payload)) { throw new TypeError("JWT Claims Set MUST be an object"); } this._payload = payload; } setIssuer(issuer) { this._payload = { ...this._payload, iss: issuer }; return this; } setSubject(subject) { this._payload = { ...this._payload, sub: subject }; return this; } setAudience(audience) { this._payload = { ...this._payload, aud: audience }; return this; } setJti(jwtId) { this._payload = { ...this._payload, jti: jwtId }; return this; } setNotBefore(input) { if (typeof input === "number") { this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) }; } else if (input instanceof Date) { this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) }; } else { this._payload = { ...this._payload, nbf: epoch_default(new Date()) + secs_default(input) }; } return this; } setExpirationTime(input) { if (typeof input === "number") { this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) }; } else if (input instanceof Date) { this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) }; } else { this._payload = { ...this._payload, exp: epoch_default(new Date()) + secs_default(input) }; } return this; } setIssuedAt(input) { if (typeof input === "undefined") { this._payload = { ...this._payload, iat: epoch_default(new Date()) }; } else if (input instanceof Date) { this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) }; } else if (typeof input === "string") { this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(new Date()) + secs_default(input)) }; } else { this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) }; } return this; } }; // node_modules/jose/dist/browser/jwt/sign.js var SignJWT = class extends ProduceJWT { setProtectedHeader(protectedHeader) { this._protectedHeader = protectedHeader; return this; } async sign(key, options) { var _a3; const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload))); sig.setProtectedHeader(this._protectedHeader); if (Array.isArray((_a3 = this._protectedHeader) == null ? void 0 : _a3.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) { throw new JWTInvalid("JWTs MUST NOT use unencoded payload"); } return sig.sign(key, options); } }; // node_modules/jose/dist/browser/jwks/remote.js var USER_AGENT; var _a2, _b; if (typeof navigator === "undefined" || !((_b = (_a2 = navigator.userAgent) == null ? void 0 : _a2.startsWith) == null ? void 0 : _b.call(_a2, "Mozilla/5.0 "))) { const NAME = "jose"; const VERSION2 = "v5.2.0"; USER_AGENT = `${NAME}/${VERSION2}`; } // node_modules/jose/dist/browser/util/base64url.js var base64url_exports2 = {}; __export(base64url_exports2, { decode: () => decode2, encode: () => encode2 }); var encode2 = encode; var decode2 = decode; // src/token.ts var createToken = async (apiKeySecret, expireInMinutes) => { const [apiKey, apiSecret] = apiKeySecret.split("."); if (!apiKey || !apiSecret) throw new Error('Invalid API key secret, must be in the format "apiKey.apiSecret"'); const now = Date.now(); const payload = { api_key: apiKey, exp: now + expireInMinutes * 60 * 1e3, timestamp: now }; const encoded = await new SignJWT({ ...payload }).setProtectedHeader({ alg: "HS256", sign_type: "SIGN" }).sign(new TextEncoder().encode(apiSecret)); return { id: encoded, exp: payload.exp, apiKeySecret }; }; var validOrCreate = async (currentToken, apiKeySecret, expireInMinutes) => { const now = Date.now(); if (currentToken && currentToken.apiKeySecret === apiKeySecret && currentToken.exp > now + 3 * 60 * 1e3) { return { isValid: true, token: currentToken }; } const newToken = await createToken(apiKeySecret, expireInMinutes); return { isValid: false, token: newToken }; }; // src/main.ts var AIZhipuPlugin = class extends import_obsidian4.Plugin { async onload() { await this.loadSettings(); console.debug("loading AI Zhipu plugin..."); await this.createPromptFileIfNotExist(); this.addCommand({ id: "generate", name: t("Generate from the selected text / line / block"), editorCallback: async (editor, view) => { if (this.settings.apiKey.length <= 1) { new import_obsidian4.Notice(t("ZhipuAI API Key is not provided.")); return; } const lines = editor.getValue().split("\n"); const current = editor.getCursor("to").line; const multiRoundDivider = findMultiRoundRange(lines, current); if (multiRoundDivider) { let preBlocks = []; try { preBlocks = findPreMsgBlocks(lines, multiRoundDivider.start, current); } catch (e) { new import_obsidian4.Notice(e.message); return; } const round = preBlocks.filter((block) => block._tag === "assistant").length + 1; new import_obsidian4.Notice(t("Round") + " " + round + " " + t("generate content")); this.generateText(editor, this.settings.multiRoundTemplate, preBlocks); } else { const onChoose = (template) => { this.generateText(editor, template); }; const promptTemplates = await this.fetchPromptTemplates(); new PromptTemplatesModal(this.app, promptTemplates, onChoose, this.apiCallInfo).open(); } } }); this.addCommand({ id: "select-block", name: t("Select \u2728block\u2728"), editorCallback: async (editor, view) => { const block = findBlockByCurrentLine(editor.getValue().split("\n"), editor.getCursor("to").line); if (block) { const { start, end } = block; editor.setSelection({ line: start + 1, ch: 0 }, { line: end - 1, ch: editor.getLine(end - 1).length }); } else { new import_obsidian4.Notice(t("Cannot find a valid block.")); } } }); this.addCommand({ id: "show-chat-detail", name: t("Show the chat details"), callback: () => { if (!this.apiCallInfo) { new import_obsidian4.Notice(t("No chat in this session yet.")); return; } new ApiCallInfoModal(this.app, this.apiCallInfo).open(); } }); this.addCommand({ id: "open-template-file", name: t("Open prompt template file"), callback: async () => { const promptFilePath = (0, import_obsidian4.normalizePath)(`${this.settings.rootFolder}/${this.settings.promptFileName}.md`); const file = this.app.vault.getAbstractFileByPath(promptFilePath); if (!file) { new import_obsidian4.Notice(t("Cannot find prompt template file.")); return; } await this.app.workspace.openLinkText("", file.path, true); } }); this.addSettingTab(new AIZhipuSettingTab(this.app, this)); } onunload() { } async createPromptFileIfNotExist() { if (!await this.app.vault.adapter.exists((0, import_obsidian4.normalizePath)(this.settings.rootFolder))) { await this.app.vault.createFolder(this.settings.rootFolder); new import_obsidian4.Notice(t("Create template folder") + " " + this.settings.rootFolder); } const promptEnFilePath = (0, import_obsidian4.normalizePath)(`${this.settings.rootFolder}/${promptEnFileName}.md`); if (!await this.app.vault.adapter.exists(promptEnFilePath)) { await this.app.vault.create(promptEnFilePath, promptEn); new import_obsidian4.Notice(t("Create template file") + " " + promptEnFileName); } const promptZhFilePath = (0, import_obsidian4.normalizePath)(`${this.settings.rootFolder}/${promptZhFileName}.md`); if (!await this.app.vault.adapter.exists(promptZhFilePath)) { await this.app.vault.create(promptZhFilePath, promptZh); new import_obsidian4.Notice(t("Create template file") + " " + promptZhFileName); } } async loadSettings() { const promptFileName = t("PromptTemplates"); this.settings = Object.assign({ promptFileName }, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings() { await this.saveData(this.settings); } async fetchPromptTemplates() { const promptFilePath = (0, import_obsidian4.normalizePath)(`${this.settings.rootFolder}/${this.settings.promptFileName}.md`); const templateFile = this.app.vault.getAbstractFileByPath(promptFilePath); let fileContent; if (templateFile instanceof import_obsidian4.TFile) { fileContent = await this.app.vault.cachedRead(templateFile); } else { console.warn(`Cannot getAbstractFileByPath ${promptFilePath}`); console.warn(`load preset prompt`); fileContent = this.getPresetPromptFileContent(); } return getTemplates(fileContent); } getPresetPromptFileContent() { return this.settings.promptFileName === promptZhFileName ? promptZh : promptEn; } async getClient() { const { isValid, token } = await validOrCreate(this.token, this.settings.apiKey, this.settings.tokenExpireInMinutes); if (!isValid) { this.token = token; } if (!this.token) throw new Error("Cannot get token."); const client = new ZhipuAI(this.token.id, this.settings.baseURL); return client; } createBlockFromSelection(editor, selection) { const block = { _tag: "user", content: selection, start: editor.getCursor("from").line + 1, end: editor.getCursor("to").line + 3 }; editor.replaceSelection( LINE_BREAK + USER_MARK_START + LINE_BREAK + selection.trimEnd() + LINE_BREAK + USER_MARK_END + LINE_BREAK ); return block; } createBlockFromLine(editor, current) { const lineContent = editor.getLine(current); if (lineContent.trim().length === 0) { throw new Error("Nothing was selected"); } editor.replaceRange( USER_MARK_START + LINE_BREAK + lineContent.trimEnd() + LINE_BREAK + USER_MARK_END, { line: current, ch: 0 }, { line: current, ch: lineContent.length } ); return { _tag: "user", content: lineContent, start: current, end: current + 2 }; } async generateText(editor, template, preBlocks = []) { var _a3, _b2; let block = findBlockByCurrentLine(editor.getValue().split("\n"), editor.getCursor("to").line); if (!block) { const selection2 = editor.getSelection(); if (selection2.trim().length > 0) { block = this.createBlockFromSelection(editor, selection2); } else { const current = editor.getCursor("to").line; if (editor.getLine(current).trim().length === 0) { new import_obsidian4.Notice(t("Nothing was selected")); return; } block = this.createBlockFromLine(editor, current); } } else if (block._tag === "assistant") { new import_obsidian4.Notice( t( "This is the block for generating content. Copy the selected text outside of this block, and then execute the command." ), 1e3 * 5 ); return; } else if (block.content.trim().length === 0) { new import_obsidian4.Notice(t("Block is empty")); return; } console.debug("block", block); editor.setSelection( { line: block.start + 1, ch: 0 }, { line: block.end - 1, ch: editor.getLine(block.end - 1).length } ); const selection = editor.getSelection(); console.debug("block.content", block.content); console.debug("selection", selection); const nextEmptyBlock = findNextEmptyAssistBlock(editor.getValue().split("\n"), block.end + 1); if (nextEmptyBlock) { console.debug("nextEmptyBlock", nextEmptyBlock); editor.replaceRange( "", { line: nextEmptyBlock.start, ch: 0 }, { line: nextEmptyBlock.end, ch: editor.getLine(nextEmptyBlock.end).length } ); new import_obsidian4.Notice(t("Regenerate block")); } let prompt = selection; if (template.template && template.template.trim().length > 0 && template.template.trim() !== "{{selection}}") { const templateFn = import_handlebars.default.compile(template.template); prompt = templateFn({ selection }); } console.debug("prompt", prompt); console.debug("template", template); let LnToWrite = block.end; const onConnect = () => { editor.replaceRange(LINE_BREAK + ASSISTANT_MARK_START + LINE_BREAK, { line: LnToWrite, ch: editor.getLine(LnToWrite).length }); LnToWrite = LnToWrite + 2; }; const onContent = (diff) => { const lines = diff.split("\n"); if (lines.length > 1) { editor.replaceRange(diff, { line: LnToWrite, ch: editor.getLine(LnToWrite).length }); LnToWrite = LnToWrite + lines.length - 1; } else { this.setLineThenScroll(editor, LnToWrite, diff); } }; const preMsg = preBlocks.map( (block2) => block2._tag === "user" ? { role: "user", content: block2.content } : { role: "assistant", content: block2.content } ); this.apiCallInfo = newApiCallInfo(template, [...preMsg, { role: "user", content: prompt }]); try { const client = await this.getClient(); if (ImageGenerateParams.is(template.params)) { const response = await client.images.generate({ prompt, model: this.apiCallInfo.template.params.model }); console.debug("response", response); const url = (_a3 = response.data[0]) == null ? void 0 : _a3.url; if (url) { onConnect(); onContent(`![](${url})${LINE_BREAK}`); } else { onConnect(); onContent(t("Failed to generate image") + LINE_BREAK); } this.apiCallInfo.endTime = new Date(); this.apiCallInfo.result = ((_b2 = response.data[0]) == null ? void 0 : _b2.url) || null; } else if (KnowledgeChatParams.is(template.params)) { const tools = [ { type: "retrieval", retrieval: { knowledge_id: template.params.knowledge_id, prompt_template: template.params.prompt_template } } ]; console.debug("prompt_template", template.params.prompt_template); const knowledgeChat = client.beta.chat.completions.runTools({ ...toChatCompletionStreamParams(this.apiCallInfo), stream: true, tools }).on("connect", onConnect).on("content", (diff) => onContent(diff)); const final = await knowledgeChat.finalChatCompletion(); const content = final.choices[0].message.content; this.apiCallInfo.endTime = new Date(); this.apiCallInfo.result = content; this.apiCallInfo.usage = final.usage || null; } else if (ChatParams.is(template.params)) { const chat = client.beta.chat.completions.stream(toChatCompletionStreamParams(this.apiCallInfo)).on("connect", onConnect).on("content", (diff) => onContent(diff)); const final = await chat.finalChatCompletion(); const content = final.choices[0].message.content; this.apiCallInfo.endTime = new Date(); this.apiCallInfo.result = content; this.apiCallInfo.usage = final.usage || null; } else { throw new Error("Unknown template"); } this.insertNewLineThenScroll(editor, LnToWrite, ASSISTANT_MARK_END + " "); } catch (error) { console.error("error", error); this.apiCallInfo.error = `${error}`; this.apiCallInfo.endTime = new Date(); this.insertNewLineThenScroll(editor, LnToWrite, `${ERROR_MARK} ${error} `); } } insertNewLineThenScroll(editor, LnToWrite, text) { editor.replaceRange(LINE_BREAK + text, { line: LnToWrite, ch: editor.getLine(LnToWrite).length }); LnToWrite++; editor.setCursor({ line: LnToWrite, ch: editor.getLine(LnToWrite).length }); editor.scrollIntoView({ from: editor.getCursor("from"), to: editor.getCursor("to") }); return LnToWrite; } setLineThenScroll(editor, LnToWrite, text) { const textLine = editor.getLine(LnToWrite) + text; editor.setLine(LnToWrite, textLine); editor.setCursor({ line: LnToWrite, ch: textLine.length }); editor.scrollIntoView({ from: editor.getCursor("from"), to: editor.getCursor("to") }); } }; /* nosourcemap */