From a7af0e24e1498120a4eb8c252bb425d5aec7a95a Mon Sep 17 00:00:00 2001 From: shwetha729 Date: Mon, 28 Aug 2023 04:00:03 -0400 Subject: [PATCH] Monday, August 28, 2023, 04:00:01 + 5 --- enter/.obsidian/plugins/hk-code-block/main.js | 627 ++ .../plugins/hk-code-block/manifest.json | 11 + .../plugins/hk-code-block/styles.css | 241 + enter/.obsidian/plugins/khoj/main.js | 6147 +++++++++++++++++ enter/.obsidian/plugins/khoj/manifest.json | 10 + enter/.obsidian/plugins/khoj/styles.css | 176 + 6 files changed, 7212 insertions(+) create mode 100644 enter/.obsidian/plugins/hk-code-block/main.js create mode 100644 enter/.obsidian/plugins/hk-code-block/manifest.json create mode 100644 enter/.obsidian/plugins/hk-code-block/styles.css create mode 100644 enter/.obsidian/plugins/khoj/main.js create mode 100644 enter/.obsidian/plugins/khoj/manifest.json create mode 100644 enter/.obsidian/plugins/khoj/styles.css diff --git a/enter/.obsidian/plugins/hk-code-block/main.js b/enter/.obsidian/plugins/hk-code-block/main.js new file mode 100644 index 0000000..b4b139a --- /dev/null +++ b/enter/.obsidian/plugins/hk-code-block/main.js @@ -0,0 +1,627 @@ +/* +THIS IS A GENERATED/BUNDLED FILE BY ESBUILD +if you want to view the source, please visit the github repository of this plugin +*/ + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => HKCodeBlockPlugin +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian3 = require("obsidian"); + +// src/settings.ts +var DEFAULT_SETTINGS = { + useTitleGlobal: "default off, but on when specified", + useCollapsibleGlobal: "default on, but off when specified", + defaultCollapse: "expand", + showCollapseBtn: true, + useLinenosGlobal: "default off, but on when specified", + defaultLinenosStart: 1, + showLinenosSplitter: true, + useHighlightGlobal: "default off, but on when specified", + highlightColor: "#ff0000", + useLanguageGlobal: "default on, but off when specified", + defaultLanguage: "plain text", + useCopyBtnGlobal: "default on, but off when specified", + usePromptGlobal: "default on, but off when specified", + promptingLanguages: ["bash"], + defaultPrompt: "$", + useResultGlobal: true, + defaultResultPrompt: "Result", + debugMode: false +}; + +// src/settingTab.ts +var import_obsidian = require("obsidian"); +var fragWithHTML = (text) => { + return createFragment((frag) => { + frag.createDiv().innerHTML = text.split("\n").map((line) => line.trim()).join("
"); + }); +}; +var HKCodeBlockSettingTab = class extends import_obsidian.PluginSettingTab { + constructor(app2, plugin) { + super(app2, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl("h2", { text: "Title" }); + new import_obsidian.Setting(containerEl).setName("Use Title").setDesc(fragWithHTML(`- default off, but on when specified : the title will only be shown if the title statement is specified + - always off : the title will never be shown`)).addDropdown( + (tc) => tc.addOptions({ + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.useTitleGlobal).onChange(async (value) => { + this.plugin.settings.useTitleGlobal = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Collapse" }); + new import_obsidian.Setting(containerEl).setName("Use Collapse").setDesc(fragWithHTML(`- always on : the code block will always be collapsible + - default on, but off when specified : the code block will always be collapsible, but will not be collapsed if collapse statement is specified as false + - default off, but on when specified : the code block will only be collapsible if the collapse statement is specified as true + - always off : the code block will never be collapsible`)).addDropdown( + (tc) => tc.addOptions({ + "always on": "always on", + "default on, but off when specified": "default on, but off when specified", + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.useCollapsibleGlobal).onChange(async (value) => { + this.plugin.settings.useCollapsibleGlobal = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Default Collapse State").setDesc("The default collapse state of the code block.").addDropdown( + (tc) => tc.addOptions({ + "collapse": "collapse", + "expand": "expand" + }).setValue(this.plugin.settings.defaultCollapse).onChange(async (value) => { + this.plugin.settings.defaultCollapse = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Line Numbers" }); + new import_obsidian.Setting(containerEl).setName("Use Line Numbers").setDesc(fragWithHTML(`- always on : line numbers will always be shown + - default on, but off when specified : line numbers will always be shown, but will not be shown if linenos statement is specified as false + - default off, but on when specified : line numbers will only be shown if the linenos statement is specified as true + - always off : line numbers will never be shown`)).addDropdown( + (tc) => tc.addOptions({ + "always on": "always on", + "default on, but off when specified": "default on, but off when specified", + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.useLinenosGlobal).onChange(async (value) => { + this.plugin.settings.useLinenosGlobal = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Default Line Number Start").setDesc("The default line number start of the code block.").addText( + (tc) => tc.setValue(this.plugin.settings.defaultLinenosStart.toString()).onChange(async (value) => { + const num = parseInt(value); + if (isNaN(num)) + return; + this.plugin.settings.defaultLinenosStart = num; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Show Line Number Splitter").addToggle( + (tc) => tc.setValue(this.plugin.settings.showLinenosSplitter).onChange(async (value) => { + this.plugin.settings.showLinenosSplitter = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Line Highlight" }); + new import_obsidian.Setting(containerEl).setName("Use Line Highlight").setDesc(fragWithHTML(`- default off, but on when specified : line highlight will only be shown if the line highlight statement is specified + - always off : line highlight will never be shown`)).addDropdown( + (tc) => tc.addOptions({ + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.useHighlightGlobal).onChange(async (value) => { + this.plugin.settings.useHighlightGlobal = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Line Highlight Color").setDesc("The background color of the highlighted line. Note that the given color will be applied with 0.2 opacity.").addText( + (tc) => tc.setValue(this.plugin.settings.highlightColor).onChange(async (value) => { + this.plugin.settings.highlightColor = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Language Indicator" }); + new import_obsidian.Setting(containerEl).setName("Use Language Indicator").setDesc(fragWithHTML(`- always on : language indicator will always be shown + - default on, but off when specified : language indicator will always be shown, but will not be shown if the language indicator statement is specified as false + - default off, but on when specified : language indicator will only be shown if the language indicator statement is specified as true + - always off : language indicator will never be shown`)).addDropdown( + (tc) => tc.addOptions({ + "always on": "always on", + "default on, but off when specified": "default on, but off when specified", + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.useLanguageGlobal).onChange(async (value) => { + this.plugin.settings.useLanguageGlobal = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Default Language").setDesc("The default language name of the code block if the language is not specified.").addText( + (tc) => tc.setValue(this.plugin.settings.defaultLanguage).onChange(async (value) => { + this.plugin.settings.defaultLanguage = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Copy Button" }); + new import_obsidian.Setting(containerEl).setName("Use Copy Button").setDesc(fragWithHTML(`- always on : copy button will always be shown + - default on, but off when specified : copy button will always be shown, but will not be shown if the copy button statement is specified as false + - default off, but on when specified : copy button will only be shown if the copy button statement is specified as true + - always off : copy button will never be shown`)).addDropdown( + (tc) => tc.addOptions({ + "always on": "always on", + "default on, but off when specified": "default on, but off when specified", + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.useCopyBtnGlobal).onChange(async (value) => { + this.plugin.settings.useCopyBtnGlobal = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Prompt" }); + new import_obsidian.Setting(containerEl).setName("Use Prompt").setDesc(fragWithHTML(`- always on : prompt will always be shown + - default on, but off when specified : prompt will always be shown, but will not be shown if the prompt statement is specified as false + - default off, but on when specified : prompt will only be shown if the prompt statement is specified as true + - always off : prompt will never be shown`)).addDropdown( + (tc) => tc.addOptions({ + "always on": "always on", + "default on, but off when specified": "default on, but off when specified", + "default off, but on when specified": "default off, but on when specified", + "always off": "always off" + }).setValue(this.plugin.settings.usePromptGlobal).onChange(async (value) => { + this.plugin.settings.usePromptGlobal = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Prompting Languages").setDesc("The languages that will be prompted by default. You can specify multiple languages by separating them with enters.").addTextArea( + (tc) => tc.setValue(this.plugin.settings.promptingLanguages.join("\n")).onChange(async (value) => { + const lines = value.split("\n").filter((line) => line.trim() !== ""); + this.plugin.settings.promptingLanguages = lines; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Default Prompt").setDesc("The default prompt of the bash code block.").addText( + (tc) => tc.setValue(this.plugin.settings.defaultPrompt).onChange(async (value) => { + this.plugin.settings.defaultPrompt = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Result" }); + new import_obsidian.Setting(containerEl).setName("Use Result").setDesc(fragWithHTML(`- enable : treat the code block starts like \`\`\`\`result\` as the result of the adjacent previous code block + - disable : treat the code block with \`result\` as its language name as a normal code block`)).addToggle( + (tc) => tc.setValue(this.plugin.settings.useResultGlobal).onChange(async (value) => { + this.plugin.settings.useResultGlobal = value; + await this.plugin.saveSettings(); + }) + ); + new import_obsidian.Setting(containerEl).setName("Default Result Prompt").setDesc("The default prompt of the result code block.").addText( + (tc) => tc.setValue(this.plugin.settings.defaultResultPrompt).onChange(async (value) => { + this.plugin.settings.defaultResultPrompt = value; + await this.plugin.saveSettings(); + }) + ); + containerEl.createEl("h2", { text: "Developers" }); + new import_obsidian.Setting(containerEl).setName("Debug Mode").setDesc("Show logs in the console.").addToggle( + (tc) => tc.setValue(this.plugin.settings.debugMode).onChange(async (value) => { + this.plugin.settings.debugMode = value; + await this.plugin.saveSettings(); + }) + ); + } +}; + +// src/processor.ts +var import_obsidian2 = require("obsidian"); +var REGEX = { + TITLE: /\stitle:(?:'(.*?)'|"(.*?)")\s/, + COLLAPSIBLE_SIMPLE: /\scollapsible\s/, + COLLAPSIBLE_COMPLICATE: /\scollapsible:(true|false)\s/, + LINENOS_SIMPLE: /\slinenos\s/, + LINENOS_COMPLICATE: /\slinenos:(true|false|(-{0,1}\d+))\s/, + HIGHLIGHT: /\shighlight:(?:'(.*?)'|"(.*?)")\s/, + LANGUAGE_FROM_CLASS: /^language-(\w+)$/, + LANGUAGE_SIMPLE: /\slanguage\s/, + LANGUAGE_COMPLICATE: /\slanguage:(true|false|'(.*?)'|"(.*?)")\s/, + COPYBTN_SIMPLE: /\scopybtn\s/, + COPYBTN_COMPLICATE: /\scopybtn:(true|false)\s/, + RESULT: /^```result\s/, + PROMPT_SIMPLE: /\sprompt\s/, + PROMPT_COMPLICATE: /\sprompt:(true|false|'(.*?)'|"(.*?)")\s/, + NUMBER: /^-{0,1}\d+$/ +}; +function getMeta(view, elem_code, elem_code_idx, section_code, settings) { + const return_value = { + isError: false, + lineStartInSection: -1, + lineEndInSection: -1, + showTitle: void 0, + title: "", + isCollapsible: void 0, + showLinenos: void 0, + linenosStart: settings.defaultLinenosStart, + linenosNum: 0, + showHighlight: void 0, + highlightLines: [], + showLanguage: void 0, + language: settings.defaultLanguage, + showCopyBtn: void 0, + isResult: false, + resultPrompt: settings.defaultResultPrompt, + showPrompt: void 0, + prompt: settings.defaultPrompt + }; + let marker_count = 0; + for (let i = section_code.lineStart; i <= section_code.lineEnd; i++) { + const line = view.editor.getLine(i); + if (line.trim().startsWith("```")) + marker_count++; + if (return_value.lineStartInSection === -1 && marker_count === elem_code_idx * 2 + 1) { + return_value.lineStartInSection = i; + } + if (return_value.lineEndInSection === -1 && marker_count === elem_code_idx * 2 + 2) { + return_value.lineEndInSection = i; + break; + } + } + if (return_value.lineStartInSection < 0 || return_value.lineEndInSection < 0 || return_value.lineStartInSection >= return_value.lineEndInSection) { + return_value.isError = true; + return return_value; + } + const firstline = view.editor.getLine(return_value.lineStartInSection).trim() + " "; + const regexResult_title = REGEX.TITLE.exec(firstline); + if (regexResult_title) { + return_value.showTitle = true; + return_value.title = regexResult_title[1] || regexResult_title[2]; + } + const regexResult_collapsibleSimple = REGEX.COLLAPSIBLE_SIMPLE.exec(firstline); + const regexResult_collapsibleComplicate = REGEX.COLLAPSIBLE_COMPLICATE.exec(firstline); + if (regexResult_collapsibleSimple) { + return_value.isCollapsible = true; + } else if (regexResult_collapsibleComplicate) { + if (regexResult_collapsibleComplicate[1] === "true") { + return_value.isCollapsible = true; + } else if (regexResult_collapsibleComplicate[1] === "false") { + return_value.isCollapsible = false; + } + } + return_value.linenosNum = return_value.lineEndInSection - return_value.lineStartInSection - 1; + const regexResult_linenosSimple = REGEX.LINENOS_SIMPLE.exec(firstline); + const regexResult_linenosComplicate = REGEX.LINENOS_COMPLICATE.exec(firstline); + if (regexResult_linenosSimple) { + return_value.showLinenos = true; + } else if (regexResult_linenosComplicate) { + if (regexResult_linenosComplicate[1] === "true") { + return_value.showLinenos = true; + } else if (regexResult_linenosComplicate[1] === "false") { + return_value.showLinenos = false; + } else { + return_value.showLinenos = true; + return_value.linenosStart = parseInt(regexResult_linenosComplicate[2]) || 1; + } + } + const regexResult_highlight = REGEX.HIGHLIGHT.exec(firstline); + if (regexResult_highlight) { + return_value.showHighlight = true; + const highlightLines_str = regexResult_highlight[1] || regexResult_highlight[2]; + let highlightLines = highlightLines_str.split(",").map((item) => { + item = item.trim(); + if (REGEX.NUMBER.test(item)) + return parseInt(item); + const multiple_lines = item.split("-"); + if (multiple_lines.length === 2) { + const start = parseInt(multiple_lines[0].trim()); + const end = parseInt(multiple_lines[1].trim()); + if (!isNaN(start) && !isNaN(end)) { + return Array.from({ length: end - start + 1 }, (_, i) => i + start); + } + } + return NaN; + }).flat().filter((item) => !isNaN(item)); + if (highlightLines.some((line) => isNaN(line))) { + return_value.showHighlight = void 0; + return_value.highlightLines = []; + } else { + return_value.highlightLines = highlightLines.filter( + (line) => line >= return_value.linenosStart && line < return_value.linenosStart + return_value.linenosNum + ); + } + } + elem_code.classList.forEach((className) => { + const regexResult_languageFromClass = REGEX.LANGUAGE_FROM_CLASS.exec(className.trim()); + if (regexResult_languageFromClass) { + return_value.language = regexResult_languageFromClass[1]; + } + }); + const regexResult_languageSimple = REGEX.LANGUAGE_SIMPLE.exec(firstline); + const regexResult_languageComplicate = REGEX.LANGUAGE_COMPLICATE.exec(firstline); + if (regexResult_languageSimple) { + return_value.showLanguage = true; + } else if (regexResult_languageComplicate) { + if (regexResult_languageComplicate[1] === "true") { + return_value.showLanguage = true; + } else if (regexResult_languageComplicate[1] === "false") { + return_value.showLanguage = false; + } else { + return_value.showLanguage = true; + return_value.language = regexResult_languageComplicate[2] || regexResult_languageComplicate[3]; + } + } + const regexResult_copyBtnSimple = REGEX.COPYBTN_SIMPLE.exec(firstline); + const regexResult_copyBtnComplicate = REGEX.COPYBTN_COMPLICATE.exec(firstline); + if (regexResult_copyBtnSimple) { + return_value.showCopyBtn = true; + } else if (regexResult_copyBtnComplicate) { + if (regexResult_copyBtnComplicate[1] === "true") { + return_value.showCopyBtn = true; + } else if (regexResult_copyBtnComplicate[1] === "false") { + return_value.showCopyBtn = false; + } + } + const regexResult_promptSimple = REGEX.PROMPT_SIMPLE.exec(firstline); + const regexResult_promptComplicate = REGEX.PROMPT_COMPLICATE.exec(firstline); + if (regexResult_promptSimple) { + return_value.showPrompt = true; + } else if (regexResult_promptComplicate) { + if (regexResult_promptComplicate[1] === "true") { + return_value.showPrompt = true; + } else if (regexResult_promptComplicate[1] === "false") { + return_value.showPrompt = false; + } else { + return_value.showPrompt = true; + return_value.prompt = regexResult_promptComplicate[2] || regexResult_promptComplicate[3]; + } + } + const regexResult_result = REGEX.RESULT.exec(firstline); + const regexResultPrompt_result = REGEX.PROMPT_COMPLICATE.exec(firstline); + if (regexResult_result) { + return_value.isResult = true; + return_value.showTitle = false; + return_value.showLanguage = false; + return_value.showCopyBtn = false; + return_value.showPrompt = false; + if (regexResultPrompt_result) { + return_value.resultPrompt = regexResultPrompt_result[2] || regexResultPrompt_result[3]; + } + } + return return_value; +} +function HKCodeBlockProcessor(el, context, plugin) { + const settings = plugin.settings; + const view = app.workspace.getActiveViewOfType(import_obsidian2.MarkdownView); + if (!view) + return; + const elem_codes = el.querySelectorAll("pre:not(.frontmatter) > code"); + if (elem_codes.length === 0) + return; + elem_codes.forEach((elem_code, elem_code_idx) => { + const elem_pre = elem_code.parentElement; + if (!elem_pre) + return; + const elem_pre_parent = elem_pre.parentElement; + if (!elem_pre_parent) + return; + const elem_copyBtn = elem_pre.querySelector(".copy-code-button"); + if (!elem_copyBtn) + return; + const section_code = context.getSectionInfo(elem_code); + if (!section_code) + return; + const { + isError, + lineStartInSection, + lineEndInSection, + showTitle, + title, + isCollapsible, + showLinenos, + linenosStart, + linenosNum, + showHighlight, + highlightLines, + showLanguage, + language, + showCopyBtn, + isResult, + resultPrompt, + showPrompt, + prompt + } = getMeta(view, elem_code, elem_code_idx, section_code, settings); + if (isError) + return; + if (settings.debugMode) { + console.log({ + isError, + lineStartInSection, + lineEndInSection, + showTitle, + title, + isCollapsible, + showLinenos, + linenosStart, + linenosNum, + showHighlight, + highlightLines, + showLanguage, + language, + showCopyBtn, + isResult, + resultPrompt, + showPrompt, + prompt + }); + } + const elem_div = document.createElement("div"); + elem_pre_parent.replaceChild(elem_div, elem_pre); + elem_div.appendChild(elem_pre); + elem_div.classList.add("hk-codeblock"); + elem_code.classList.add("hk-codeblock-code"); + elem_copyBtn.remove(); + let elem_title = void 0; + if (settings.useTitleGlobal === "default off, but on when specified" && showTitle === true) { + elem_div.classList.add("hk-codeblock-show-title"); + elem_title = document.createElement("div"); + elem_title.classList.add("hk-codeblock-title"); + elem_title.innerHTML = title; + elem_div.insertBefore(elem_title, elem_pre); + } + if (settings.useCollapsibleGlobal === "always on" || settings.useCollapsibleGlobal === "default on, but off when specified" && (isCollapsible === void 0 || isCollapsible === true) || settings.useCollapsibleGlobal === "default off, but on when specified" && isCollapsible === true) { + if (elem_title) { + elem_div.classList.add("hk-codeblock-collapsible"); + if (settings.defaultCollapse === "collapse") { + elem_div.classList.add("hk-codeblock-collapsed"); + } + elem_title.addEventListener("click", (ev) => { + ev.stopPropagation(); + ev.preventDefault(); + elem_div.classList.toggle("hk-codeblock-collapsed"); + }); + const elem_collapseBtns = document.createElement("div"); + elem_collapseBtns.classList.add("hk-codeblock-collapse-btns"); + const elem_collapseBtn = document.createElement("div"); + elem_collapseBtn.classList.add("hk-codeblock-collapse-btn", "hk-codeblock-collapsed-btn"); + elem_collapseBtn.innerHTML = ` + + `; + elem_collapseBtns.appendChild(elem_collapseBtn); + const elem_expandBtn = document.createElement("div"); + elem_expandBtn.classList.add("hk-codeblock-collapse-btn", "hk-codeblock-expanded-btn"); + elem_expandBtn.innerHTML = ` + + `; + elem_collapseBtns.appendChild(elem_expandBtn); + elem_title.prepend(elem_collapseBtns); + } + } + if (settings.useLinenosGlobal === "always on" || settings.useLinenosGlobal === "default on, but off when specified" && (showLinenos === void 0 || showLinenos === true) || settings.useLinenosGlobal === "default off, but on when specified" && showLinenos === true) { + elem_div.classList.add("hk-codeblock-show-linenos"); + const elem_linenos = document.createElement("div"); + elem_linenos.classList.add("hk-codeblock-linenos"); + elem_linenos.innerText = Array(linenosNum).fill(0).map((_, idx) => idx + linenosStart).join("\n"); + elem_pre.insertBefore(elem_linenos, elem_code); + if (settings.showLinenosSplitter) { + elem_linenos.classList.add("show-splitter"); + } + } + if (settings.useHighlightGlobal === "default off, but on when specified" && showHighlight === true) { + elem_div.classList.add("hk-codeblock-show-highlight"); + elem_div.style.setProperty("--hk-codeblock-highlight-background-color", settings.highlightColor); + const elem_highlight = document.createElement("div"); + elem_highlight.classList.add("hk-codeblock-highlight"); + elem_highlight.innerHTML = Array(linenosNum).fill(0).map((_, idx) => { + const classNames = []; + if (highlightLines.includes(idx + linenosStart)) + classNames.push("highlight"); + return ` `; + }).join("\n"); + elem_pre.insertBefore(elem_highlight, elem_code); + } + if (settings.useLanguageGlobal === "always on" || settings.useLanguageGlobal === "default on, but off when specified" && (showLanguage === void 0 || showLanguage === true) || settings.useLanguageGlobal === "default off, but on when specified" && showLanguage === true) { + elem_div.classList.add("hk-codeblock-show-language"); + const elem_language = document.createElement("div"); + elem_language.classList.add("hk-codeblock-language"); + elem_language.innerText = language; + elem_pre.prepend(elem_language); + } + if (settings.useCopyBtnGlobal === "always on" || settings.useCopyBtnGlobal === "default on, but off when specified" && (showCopyBtn === void 0 || showCopyBtn === true) || settings.useCopyBtnGlobal === "default off, but on when specified" && showCopyBtn === true) { + elem_div.classList.add("hk-codeblock-show-copybtn"); + elem_pre.appendChild(elem_copyBtn); + } + if (settings.usePromptGlobal === "always on" && settings.promptingLanguages.includes(language) || settings.usePromptGlobal === "default on, but off when specified" && settings.promptingLanguages.includes(language) && (showPrompt === void 0 || showPrompt === true) || settings.usePromptGlobal === "default off, but on when specified" && showPrompt === true) { + elem_div.classList.add("hk-codeblock-show-prompt"); + const elem_prompt = document.createElement("div"); + elem_prompt.classList.add("hk-codeblock-prompt"); + const lines = elem_code.innerText.split("\n"); + elem_prompt.innerText = Array(linenosNum).fill(0).map((_, idx) => { + if (idx < 0 || idx >= lines.length) + return null; + const line = lines[idx].trim(); + const prevLine = idx > 0 ? lines[idx - 1].trim() : ""; + if (line === "" || // check if the line is empty + line.startsWith("#") || // check if the line is a comment + prevLine.endsWith("\\")) { + return " ".repeat(prompt.length); + } + return prompt; + }).filter((line) => line !== null).join("\n"); + elem_pre.insertBefore(elem_prompt, elem_code); + } + if (settings.useResultGlobal === true && isResult === true) { + const isCodeBlockAdjacent = (() => { + let line_idx = lineStartInSection - 1; + while (line_idx >= 0) { + const line = view.editor.getLine(line_idx).trim(); + if (line.length === 0) { + line_idx--; + continue; + } else if (line === "```") { + return true; + } else { + return false; + } + } + return false; + })(); + if (isCodeBlockAdjacent) { + elem_div.classList.add("hk-codeblock-result"); + elem_code.classList.add("hk-codeblock-result-code"); + const elem_result_prompt = document.createElement("div"); + elem_result_prompt.classList.add("hk-codeblock-result-prompt"); + elem_result_prompt.innerText = resultPrompt; + elem_div.insertBefore(elem_result_prompt, elem_pre); + } + } + }); +} + +// src/main.ts +var HKCodeBlockPlugin = class extends import_obsidian3.Plugin { + async onload() { + await this.loadSettings(); + if (this.settings.debugMode) { + console.log("loading HK Code Block plugin"); + } + this.addSettingTab(new HKCodeBlockSettingTab(this.app, this)); + const processor = this.registerMarkdownPostProcessor((el, ctx) => { + HKCodeBlockProcessor(el, ctx, this); + }); + processor.sortOrder = 100; + } + onunload() { + if (this.settings.debugMode) { + console.log("unloading HKCodeBlock plugin"); + } + } + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + } + async saveSettings() { + await this.saveData(this.settings); + } +}; +//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL21haW4udHMiLCAiLi4vc3JjL3NldHRpbmdzLnRzIiwgIi4uL3NyYy9zZXR0aW5nVGFiLnRzIiwgIi4uL3NyYy9wcm9jZXNzb3IudHMiXSwKICAic291cmNlc0NvbnRlbnQiOiBbImltcG9ydCB7IFBsdWdpbiB9IGZyb20gJ29ic2lkaWFuJztcblxuaW1wb3J0IHR5cGUgeyBIS0NvZGVCbG9ja1NldHRpbmdzIGFzIEhLQ29kZUJsb2NrU2V0dGluZ3MgfSBmcm9tICcuL3NldHRpbmdzJztcbmltcG9ydCB7IERFRkFVTFRfU0VUVElOR1MgfSBmcm9tICcuL3NldHRpbmdzJztcbmltcG9ydCB7IEhLQ29kZUJsb2NrU2V0dGluZ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0sS0FBSyxTQUFTLENBQUM7QUFBQSxFQUMxRTtBQUFBLEVBRUEsTUFBTSxlQUFlO0FBQ3BCLFVBQU0sS0FBSyxTQUFTLEtBQUssUUFBUTtBQUFBLEVBQ2xDO0FBQ0Q7IiwKICAibmFtZXMiOiBbImltcG9ydF9vYnNpZGlhbiIsICJhcHAiLCAiaW1wb3J0X29ic2lkaWFuIl0KfQo= diff --git a/enter/.obsidian/plugins/hk-code-block/manifest.json b/enter/.obsidian/plugins/hk-code-block/manifest.json new file mode 100644 index 0000000..d05b742 --- /dev/null +++ b/enter/.obsidian/plugins/hk-code-block/manifest.json @@ -0,0 +1,11 @@ +{ + "id": "hk-code-block", + "name": "HK Code Block", + "version": "0.4.1", + "minAppVersion": "1.0.0", + "description": "Obsidian plugin developed by Heekang Park; Make code block looking good on reading view", + "author": "Heekang Park", + "authorUrl": "https://github.com/HeekangPark", + "fundingUrl": "", + "isDesktopOnly": false +} \ No newline at end of file diff --git a/enter/.obsidian/plugins/hk-code-block/styles.css b/enter/.obsidian/plugins/hk-code-block/styles.css new file mode 100644 index 0000000..6e81b18 --- /dev/null +++ b/enter/.obsidian/plugins/hk-code-block/styles.css @@ -0,0 +1,241 @@ +/* src/styles.scss */ +.hk-codeblock { + position: relative; + margin-top: var(--hk-codeblock-margin); + margin-bottom: var(--hk-codeblock-margin); +} +.hk-codeblock { + --hk-codeblock-margin: 1em; + --hk-codeblock-horizontal-padding: 16px; + --hk-codeblock-vertical-padding: 8px; + --hk-codeblock-background-color: var(--code-background); + --hk-codeblock-border-color: var(--divider-color); + --hk-codeblock-font-family: var(--font-monospace); + --hk-codeblock-font-size: var(--code-size); + --hk-codeblock-text-color: var(--code-normal); + --hk-codeblock-title-text-font: var(--hk-codeblock-font-family); + --hk-codeblock-title-text-color: var(--hk-codeblock-text-color); + --hk-codeblock-title-text-size: var(--hk-codeblock-font-size); + --hk-codeblock-linenos-text-font: var(--hk-codeblock-font-family); + --hk-codeblock-linenos-text-color: var(--hk-codeblock-text-color); + --hk-codeblock-linenos-text-size: var(--hk-codeblock-font-size); + --hk-codeblock-language-text-font: var(--hk-codeblock-font-family); + --hk-codeblock-language-text-color: var(--hk-codeblock-text-color); + --hk-codeblock-language-text-size: calc(var(--hk-codeblock-font-size) * 0.9); + --hk-codeblock-copy-btn-text-font: var(--hk-codeblock-font-family); + --hk-codeblock-copy-btn-text-color: var(--hk-codeblock-text-color); + --hk-codeblock-copy-btn-text-size: calc(var(--hk-codeblock-font-size) * 0.9); + --hk-codeblock-prompt-text-font: var(--hk-codeblock-font-family); + --hk-codeblock-prompt-text-color: var(--hk-codeblock-text-color); + --hk-codeblock-prompt-text-size: var(--hk-codeblock-font-size); + --hk-codeblock-result-text-font: var(--hk-codeblock-font-family); + --hk-codeblock-result-text-color: var(--hk-codeblock-text-color); + --hk-codeblock-result-text-size: var(--hk-codeblock-font-size); +} +.hk-codeblock pre { + position: relative; + border-radius: initial; + display: flex; + flex-direction: row; + margin: 0; + min-height: 0; + padding-top: var(--hk-codeblock-vertical-padding); + padding-bottom: var(--hk-codeblock-vertical-padding); + padding-left: var(--hk-codeblock-horizontal-padding); + padding-right: var(--hk-codeblock-horizontal-padding); + background-color: var(--hk-codeblock-background-color); + font-family: var(--hk-codeblock-font-family); + color: var(--hk-codeblock-text-color); +} +.hk-codeblock pre code.hk-codeblock-code { + white-space: pre; + overflow-x: auto; + padding: 0; + background-color: var(--hk-codeblock-background-color); + font-family: var(--hk-codeblock-font-family); + color: var(--hk-codeblock-text-color); + font-size: var(--hk-codeblock-font-size); +} +.hk-codeblock.hk-codeblock-show-title .hk-codeblock-title { + padding-top: var(--hk-codeblock-vertical-padding); + padding-bottom: var(--hk-codeblock-vertical-padding); + padding-left: var(--hk-codeblock-horizontal-padding); + padding-right: var(--hk-codeblock-horizontal-padding); + background-color: var(--hk-codeblock-background-color); + border-bottom: 1px solid var(--hk-codeblock-border-color); + font-family: var(--hk-codeblock-title-text-font); + color: var(--hk-codeblock-title-text-color); + font-size: var(--hk-codeblock-title-text-size); + display: flex; + flex-direction: row; + align-items: center; +} +.hk-codeblock.hk-codeblock-show-title .hk-codeblock-title ~ pre { + margin-top: 0; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible .hk-codeblock-title { + cursor: pointer; + position: relative; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible .hk-codeblock-title .hk-codeblock-collapse-btns { + display: inline-flex; + align-items: center; + justify-content: center; + margin-right: 2px; + position: relative; + top: -1px; + left: -3px; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible .hk-codeblock-title .hk-codeblock-collapse-btns .hk-codeblock-collapse-btn { + width: var(--hk-codeblock-title-text-size); + height: var(--hk-codeblock-title-text-size); + fill: var(--hk-codeblock-title-text-color); + stroke: var(--hk-codeblock-title-text-color); + stroke-width: 2; + opacity: 0.2; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible .hk-codeblock-title .hk-codeblock-collapse-btns .hk-codeblock-collapse-btn.hk-codeblock-collapsed-btn { + display: none; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible .hk-codeblock-title .hk-codeblock-collapse-btns .hk-codeblock-collapse-btn.hk-codeblock-expanded-btn { + display: inline-block; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible.hk-codeblock-collapsed .hk-codeblock-title { + border-bottom: none; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible.hk-codeblock-collapsed .hk-codeblock-title .hk-codeblock-collapse-btns .hk-codeblock-collapse-btn.hk-codeblock-collapsed-btn { + display: inline-block; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible.hk-codeblock-collapsed .hk-codeblock-title .hk-codeblock-collapse-btns .hk-codeblock-collapse-btn.hk-codeblock-expanded-btn { + display: none; +} +.hk-codeblock.hk-codeblock-show-title.hk-codeblock-collapsible.hk-codeblock-collapsed pre { + display: none; +} +.hk-codeblock.hk-codeblock-show-linenos pre .hk-codeblock-linenos { + flex-shrink: 0; + flex-grow: 0; + text-align: right; + padding: 0; + padding-right: 1em; + opacity: 0.6; + user-select: none; + white-space: pre; + font-family: var(--hk-codeblock-linenos-text-font); + color: var(--hk-codeblock-linenos-text-color); + font-size: var(--hk-codeblock-linenos-text-size); + background-color: transparent; +} +.hk-codeblock.hk-codeblock-show-linenos pre .hk-codeblock-linenos.show-splitter { + border-right: 1px solid var(--hk-codeblock-border-color); + margin-right: 1em; +} +.hk-codeblock.hk-codeblock-show-highlight pre .hk-codeblock-highlight { + display: flex; + flex-direction: column; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + pointer-events: none; + user-select: none; + padding-top: var(--hk-codeblock-vertical-padding); + padding-bottom: var(--hk-codeblock-vertical-padding); + opacity: 0.2; + font-family: var(--hk-codeblock-linenos-text-font); + font-size: var(--hk-codeblock-linenos-text-font); + color: var(--hk-codeblock-linenos-text-color); + background-color: transparent; +} +.hk-codeblock.hk-codeblock-show-highlight pre .hk-codeblock-highlight .line.highlight { + background-color: var(--hk-codeblock-highlight-background-color); +} +.hk-codeblock.hk-codeblock-show-language pre .hk-codeblock-language { + opacity: 0.4; + user-select: none; + z-index: 1; + margin: 6px; + padding-top: 6px; + padding-bottom: 6px; + padding-left: 8px; + padding-right: 8px; + background-color: transparent; + box-shadow: none; + font-family: var(--hk-codeblock-language-text-font); + color: var(--hk-codeblock-language-text-color); + font-size: var(--hk-codeblock-language-text-size); + position: absolute; + top: 0; + right: 0; +} +.hk-codeblock.hk-codeblock-show-language pre:hover .hk-codeblock-language { + display: none; +} +.hk-codeblock.hk-codeblock-show-copybtn pre .copy-code-button { + cursor: pointer; + opacity: 0.4; + user-select: none; + z-index: 1; + margin: 6px; + padding-top: 6px; + padding-bottom: 6px; + padding-left: 8px; + padding-right: 8px; + background-color: transparent; + box-shadow: none; + font-family: var(--hk-codeblock-copy-btn-text-font); + color: var(--hk-codeblock-copy-btn-text-color); + font-size: var(--hk-codeblock-copy-btn-text-size); + position: absolute; + top: 0; + right: 0; +} +.hk-codeblock.hk-codeblock-show-copybtn pre .copy-code-button:hover { + opacity: 1; + background-color: rgba(255, 255, 255, 0.0745098039); +} +.hk-codeblock.hk-codeblock-show-copybtn pre .copy-code-button:active { + opacity: 1; + background-color: rgba(255, 255, 255, 0.1490196078); +} +.hk-codeblock.hk-codeblock-show-prompt pre .hk-codeblock-prompt { + flex-shrink: 0; + flex-grow: 0; + text-align: right; + padding-top: 0; + padding-bottom: 0; + padding-left: 0; + padding-right: 0.8em; + opacity: 0.6; + user-select: none; + color: var(--hk-codeblock-prompt-text-color); + white-space: pre; + font-family: var(--hk-codeblock-prompt-text-font); + font-size: var(--hk-codeblock-prompt-text-size); + background-color: transparent; +} +.hk-codeblock.hk-codeblock-result { + margin-top: calc(var(--hk-codeblock-margin) * -1); + border-top: 1px solid var(--hk-codeblock-border-color); + background-color: var(--hk-codeblock-background-color); +} +.hk-codeblock.hk-codeblock-result .hk-codeblock-result-prompt { + color: var(--hk-codeblock-result-text-color); + opacity: 0.4; + font-size: 0.8em; + padding-top: var(--hk-codeblock-vertical-padding); + padding-left: var(--hk-codeblock-horizontal-padding); + padding-right: var(--hk-codeblock-horizontal-padding); + user-select: none; + pointer-events: none; +} +.hk-codeblock.hk-codeblock-result pre { + margin-top: 0; +} +.hk-codeblock.hk-codeblock-result pre .hk-codeblock-result-code { + color: var(--hk-codeblock-result-text-color); + font-family: var(--hk-codeblock-result-text-font); + font-size: var(--hk-codeblock-result-text-size); +} +/*# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vc3JjL3N0eWxlcy5zY3NzIl0sCiAgInNvdXJjZXNDb250ZW50IjogWyIuaGstY29kZWJsb2NrIHtcbiAgJiB7XG4gICAgLy8gdmFyaWFibGVzXG4gICAgLS1oay1jb2RlYmxvY2stbWFyZ2luOiAxZW07XG4gICAgLS1oay1jb2RlYmxvY2staG9yaXpvbnRhbC1wYWRkaW5nOiAxNn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WhrLWNvZGVibG9jay1mb250LWZhbWlseSk7IFxuICAgIC0taGstY29kZWJsb2NrLWxhbmd1YWdlLXRleHQtY29sb3I6IHZhcigtLWhrLWNvZGVibG9jay10ZXh0LWNvbG9yKTsgXG4gICAgLS1oay1jb2RlYmxvY2stbGFuZ3VhZ2UtdGV4dC1zaXplOiBjYWxjKHZhcigtLWhrLWNvZGVibG9jay1mb250LXNpemUpICogMC45KTtcblxuICAgIC0taGstY29kZWJsb2NrLWNvcHktYnRuLXRleHQtZm9udDogdmFyKC0taGstY29kZWJsb2NrLWZvbnQtZmFtaWx5KTtcbiAgICAtLWhrLWNvZGVibG9jay1jb3B5LWJ0bi10ZXh0LWNvbG9yOiB2YXIoLS1oay1jb2RlYmxvY2stdGV4dC1jb2xvcik7XG4gICAgLS1oay1jb2RlYmxvY2stY29weS1idG4tdGV4dC1zaXplOiBjYWxjKHZhcigtLWhrLWNvZGVibG9jay1mb250LXNpemUpICogMC45KTtcblxuICAgIC0taGstY29kZWJsb2NrLXByb21wdC10ZXh0LWZvbnQ6IHZhcigtLWhrLWNvZGVibG9jay1mb250LWZhbWlseSk7XG4gICAgLS1oay1jb2RlYmxvY2stcHJvbXB0LXRleHQtY29sb3I6IHZhcigtLWhrLWNvZGVibG9jay10ZXh0LWNvbG9yKTtcbiAgICAtLWhrLWNvZGVibG9jay1wcm9tcHQtdGV4dC1zaXplOiB2YXIoLS1oay1jb2RlYmxvY2stZm9udC1zaXplKTtcblxuICAgIC0taGstY29kZWJsb2NrLXJlc3VsdC10ZXh0LWZvbnQ6IHZhcigtLWhrLWNvZGVibG9jay1mb250LWZhbWlseSk7XG4gICAgLS1oay1jb2RlYmxvY2stcmVzdWx0LXRleHQtY29sb3I6IHZhcigtLWhrLWNvZGVibG9jay10ZXh0LWNvbG9yKTtcbiAgICAtLWhrLWNvZGVibG9jay1yZXN1bHQtdGV4dC1zaXplOiB2YXIoLS1oay1jb2RlYmxvY2stZm9udC1zaXplKTtcbiAgfVxuXG4gI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AgICBvcGFjaXR5OiAwLjI7XG5cbiAgICAgICAgJi5oay1jb2RlYmxvY2stY29sbGFwc2VkLWJ0biB7XG4gICAgICAgICAgZGlzcGxheTogbm9uZTtcbiAgICAgICAgfVxuXG4gICAgICAgICYuaGstY29kZWJsb2NrLWV4cGFuZGVkLWJ0biB7XG4gICAgICAgICAgZGlzcGxheTogaW5saW5lLWJsb2NrO1xuICAgICAgICB9XG4gICAgICB9XG4gICAgfVxuICB9XG5cbiAgJi5oay1jb2RlYmxvY2stY29sbGFwc2VkIHtcbiAgICAuaGstY29kZWJsb2NrLXRpdGxlIHtcbiAgICAgIGJvcmRlci1ib3R0b206IG5vbmU7XG5cbiAgICAgIC5oay1jb2RlYmxvY2stY29sbGFwc2UtYnRucyB7XG4gICAgICAgIC5oay1jb2RlYmxvY2stY29sbGFwc2UtYnRuIHtcbiAgICAgICAgICAmLmhrLWNvZGVibG9jay1jb2xsYXBzZWQtYnRuIHtcbiAgICAgICAgICAgIGRpc3BsYXk6IGlubGluZS1ibG9jaztcbiAgICAgICAgICB9XG5cbiAgICAgICAgICAmLmhrLWNvZGVibG9jay1leHBhbmRlZC1idG4ge1xuICAgICAgICAgICAgZGlzcGxheTogbm9uZTtcbiAgICAgICAgICB9XG4gICAgICAgIH1cbiAgICAgIH1cbiAgICB9XG5cbiAgICBwcmUge1xuICAgICAgZGlzcGxheTogbm9uZTtcbiAgICB9XG4gIH1cbn1cblxuLyogbGluZW5vcyAqL1xuLmhrLWNvZGVibG9jay5oay1jb2RlYmxvY2stc2hvdy1saW5lbm9zIHtcbiAgcHJlIHtcbiAgICAuaGstY29kZWJsb2NrLWxpbmVub3Mge1xuICAgICAgZmxleC1zaHJpbms6IDA7XG4gICAgICBmbGV4LWdyb3c6IDA7XG4gICAgICB0ZXh0LWFsaWduOiByaWdodDtcbiAgICAgIHBhZGRpbmc6IDA7XG4gICAgICBwYWRkaW5nLXJpZ2h0OiAxZW07XG4gICAgICBvcGFjaXR5OiAwLjY7XG4gICAgICB1c2VyLXNlbGVjdDogbm9uZTtcbiAgICAgIHdoaXRlLXNwYWNlOiBwcmU7XG4gICAgICBmb250LWZhbWlseTogdmFyKC0taGstY29kZWJsb2NrLWxpbmVub3MtdGV4dC1mb250KTtcbiAgICAgIGNvbG9yOiB2YXIoLS1oay1jb2RlYmxvY2stbGluZW5vcy10ZXh0LWNvbG9yKTtcbiAgICAgIGZvbnQtc2l6ZTogdmFyKC0taGstY29kZWJsb2NrLWxpbmVub3MtdGV4dC1zaXplKTtcbiAgICAgIGJhY2tncm91bmQtY29sb3I6IHRyYW5zcGFyZW50O1xuXG4gICAgICAmLnNob3ctc3BsaXR0ZXIge1xuICAgICAgICBib3JkZXItcmlnaHQ6IDFweCBzb2xpZCB2YXIoLS1oay1jb2RlYmxvY2stYm9yZGVyLWNvbG9yKTtcbiAgICAgICAgbWFyZ2luLXJpZ2h0OiAxZW07XG4gICAgICB9XG4gICAgfVxuICB9XG59XG5cbi8qIGhpZ2hsaWdodCAqL1xuLmhrLWNvZGVibG9jay5oay1jb2RlYmxvY2stc2hvdy1oaWdobGlnaHQge1xuICBwcmUge1xuICAgIC5oay1jb2RlYmxvY2staGlnaGxpZ2h0IHtcbiAgICAgIGRpc3BsYXk6IGZsZXg7XG4gICAgICBmbGV4LWRpcmVjdGlvbjogY29sdW1uO1xuICAgICAgcG9zaXRpb246IGFic29sdXRlO1xuICAgICAgdG9wOiAwO1xuICAgICAgbGVmdDogMDtcbiAgICAgIHJpZ2h0OiAwO1xuICAgICAgYm90dG9tOiAwO1xuICAgICAgcG9pbnRlci1ldmVudHM6IG5vbmU7XG4gICAgICB1c2VyLXNlbGVjdDogbm9uZTtcblxuICAgICAgcGFkZGluZzoge1xuICAgICAgICB0b3A6IHZhcigtLWhrLWNvZGVibG9jay12ZXJ0aWNhbC1wYWRkaW5nKTtcbiAgICAgICAgYm90dG9tOiB2YXIoLS1oay1jb2RlYmxvY2stdmVydGljYWwtcGFkZGluZyk7XG4gICAgICB9XG5cbiAgICAgIG9wYWNpdHk6IDAuMjtcbiAgICAgIGZvbnQtZmFtaWx5OiB2YXIoLS1oay1jb2RlYmxvY2stbGluZW5vcy10ZXh0LWZvbnQpO1xuICAgICAgZm9udC1zaXplOiB2YXIoLS1oay1jb2RlYmxvY2stbGluZW5vcy10ZXh0LWZvbnQpO1xuICAgICAgY29sb3I6IHZhcigtLWhrLWNvZGVibG9jay1saW5lbm9zLXRleHQtY29sb3IpO1xuICAgICAgYmFja2dyb3VuZC1jb2xvcjogdHJhbnNwYXJlbnQ7XG5cbiAgICAgIC5saW5lLmhpZ2hsaWdodCB7XG4gICAgICAgIGJhY2tncm91bmQtY29sb3I6IHZhcigtLWhrLWNvZGVibG9jay1oaWdobGlnaHQtYmFja2dyb3VuZC1jb2xvcik7XG4gICAgICB9XG4gICAgfVxuICB9XG59XG5cbi8qIGxhbmd1YWdlICovXG4uaGstY29kZWJsb2NrLmhrLWNvZGVibG9jay1zaG93LWxhbmd1YWdlIHtcbiAgcHJlIHtcbiAgICAuaGstY29kZWJsb2NrLWxhbmd1YWdlIHtcbiAgICAgIG9wYWNpdHk6IDAuNDtcbiAgICAgIHVzZXItc2VsZWN0OiBub25lO1xuICAgICAgei1pbmRleDogMTtcbiAgICAgIG1hcmdpbjogNnB4O1xuXG4gICAgICBwYWRkaW5nOiB7XG4gICAgICAgIHRvcDogNnB4O1xuICAgICAgICBib3R0b206IDZweDtcbiAgICAgICAgbGVmdDogOHB4O1xuICAgICAgICByaWdodDogOHB4O1xuICAgICAgfVxuXG4gICAgICBiYWNrZ3JvdW5kLWNvbG9yOiB0cmFuc3BhcmVudDtcbiAgICAgIGJveC1zaGFkb3c6IG5vbmU7XG4gICAgICBmb250LWZhbWlseTogdmFyKC0taGstY29kZWJsb2NrLWxhbmd1YWdlLXRleHQtZm9udCk7XG4gICAgICBjb2xvcjogdmFyKC0taGstY29kZWJsb2NrLWxhbmd1YWdlLXRleHQtY29sb3IpO1xuICAgICAgZm9udC1zaXplOiB2YXIo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ICAgYmFja2dyb3VuZC1jb2xvcjogI2ZmZmZmZjEzO1xuICAgICAgfVxuXG4gICAgICAmOmFjdGl2ZSB7XG4gICAgICAgIG9wYWNpdHk6IDE7XG4gICAgICAgIGJhY2tncm91bmQtY29sb3I6ICNmZmZmZmYyNjtcbiAgICAgIH1cbiAgICB9XG4gIH1cbn1cblxuLyogcHJvbXB0ICovXG4uaGstY29kZWJsb2NrLmhrLWNvZGVibG9jay1zaG93LXByb21wdCB7XG4gIHByZSB7XG4gICAgLmhrLWNvZGVibG9jay1wcm9tcHQge1xuICAgICAgZmxleC1zaHJpbms6IDA7XG4gICAgICBmbGV4LWdyb3c6IDA7XG4gICAgICB0ZXh0LWFsaWduOiByaWdodDtcblxuICAgICAgcGFkZGluZzoge1xuICAgICAgICB0b3A6IDA7XG4gICAgICAgIGJvdHRvbTogMDtcbiAgICAgICAgbGVmdDogMDtcbiAgICAgICAgcmlnaHQ6IDAuOGVtO1xuICAgICAgfVxuXG4gICAgICBvcGFjaXR5OiAwLjY7XG4gICAgICB1c2VyLXNlbGVjdDogbm9uZTtcbiAgICAgIGNvbG9yOiB2YXIoLS1oay1jb2RlYmxvY2stcHJvbXB0LXRleHQtY29sb3IpO1xuICAgICAgd2hpdGUtc3BhY2U6IHByZTtcbiAgICAgIGZvbnQtZmFtaWx5OiB2YXIoLS1oay1jb2RlYmxvY2stcHJvbXB0LXRleHQtZm9udCk7XG4gICAgICBmb250LXNpemU6IHZhcigtLWhrLWNvZGVibG9jay1wcm9tcHQtdGV4dC1zaXplKTtcbiAgICAgIGJhY2tncm91bmQtY29sb3I6IHRyYW5zcGFyZW50O1xuICAgIH1cbiAgfVxufVxuXG4vKiByZXN1bHQgKi9cbi5oay1jb2RlYmxvY2suaGstY29kZWJsb2NrLXJlc3VsdCB7XG4gIG1hcmdpbi10b3A6IGNhbGModmFyKC0taGstY29kZWJsb2NrLW1hcmdpbikgKiAoLTEpKTtcbiAgYm9yZGVyLXRvcDogMXB4IHNvbGlkIHZ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0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBRUE7QUFDRTtBQUNBOztBQUdGO0FBQ0U7QUFDQTs7QUFTSjtBQUNFO0FBQ0E7QUFDQTtBQUdFO0FBQ0E7QUFDQTtBQUNBO0FBR0Y7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7O0FBTU47QUFDRTtBQUNBO0FBQ0E7O0FBRUE7QUFDRTtBQUNBO0FBQ0E7QUFHRTtBQUNBO0FBQ0E7QUFHRjtBQUNBOztBQUdGO0FBQ0U7O0FBRUE7QUFDRTtBQUNBO0FBQ0E7OyIsCiAgIm5hbWVzIjogW10KfQo= */ diff --git a/enter/.obsidian/plugins/khoj/main.js b/enter/.obsidian/plugins/khoj/main.js new file mode 100644 index 0000000..d7b64f6 --- /dev/null +++ b/enter/.obsidian/plugins/khoj/main.js @@ -0,0 +1,6147 @@ +/* +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 __esm = (fn, res) => function __init() { + return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, 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(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __accessCheck = (obj, member, msg) => { + if (!member.has(obj)) + throw TypeError("Cannot " + msg); +}; +var __privateGet = (obj, member, getter) => { + __accessCheck(obj, member, "read from private field"); + return getter ? getter.call(obj) : member.get(obj); +}; +var __privateAdd = (obj, member, value) => { + if (member.has(obj)) + throw TypeError("Cannot add the same private member more than once"); + member instanceof WeakSet ? member.add(obj) : member.set(obj, value); +}; +var __privateSet = (obj, member, value, setter) => { + __accessCheck(obj, member, "write to private field"); + setter ? setter.call(obj, value) : member.set(obj, value); + return value; +}; + +// node_modules/web-streams-polyfill/dist/ponyfill.es2018.js +var require_ponyfill_es2018 = __commonJS({ + "node_modules/web-streams-polyfill/dist/ponyfill.es2018.js"(exports, module2) { + (function(global2, factory) { + typeof exports === "object" && typeof module2 !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global2 = typeof globalThis !== "undefined" ? globalThis : global2 || self, factory(global2.WebStreamsPolyfill = {})); + })(exports, function(exports2) { + "use strict"; + const SymbolPolyfill = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? Symbol : (description) => `Symbol(${description})`; + function noop2() { + return void 0; + } + function getGlobals() { + if (typeof self !== "undefined") { + return self; + } else if (typeof window !== "undefined") { + return window; + } else if (typeof global !== "undefined") { + return global; + } + return void 0; + } + const globals = getGlobals(); + function typeIsObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + const rethrowAssertionErrorRejection = noop2; + const originalPromise = Promise; + const originalPromiseThen = Promise.prototype.then; + const originalPromiseResolve = Promise.resolve.bind(originalPromise); + const originalPromiseReject = Promise.reject.bind(originalPromise); + function newPromise(executor) { + return new originalPromise(executor); + } + function promiseResolvedWith(value) { + return originalPromiseResolve(value); + } + function promiseRejectedWith(reason) { + return originalPromiseReject(reason); + } + function PerformPromiseThen(promise, onFulfilled, onRejected) { + return originalPromiseThen.call(promise, onFulfilled, onRejected); + } + function uponPromise(promise, onFulfilled, onRejected) { + PerformPromiseThen(PerformPromiseThen(promise, onFulfilled, onRejected), void 0, rethrowAssertionErrorRejection); + } + function uponFulfillment(promise, onFulfilled) { + uponPromise(promise, onFulfilled); + } + function uponRejection(promise, onRejected) { + uponPromise(promise, void 0, onRejected); + } + function transformPromiseWith(promise, fulfillmentHandler, rejectionHandler) { + return PerformPromiseThen(promise, fulfillmentHandler, rejectionHandler); + } + function setPromiseIsHandledToTrue(promise) { + PerformPromiseThen(promise, void 0, rethrowAssertionErrorRejection); + } + const queueMicrotask = (() => { + const globalQueueMicrotask = globals && globals.queueMicrotask; + if (typeof globalQueueMicrotask === "function") { + return globalQueueMicrotask; + } + const resolvedPromise = promiseResolvedWith(void 0); + return (fn) => PerformPromiseThen(resolvedPromise, fn); + })(); + function reflectCall(F2, V, args) { + if (typeof F2 !== "function") { + throw new TypeError("Argument is not a function"); + } + return Function.prototype.apply.call(F2, V, args); + } + function promiseCall(F2, V, args) { + try { + return promiseResolvedWith(reflectCall(F2, V, args)); + } catch (value) { + return promiseRejectedWith(value); + } + } + const QUEUE_MAX_ARRAY_SIZE = 16384; + class SimpleQueue { + constructor() { + this._cursor = 0; + this._size = 0; + this._front = { + _elements: [], + _next: void 0 + }; + this._back = this._front; + this._cursor = 0; + this._size = 0; + } + get length() { + return this._size; + } + push(element) { + const oldBack = this._back; + let newBack = oldBack; + if (oldBack._elements.length === QUEUE_MAX_ARRAY_SIZE - 1) { + newBack = { + _elements: [], + _next: void 0 + }; + } + oldBack._elements.push(element); + if (newBack !== oldBack) { + this._back = newBack; + oldBack._next = newBack; + } + ++this._size; + } + shift() { + const oldFront = this._front; + let newFront = oldFront; + const oldCursor = this._cursor; + let newCursor = oldCursor + 1; + const elements = oldFront._elements; + const element = elements[oldCursor]; + if (newCursor === QUEUE_MAX_ARRAY_SIZE) { + newFront = oldFront._next; + newCursor = 0; + } + --this._size; + this._cursor = newCursor; + if (oldFront !== newFront) { + this._front = newFront; + } + elements[oldCursor] = void 0; + return element; + } + forEach(callback) { + let i2 = this._cursor; + let node = this._front; + let elements = node._elements; + while (i2 !== elements.length || node._next !== void 0) { + if (i2 === elements.length) { + node = node._next; + elements = node._elements; + i2 = 0; + if (elements.length === 0) { + break; + } + } + callback(elements[i2]); + ++i2; + } + } + peek() { + const front = this._front; + const cursor = this._cursor; + return front._elements[cursor]; + } + } + function ReadableStreamReaderGenericInitialize(reader, stream) { + reader._ownerReadableStream = stream; + stream._reader = reader; + if (stream._state === "readable") { + defaultReaderClosedPromiseInitialize(reader); + } else if (stream._state === "closed") { + defaultReaderClosedPromiseInitializeAsResolved(reader); + } else { + defaultReaderClosedPromiseInitializeAsRejected(reader, stream._storedError); + } + } + function ReadableStreamReaderGenericCancel(reader, reason) { + const stream = reader._ownerReadableStream; + return ReadableStreamCancel(stream, reason); + } + function ReadableStreamReaderGenericRelease(reader) { + if (reader._ownerReadableStream._state === "readable") { + defaultReaderClosedPromiseReject(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } else { + defaultReaderClosedPromiseResetToRejected(reader, new TypeError(`Reader was released and can no longer be used to monitor the stream's closedness`)); + } + reader._ownerReadableStream._reader = void 0; + reader._ownerReadableStream = void 0; + } + function readerLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released reader"); + } + function defaultReaderClosedPromiseInitialize(reader) { + reader._closedPromise = newPromise((resolve, reject) => { + reader._closedPromise_resolve = resolve; + reader._closedPromise_reject = reject; + }); + } + function defaultReaderClosedPromiseInitializeAsRejected(reader, reason) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseReject(reader, reason); + } + function defaultReaderClosedPromiseInitializeAsResolved(reader) { + defaultReaderClosedPromiseInitialize(reader); + defaultReaderClosedPromiseResolve(reader); + } + function defaultReaderClosedPromiseReject(reader, reason) { + if (reader._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(reader._closedPromise); + reader._closedPromise_reject(reason); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + function defaultReaderClosedPromiseResetToRejected(reader, reason) { + defaultReaderClosedPromiseInitializeAsRejected(reader, reason); + } + function defaultReaderClosedPromiseResolve(reader) { + if (reader._closedPromise_resolve === void 0) { + return; + } + reader._closedPromise_resolve(void 0); + reader._closedPromise_resolve = void 0; + reader._closedPromise_reject = void 0; + } + const AbortSteps = SymbolPolyfill("[[AbortSteps]]"); + const ErrorSteps = SymbolPolyfill("[[ErrorSteps]]"); + const CancelSteps = SymbolPolyfill("[[CancelSteps]]"); + const PullSteps = SymbolPolyfill("[[PullSteps]]"); + const NumberIsFinite = Number.isFinite || function(x2) { + return typeof x2 === "number" && isFinite(x2); + }; + const MathTrunc = Math.trunc || function(v) { + return v < 0 ? Math.ceil(v) : Math.floor(v); + }; + function isDictionary(x2) { + return typeof x2 === "object" || typeof x2 === "function"; + } + function assertDictionary(obj, context) { + if (obj !== void 0 && !isDictionary(obj)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertFunction(x2, context) { + if (typeof x2 !== "function") { + throw new TypeError(`${context} is not a function.`); + } + } + function isObject(x2) { + return typeof x2 === "object" && x2 !== null || typeof x2 === "function"; + } + function assertObject(x2, context) { + if (!isObject(x2)) { + throw new TypeError(`${context} is not an object.`); + } + } + function assertRequiredArgument(x2, position, context) { + if (x2 === void 0) { + throw new TypeError(`Parameter ${position} is required in '${context}'.`); + } + } + function assertRequiredField(x2, field, context) { + if (x2 === void 0) { + throw new TypeError(`${field} is required in '${context}'.`); + } + } + function convertUnrestrictedDouble(value) { + return Number(value); + } + function censorNegativeZero(x2) { + return x2 === 0 ? 0 : x2; + } + function integerPart(x2) { + return censorNegativeZero(MathTrunc(x2)); + } + function convertUnsignedLongLongWithEnforceRange(value, context) { + const lowerBound = 0; + const upperBound = Number.MAX_SAFE_INTEGER; + let x2 = Number(value); + x2 = censorNegativeZero(x2); + if (!NumberIsFinite(x2)) { + throw new TypeError(`${context} is not a finite number`); + } + x2 = integerPart(x2); + if (x2 < lowerBound || x2 > upperBound) { + throw new TypeError(`${context} is outside the accepted range of ${lowerBound} to ${upperBound}, inclusive`); + } + if (!NumberIsFinite(x2) || x2 === 0) { + return 0; + } + return x2; + } + function assertReadableStream(x2, context) { + if (!IsReadableStream(x2)) { + throw new TypeError(`${context} is not a ReadableStream.`); + } + } + function AcquireReadableStreamDefaultReader(stream) { + return new ReadableStreamDefaultReader(stream); + } + function ReadableStreamAddReadRequest(stream, readRequest) { + stream._reader._readRequests.push(readRequest); + } + function ReadableStreamFulfillReadRequest(stream, chunk, done) { + const reader = stream._reader; + const readRequest = reader._readRequests.shift(); + if (done) { + readRequest._closeSteps(); + } else { + readRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadRequests(stream) { + return stream._reader._readRequests.length; + } + function ReadableStreamHasDefaultReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamDefaultReader(reader)) { + return false; + } + return true; + } + class ReadableStreamDefaultReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamDefaultReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readRequests = new SimpleQueue(); + } + get closed() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + cancel(reason = void 0) { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read() { + if (!IsReadableStreamDefaultReader(this)) { + return promiseRejectedWith(defaultReaderBrandCheckException("read")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: () => resolvePromise({ value: void 0, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamDefaultReaderRead(this, readRequest); + return promise; + } + releaseLock() { + if (!IsReadableStreamDefaultReader(this)) { + throw defaultReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamDefaultReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultReader", + configurable: true + }); + } + function IsReadableStreamDefaultReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readRequests")) { + return false; + } + return x2 instanceof ReadableStreamDefaultReader; + } + function ReadableStreamDefaultReaderRead(reader, readRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "closed") { + readRequest._closeSteps(); + } else if (stream._state === "errored") { + readRequest._errorSteps(stream._storedError); + } else { + stream._readableStreamController[PullSteps](readRequest); + } + } + function defaultReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamDefaultReader.prototype.${name} can only be used on a ReadableStreamDefaultReader`); + } + const AsyncIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf(async function* () { + }).prototype); + class ReadableStreamAsyncIteratorImpl { + constructor(reader, preventCancel) { + this._ongoingPromise = void 0; + this._isFinished = false; + this._reader = reader; + this._preventCancel = preventCancel; + } + next() { + const nextSteps = () => this._nextSteps(); + this._ongoingPromise = this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, nextSteps, nextSteps) : nextSteps(); + return this._ongoingPromise; + } + return(value) { + const returnSteps = () => this._returnSteps(value); + return this._ongoingPromise ? transformPromiseWith(this._ongoingPromise, returnSteps, returnSteps) : returnSteps(); + } + _nextSteps() { + if (this._isFinished) { + return Promise.resolve({ value: void 0, done: true }); + } + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("iterate")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readRequest = { + _chunkSteps: (chunk) => { + this._ongoingPromise = void 0; + queueMicrotask(() => resolvePromise({ value: chunk, done: false })); + }, + _closeSteps: () => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + resolvePromise({ value: void 0, done: true }); + }, + _errorSteps: (reason) => { + this._ongoingPromise = void 0; + this._isFinished = true; + ReadableStreamReaderGenericRelease(reader); + rejectPromise(reason); + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promise; + } + _returnSteps(value) { + if (this._isFinished) { + return Promise.resolve({ value, done: true }); + } + this._isFinished = true; + const reader = this._reader; + if (reader._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("finish iterating")); + } + if (!this._preventCancel) { + const result = ReadableStreamReaderGenericCancel(reader, value); + ReadableStreamReaderGenericRelease(reader); + return transformPromiseWith(result, () => ({ value, done: true })); + } + ReadableStreamReaderGenericRelease(reader); + return promiseResolvedWith({ value, done: true }); + } + } + const ReadableStreamAsyncIteratorPrototype = { + next() { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("next")); + } + return this._asyncIteratorImpl.next(); + }, + return(value) { + if (!IsReadableStreamAsyncIterator(this)) { + return promiseRejectedWith(streamAsyncIteratorBrandCheckException("return")); + } + return this._asyncIteratorImpl.return(value); + } + }; + if (AsyncIteratorPrototype !== void 0) { + Object.setPrototypeOf(ReadableStreamAsyncIteratorPrototype, AsyncIteratorPrototype); + } + function AcquireReadableStreamAsyncIterator(stream, preventCancel) { + const reader = AcquireReadableStreamDefaultReader(stream); + const impl = new ReadableStreamAsyncIteratorImpl(reader, preventCancel); + const iterator = Object.create(ReadableStreamAsyncIteratorPrototype); + iterator._asyncIteratorImpl = impl; + return iterator; + } + function IsReadableStreamAsyncIterator(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_asyncIteratorImpl")) { + return false; + } + try { + return x2._asyncIteratorImpl instanceof ReadableStreamAsyncIteratorImpl; + } catch (_a4) { + return false; + } + } + function streamAsyncIteratorBrandCheckException(name) { + return new TypeError(`ReadableStreamAsyncIterator.${name} can only be used on a ReadableSteamAsyncIterator`); + } + const NumberIsNaN = Number.isNaN || function(x2) { + return x2 !== x2; + }; + function CreateArrayFromList(elements) { + return elements.slice(); + } + function CopyDataBlockBytes(dest, destOffset, src, srcOffset, n) { + new Uint8Array(dest).set(new Uint8Array(src, srcOffset, n), destOffset); + } + function TransferArrayBuffer(O) { + return O; + } + function IsDetachedBuffer(O) { + return false; + } + function ArrayBufferSlice(buffer, begin, end) { + if (buffer.slice) { + return buffer.slice(begin, end); + } + const length = end - begin; + const slice = new ArrayBuffer(length); + CopyDataBlockBytes(slice, 0, buffer, begin, length); + return slice; + } + function IsNonNegativeNumber(v) { + if (typeof v !== "number") { + return false; + } + if (NumberIsNaN(v)) { + return false; + } + if (v < 0) { + return false; + } + return true; + } + function CloneAsUint8Array(O) { + const buffer = ArrayBufferSlice(O.buffer, O.byteOffset, O.byteOffset + O.byteLength); + return new Uint8Array(buffer); + } + function DequeueValue(container) { + const pair = container._queue.shift(); + container._queueTotalSize -= pair.size; + if (container._queueTotalSize < 0) { + container._queueTotalSize = 0; + } + return pair.value; + } + function EnqueueValueWithSize(container, value, size) { + if (!IsNonNegativeNumber(size) || size === Infinity) { + throw new RangeError("Size must be a finite, non-NaN, non-negative number."); + } + container._queue.push({ value, size }); + container._queueTotalSize += size; + } + function PeekQueueValue(container) { + const pair = container._queue.peek(); + return pair.value; + } + function ResetQueue(container) { + container._queue = new SimpleQueue(); + container._queueTotalSize = 0; + } + class ReadableStreamBYOBRequest { + constructor() { + throw new TypeError("Illegal constructor"); + } + get view() { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("view"); + } + return this._view; + } + respond(bytesWritten) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respond"); + } + assertRequiredArgument(bytesWritten, 1, "respond"); + bytesWritten = convertUnsignedLongLongWithEnforceRange(bytesWritten, "First parameter"); + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(this._view.buffer)) + ; + ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController, bytesWritten); + } + respondWithNewView(view) { + if (!IsReadableStreamBYOBRequest(this)) { + throw byobRequestBrandCheckException("respondWithNewView"); + } + assertRequiredArgument(view, 1, "respondWithNewView"); + if (!ArrayBuffer.isView(view)) { + throw new TypeError("You can only respond with array buffer views"); + } + if (this._associatedReadableByteStreamController === void 0) { + throw new TypeError("This BYOB request has been invalidated"); + } + if (IsDetachedBuffer(view.buffer)) + ; + ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController, view); + } + } + Object.defineProperties(ReadableStreamBYOBRequest.prototype, { + respond: { enumerable: true }, + respondWithNewView: { enumerable: true }, + view: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBRequest.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBRequest", + configurable: true + }); + } + class ReadableByteStreamController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get byobRequest() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("byobRequest"); + } + return ReadableByteStreamControllerGetBYOBRequest(this); + } + get desiredSize() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("desiredSize"); + } + return ReadableByteStreamControllerGetDesiredSize(this); + } + close() { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("close"); + } + if (this._closeRequested) { + throw new TypeError("The stream has already been closed; do not close it again!"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be closed`); + } + ReadableByteStreamControllerClose(this); + } + enqueue(chunk) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("enqueue"); + } + assertRequiredArgument(chunk, 1, "enqueue"); + if (!ArrayBuffer.isView(chunk)) { + throw new TypeError("chunk must be an array buffer view"); + } + if (chunk.byteLength === 0) { + throw new TypeError("chunk must have non-zero byteLength"); + } + if (chunk.buffer.byteLength === 0) { + throw new TypeError(`chunk's buffer must have non-zero byteLength`); + } + if (this._closeRequested) { + throw new TypeError("stream is closed or draining"); + } + const state = this._controlledReadableByteStream._state; + if (state !== "readable") { + throw new TypeError(`The stream (in ${state} state) is not in the readable state and cannot be enqueued to`); + } + ReadableByteStreamControllerEnqueue(this, chunk); + } + error(e2 = void 0) { + if (!IsReadableByteStreamController(this)) { + throw byteStreamControllerBrandCheckException("error"); + } + ReadableByteStreamControllerError(this, e2); + } + [CancelSteps](reason) { + ReadableByteStreamControllerClearPendingPullIntos(this); + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableByteStreamControllerClearAlgorithms(this); + return result; + } + [PullSteps](readRequest) { + const stream = this._controlledReadableByteStream; + if (this._queueTotalSize > 0) { + const entry = this._queue.shift(); + this._queueTotalSize -= entry.byteLength; + ReadableByteStreamControllerHandleQueueDrain(this); + const view = new Uint8Array(entry.buffer, entry.byteOffset, entry.byteLength); + readRequest._chunkSteps(view); + return; + } + const autoAllocateChunkSize = this._autoAllocateChunkSize; + if (autoAllocateChunkSize !== void 0) { + let buffer; + try { + buffer = new ArrayBuffer(autoAllocateChunkSize); + } catch (bufferE) { + readRequest._errorSteps(bufferE); + return; + } + const pullIntoDescriptor = { + buffer, + bufferByteLength: autoAllocateChunkSize, + byteOffset: 0, + byteLength: autoAllocateChunkSize, + bytesFilled: 0, + elementSize: 1, + viewConstructor: Uint8Array, + readerType: "default" + }; + this._pendingPullIntos.push(pullIntoDescriptor); + } + ReadableStreamAddReadRequest(stream, readRequest); + ReadableByteStreamControllerCallPullIfNeeded(this); + } + } + Object.defineProperties(ReadableByteStreamController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + byobRequest: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableByteStreamController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableByteStreamController", + configurable: true + }); + } + function IsReadableByteStreamController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableByteStream")) { + return false; + } + return x2 instanceof ReadableByteStreamController; + } + function IsReadableStreamBYOBRequest(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_associatedReadableByteStreamController")) { + return false; + } + return x2 instanceof ReadableStreamBYOBRequest; + } + function ReadableByteStreamControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableByteStreamControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableByteStreamControllerError(controller, e2); + }); + } + function ReadableByteStreamControllerClearPendingPullIntos(controller) { + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + controller._pendingPullIntos = new SimpleQueue(); + } + function ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor) { + let done = false; + if (stream._state === "closed") { + done = true; + } + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + if (pullIntoDescriptor.readerType === "default") { + ReadableStreamFulfillReadRequest(stream, filledView, done); + } else { + ReadableStreamFulfillReadIntoRequest(stream, filledView, done); + } + } + function ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor) { + const bytesFilled = pullIntoDescriptor.bytesFilled; + const elementSize = pullIntoDescriptor.elementSize; + return new pullIntoDescriptor.viewConstructor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, bytesFilled / elementSize); + } + function ReadableByteStreamControllerEnqueueChunkToQueue(controller, buffer, byteOffset, byteLength) { + controller._queue.push({ buffer, byteOffset, byteLength }); + controller._queueTotalSize += byteLength; + } + function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) { + const elementSize = pullIntoDescriptor.elementSize; + const currentAlignedBytes = pullIntoDescriptor.bytesFilled - pullIntoDescriptor.bytesFilled % elementSize; + const maxBytesToCopy = Math.min(controller._queueTotalSize, pullIntoDescriptor.byteLength - pullIntoDescriptor.bytesFilled); + const maxBytesFilled = pullIntoDescriptor.bytesFilled + maxBytesToCopy; + const maxAlignedBytes = maxBytesFilled - maxBytesFilled % elementSize; + let totalBytesToCopyRemaining = maxBytesToCopy; + let ready = false; + if (maxAlignedBytes > currentAlignedBytes) { + totalBytesToCopyRemaining = maxAlignedBytes - pullIntoDescriptor.bytesFilled; + ready = true; + } + const queue = controller._queue; + while (totalBytesToCopyRemaining > 0) { + const headOfQueue = queue.peek(); + const bytesToCopy = Math.min(totalBytesToCopyRemaining, headOfQueue.byteLength); + const destStart = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + CopyDataBlockBytes(pullIntoDescriptor.buffer, destStart, headOfQueue.buffer, headOfQueue.byteOffset, bytesToCopy); + if (headOfQueue.byteLength === bytesToCopy) { + queue.shift(); + } else { + headOfQueue.byteOffset += bytesToCopy; + headOfQueue.byteLength -= bytesToCopy; + } + controller._queueTotalSize -= bytesToCopy; + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor); + totalBytesToCopyRemaining -= bytesToCopy; + } + return ready; + } + function ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, size, pullIntoDescriptor) { + pullIntoDescriptor.bytesFilled += size; + } + function ReadableByteStreamControllerHandleQueueDrain(controller) { + if (controller._queueTotalSize === 0 && controller._closeRequested) { + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(controller._controlledReadableByteStream); + } else { + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + } + function ReadableByteStreamControllerInvalidateBYOBRequest(controller) { + if (controller._byobRequest === null) { + return; + } + controller._byobRequest._associatedReadableByteStreamController = void 0; + controller._byobRequest._view = null; + controller._byobRequest = null; + } + function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller) { + while (controller._pendingPullIntos.length > 0) { + if (controller._queueTotalSize === 0) { + return; + } + const pullIntoDescriptor = controller._pendingPullIntos.peek(); + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerPullInto(controller, view, readIntoRequest) { + const stream = controller._controlledReadableByteStream; + let elementSize = 1; + if (view.constructor !== DataView) { + elementSize = view.constructor.BYTES_PER_ELEMENT; + } + const ctor = view.constructor; + const buffer = TransferArrayBuffer(view.buffer); + const pullIntoDescriptor = { + buffer, + bufferByteLength: buffer.byteLength, + byteOffset: view.byteOffset, + byteLength: view.byteLength, + bytesFilled: 0, + elementSize, + viewConstructor: ctor, + readerType: "byob" + }; + if (controller._pendingPullIntos.length > 0) { + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + return; + } + if (stream._state === "closed") { + const emptyView = new ctor(pullIntoDescriptor.buffer, pullIntoDescriptor.byteOffset, 0); + readIntoRequest._closeSteps(emptyView); + return; + } + if (controller._queueTotalSize > 0) { + if (ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor)) { + const filledView = ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor); + ReadableByteStreamControllerHandleQueueDrain(controller); + readIntoRequest._chunkSteps(filledView); + return; + } + if (controller._closeRequested) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + readIntoRequest._errorSteps(e2); + return; + } + } + controller._pendingPullIntos.push(pullIntoDescriptor); + ReadableStreamAddReadIntoRequest(stream, readIntoRequest); + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor) { + const stream = controller._controlledReadableByteStream; + if (ReadableStreamHasBYOBReader(stream)) { + while (ReadableStreamGetNumReadIntoRequests(stream) > 0) { + const pullIntoDescriptor = ReadableByteStreamControllerShiftPendingPullInto(controller); + ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor); + } + } + } + function ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, pullIntoDescriptor) { + ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor); + if (pullIntoDescriptor.bytesFilled < pullIntoDescriptor.elementSize) { + return; + } + ReadableByteStreamControllerShiftPendingPullInto(controller); + const remainderSize = pullIntoDescriptor.bytesFilled % pullIntoDescriptor.elementSize; + if (remainderSize > 0) { + const end = pullIntoDescriptor.byteOffset + pullIntoDescriptor.bytesFilled; + const remainder = ArrayBufferSlice(pullIntoDescriptor.buffer, end - remainderSize, end); + ReadableByteStreamControllerEnqueueChunkToQueue(controller, remainder, 0, remainder.byteLength); + } + pullIntoDescriptor.bytesFilled -= remainderSize; + ReadableByteStreamControllerCommitPullIntoDescriptor(controller._controlledReadableByteStream, pullIntoDescriptor); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } + function ReadableByteStreamControllerRespondInternal(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + ReadableByteStreamControllerRespondInClosedState(controller); + } else { + ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerShiftPendingPullInto(controller) { + const descriptor = controller._pendingPullIntos.shift(); + return descriptor; + } + function ReadableByteStreamControllerShouldCallPull(controller) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return false; + } + if (controller._closeRequested) { + return false; + } + if (!controller._started) { + return false; + } + if (ReadableStreamHasDefaultReader(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + if (ReadableStreamHasBYOBReader(stream) && ReadableStreamGetNumReadIntoRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableByteStreamControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableByteStreamControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + } + function ReadableByteStreamControllerClose(controller) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + if (controller._queueTotalSize > 0) { + controller._closeRequested = true; + return; + } + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (firstPendingPullInto.bytesFilled > 0) { + const e2 = new TypeError("Insufficient bytes to fill elements in the given buffer"); + ReadableByteStreamControllerError(controller, e2); + throw e2; + } + } + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + function ReadableByteStreamControllerEnqueue(controller, chunk) { + const stream = controller._controlledReadableByteStream; + if (controller._closeRequested || stream._state !== "readable") { + return; + } + const buffer = chunk.buffer; + const byteOffset = chunk.byteOffset; + const byteLength = chunk.byteLength; + const transferredBuffer = TransferArrayBuffer(buffer); + if (controller._pendingPullIntos.length > 0) { + const firstPendingPullInto = controller._pendingPullIntos.peek(); + if (IsDetachedBuffer(firstPendingPullInto.buffer)) + ; + firstPendingPullInto.buffer = TransferArrayBuffer(firstPendingPullInto.buffer); + } + ReadableByteStreamControllerInvalidateBYOBRequest(controller); + if (ReadableStreamHasDefaultReader(stream)) { + if (ReadableStreamGetNumReadRequests(stream) === 0) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } else { + if (controller._pendingPullIntos.length > 0) { + ReadableByteStreamControllerShiftPendingPullInto(controller); + } + const transferredView = new Uint8Array(transferredBuffer, byteOffset, byteLength); + ReadableStreamFulfillReadRequest(stream, transferredView, false); + } + } else if (ReadableStreamHasBYOBReader(stream)) { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller); + } else { + ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength); + } + ReadableByteStreamControllerCallPullIfNeeded(controller); + } + function ReadableByteStreamControllerError(controller, e2) { + const stream = controller._controlledReadableByteStream; + if (stream._state !== "readable") { + return; + } + ReadableByteStreamControllerClearPendingPullIntos(controller); + ResetQueue(controller); + ReadableByteStreamControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableByteStreamControllerGetBYOBRequest(controller) { + if (controller._byobRequest === null && controller._pendingPullIntos.length > 0) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const view = new Uint8Array(firstDescriptor.buffer, firstDescriptor.byteOffset + firstDescriptor.bytesFilled, firstDescriptor.byteLength - firstDescriptor.bytesFilled); + const byobRequest = Object.create(ReadableStreamBYOBRequest.prototype); + SetUpReadableStreamBYOBRequest(byobRequest, controller, view); + controller._byobRequest = byobRequest; + } + return controller._byobRequest; + } + function ReadableByteStreamControllerGetDesiredSize(controller) { + const state = controller._controlledReadableByteStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableByteStreamControllerRespond(controller, bytesWritten) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (bytesWritten !== 0) { + throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream"); + } + } else { + if (bytesWritten === 0) { + throw new TypeError("bytesWritten must be greater than 0 when calling respond() on a readable stream"); + } + if (firstDescriptor.bytesFilled + bytesWritten > firstDescriptor.byteLength) { + throw new RangeError("bytesWritten out of range"); + } + } + firstDescriptor.buffer = TransferArrayBuffer(firstDescriptor.buffer); + ReadableByteStreamControllerRespondInternal(controller, bytesWritten); + } + function ReadableByteStreamControllerRespondWithNewView(controller, view) { + const firstDescriptor = controller._pendingPullIntos.peek(); + const state = controller._controlledReadableByteStream._state; + if (state === "closed") { + if (view.byteLength !== 0) { + throw new TypeError("The view's length must be 0 when calling respondWithNewView() on a closed stream"); + } + } else { + if (view.byteLength === 0) { + throw new TypeError("The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"); + } + } + if (firstDescriptor.byteOffset + firstDescriptor.bytesFilled !== view.byteOffset) { + throw new RangeError("The region specified by view does not match byobRequest"); + } + if (firstDescriptor.bufferByteLength !== view.buffer.byteLength) { + throw new RangeError("The buffer of view has different capacity than byobRequest"); + } + if (firstDescriptor.bytesFilled + view.byteLength > firstDescriptor.byteLength) { + throw new RangeError("The region specified by view is larger than byobRequest"); + } + const viewByteLength = view.byteLength; + firstDescriptor.buffer = TransferArrayBuffer(view.buffer); + ReadableByteStreamControllerRespondInternal(controller, viewByteLength); + } + function SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize) { + controller._controlledReadableByteStream = stream; + controller._pullAgain = false; + controller._pulling = false; + controller._byobRequest = null; + controller._queue = controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._closeRequested = false; + controller._started = false; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + controller._autoAllocateChunkSize = autoAllocateChunkSize; + controller._pendingPullIntos = new SimpleQueue(); + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableByteStreamControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableByteStreamControllerError(controller, r2); + }); + } + function SetUpReadableByteStreamControllerFromUnderlyingSource(stream, underlyingByteSource, highWaterMark) { + const controller = Object.create(ReadableByteStreamController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingByteSource.start !== void 0) { + startAlgorithm = () => underlyingByteSource.start(controller); + } + if (underlyingByteSource.pull !== void 0) { + pullAlgorithm = () => underlyingByteSource.pull(controller); + } + if (underlyingByteSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingByteSource.cancel(reason); + } + const autoAllocateChunkSize = underlyingByteSource.autoAllocateChunkSize; + if (autoAllocateChunkSize === 0) { + throw new TypeError("autoAllocateChunkSize must be greater than 0"); + } + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize); + } + function SetUpReadableStreamBYOBRequest(request5, controller, view) { + request5._associatedReadableByteStreamController = controller; + request5._view = view; + } + function byobRequestBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBRequest.prototype.${name} can only be used on a ReadableStreamBYOBRequest`); + } + function byteStreamControllerBrandCheckException(name) { + return new TypeError(`ReadableByteStreamController.prototype.${name} can only be used on a ReadableByteStreamController`); + } + function AcquireReadableStreamBYOBReader(stream) { + return new ReadableStreamBYOBReader(stream); + } + function ReadableStreamAddReadIntoRequest(stream, readIntoRequest) { + stream._reader._readIntoRequests.push(readIntoRequest); + } + function ReadableStreamFulfillReadIntoRequest(stream, chunk, done) { + const reader = stream._reader; + const readIntoRequest = reader._readIntoRequests.shift(); + if (done) { + readIntoRequest._closeSteps(chunk); + } else { + readIntoRequest._chunkSteps(chunk); + } + } + function ReadableStreamGetNumReadIntoRequests(stream) { + return stream._reader._readIntoRequests.length; + } + function ReadableStreamHasBYOBReader(stream) { + const reader = stream._reader; + if (reader === void 0) { + return false; + } + if (!IsReadableStreamBYOBReader(reader)) { + return false; + } + return true; + } + class ReadableStreamBYOBReader { + constructor(stream) { + assertRequiredArgument(stream, 1, "ReadableStreamBYOBReader"); + assertReadableStream(stream, "First parameter"); + if (IsReadableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive reading by another reader"); + } + if (!IsReadableByteStreamController(stream._readableStreamController)) { + throw new TypeError("Cannot construct a ReadableStreamBYOBReader for a stream not constructed with a byte source"); + } + ReadableStreamReaderGenericInitialize(this, stream); + this._readIntoRequests = new SimpleQueue(); + } + get closed() { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("closed")); + } + return this._closedPromise; + } + cancel(reason = void 0) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("cancel")); + } + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("cancel")); + } + return ReadableStreamReaderGenericCancel(this, reason); + } + read(view) { + if (!IsReadableStreamBYOBReader(this)) { + return promiseRejectedWith(byobReaderBrandCheckException("read")); + } + if (!ArrayBuffer.isView(view)) { + return promiseRejectedWith(new TypeError("view must be an array buffer view")); + } + if (view.byteLength === 0) { + return promiseRejectedWith(new TypeError("view must have non-zero byteLength")); + } + if (view.buffer.byteLength === 0) { + return promiseRejectedWith(new TypeError(`view's buffer must have non-zero byteLength`)); + } + if (IsDetachedBuffer(view.buffer)) + ; + if (this._ownerReadableStream === void 0) { + return promiseRejectedWith(readerLockException("read from")); + } + let resolvePromise; + let rejectPromise; + const promise = newPromise((resolve, reject) => { + resolvePromise = resolve; + rejectPromise = reject; + }); + const readIntoRequest = { + _chunkSteps: (chunk) => resolvePromise({ value: chunk, done: false }), + _closeSteps: (chunk) => resolvePromise({ value: chunk, done: true }), + _errorSteps: (e2) => rejectPromise(e2) + }; + ReadableStreamBYOBReaderRead(this, view, readIntoRequest); + return promise; + } + releaseLock() { + if (!IsReadableStreamBYOBReader(this)) { + throw byobReaderBrandCheckException("releaseLock"); + } + if (this._ownerReadableStream === void 0) { + return; + } + if (this._readIntoRequests.length > 0) { + throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled"); + } + ReadableStreamReaderGenericRelease(this); + } + } + Object.defineProperties(ReadableStreamBYOBReader.prototype, { + cancel: { enumerable: true }, + read: { enumerable: true }, + releaseLock: { enumerable: true }, + closed: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamBYOBReader.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamBYOBReader", + configurable: true + }); + } + function IsReadableStreamBYOBReader(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readIntoRequests")) { + return false; + } + return x2 instanceof ReadableStreamBYOBReader; + } + function ReadableStreamBYOBReaderRead(reader, view, readIntoRequest) { + const stream = reader._ownerReadableStream; + stream._disturbed = true; + if (stream._state === "errored") { + readIntoRequest._errorSteps(stream._storedError); + } else { + ReadableByteStreamControllerPullInto(stream._readableStreamController, view, readIntoRequest); + } + } + function byobReaderBrandCheckException(name) { + return new TypeError(`ReadableStreamBYOBReader.prototype.${name} can only be used on a ReadableStreamBYOBReader`); + } + function ExtractHighWaterMark(strategy, defaultHWM) { + const { highWaterMark } = strategy; + if (highWaterMark === void 0) { + return defaultHWM; + } + if (NumberIsNaN(highWaterMark) || highWaterMark < 0) { + throw new RangeError("Invalid highWaterMark"); + } + return highWaterMark; + } + function ExtractSizeAlgorithm(strategy) { + const { size } = strategy; + if (!size) { + return () => 1; + } + return size; + } + function convertQueuingStrategy(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + const size = init === null || init === void 0 ? void 0 : init.size; + return { + highWaterMark: highWaterMark === void 0 ? void 0 : convertUnrestrictedDouble(highWaterMark), + size: size === void 0 ? void 0 : convertQueuingStrategySize(size, `${context} has member 'size' that`) + }; + } + function convertQueuingStrategySize(fn, context) { + assertFunction(fn, context); + return (chunk) => convertUnrestrictedDouble(fn(chunk)); + } + function convertUnderlyingSink(original, context) { + assertDictionary(original, context); + const abort = original === null || original === void 0 ? void 0 : original.abort; + const close = original === null || original === void 0 ? void 0 : original.close; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + const write = original === null || original === void 0 ? void 0 : original.write; + return { + abort: abort === void 0 ? void 0 : convertUnderlyingSinkAbortCallback(abort, original, `${context} has member 'abort' that`), + close: close === void 0 ? void 0 : convertUnderlyingSinkCloseCallback(close, original, `${context} has member 'close' that`), + start: start === void 0 ? void 0 : convertUnderlyingSinkStartCallback(start, original, `${context} has member 'start' that`), + write: write === void 0 ? void 0 : convertUnderlyingSinkWriteCallback(write, original, `${context} has member 'write' that`), + type + }; + } + function convertUnderlyingSinkAbortCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSinkCloseCallback(fn, original, context) { + assertFunction(fn, context); + return () => promiseCall(fn, original, []); + } + function convertUnderlyingSinkStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertUnderlyingSinkWriteCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + function assertWritableStream(x2, context) { + if (!IsWritableStream(x2)) { + throw new TypeError(`${context} is not a WritableStream.`); + } + } + function isAbortSignal2(value) { + if (typeof value !== "object" || value === null) { + return false; + } + try { + return typeof value.aborted === "boolean"; + } catch (_a4) { + return false; + } + } + const supportsAbortController = typeof AbortController === "function"; + function createAbortController() { + if (supportsAbortController) { + return new AbortController(); + } + return void 0; + } + class WritableStream { + constructor(rawUnderlyingSink = {}, rawStrategy = {}) { + if (rawUnderlyingSink === void 0) { + rawUnderlyingSink = null; + } else { + assertObject(rawUnderlyingSink, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSink = convertUnderlyingSink(rawUnderlyingSink, "First parameter"); + InitializeWritableStream(this); + const type = underlyingSink.type; + if (type !== void 0) { + throw new RangeError("Invalid type is specified"); + } + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpWritableStreamDefaultControllerFromUnderlyingSink(this, underlyingSink, highWaterMark, sizeAlgorithm); + } + get locked() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("locked"); + } + return IsWritableStreamLocked(this); + } + abort(reason = void 0) { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("abort")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot abort a stream that already has a writer")); + } + return WritableStreamAbort(this, reason); + } + close() { + if (!IsWritableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$2("close")); + } + if (IsWritableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot close a stream that already has a writer")); + } + if (WritableStreamCloseQueuedOrInFlight(this)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamClose(this); + } + getWriter() { + if (!IsWritableStream(this)) { + throw streamBrandCheckException$2("getWriter"); + } + return AcquireWritableStreamDefaultWriter(this); + } + } + Object.defineProperties(WritableStream.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + getWriter: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStream.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStream", + configurable: true + }); + } + function AcquireWritableStreamDefaultWriter(stream) { + return new WritableStreamDefaultWriter(stream); + } + function CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(WritableStream.prototype); + InitializeWritableStream(stream); + const controller = Object.create(WritableStreamDefaultController.prototype); + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function InitializeWritableStream(stream) { + stream._state = "writable"; + stream._storedError = void 0; + stream._writer = void 0; + stream._writableStreamController = void 0; + stream._writeRequests = new SimpleQueue(); + stream._inFlightWriteRequest = void 0; + stream._closeRequest = void 0; + stream._inFlightCloseRequest = void 0; + stream._pendingAbortRequest = void 0; + stream._backpressure = false; + } + function IsWritableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_writableStreamController")) { + return false; + } + return x2 instanceof WritableStream; + } + function IsWritableStreamLocked(stream) { + if (stream._writer === void 0) { + return false; + } + return true; + } + function WritableStreamAbort(stream, reason) { + var _a4; + if (stream._state === "closed" || stream._state === "errored") { + return promiseResolvedWith(void 0); + } + stream._writableStreamController._abortReason = reason; + (_a4 = stream._writableStreamController._abortController) === null || _a4 === void 0 ? void 0 : _a4.abort(); + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseResolvedWith(void 0); + } + if (stream._pendingAbortRequest !== void 0) { + return stream._pendingAbortRequest._promise; + } + let wasAlreadyErroring = false; + if (state === "erroring") { + wasAlreadyErroring = true; + reason = void 0; + } + const promise = newPromise((resolve, reject) => { + stream._pendingAbortRequest = { + _promise: void 0, + _resolve: resolve, + _reject: reject, + _reason: reason, + _wasAlreadyErroring: wasAlreadyErroring + }; + }); + stream._pendingAbortRequest._promise = promise; + if (!wasAlreadyErroring) { + WritableStreamStartErroring(stream, reason); + } + return promise; + } + function WritableStreamClose(stream) { + const state = stream._state; + if (state === "closed" || state === "errored") { + return promiseRejectedWith(new TypeError(`The stream (in ${state} state) is not in the writable state and cannot be closed`)); + } + const promise = newPromise((resolve, reject) => { + const closeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._closeRequest = closeRequest; + }); + const writer = stream._writer; + if (writer !== void 0 && stream._backpressure && state === "writable") { + defaultWriterReadyPromiseResolve(writer); + } + WritableStreamDefaultControllerClose(stream._writableStreamController); + return promise; + } + function WritableStreamAddWriteRequest(stream) { + const promise = newPromise((resolve, reject) => { + const writeRequest = { + _resolve: resolve, + _reject: reject + }; + stream._writeRequests.push(writeRequest); + }); + return promise; + } + function WritableStreamDealWithRejection(stream, error) { + const state = stream._state; + if (state === "writable") { + WritableStreamStartErroring(stream, error); + return; + } + WritableStreamFinishErroring(stream); + } + function WritableStreamStartErroring(stream, reason) { + const controller = stream._writableStreamController; + stream._state = "erroring"; + stream._storedError = reason; + const writer = stream._writer; + if (writer !== void 0) { + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, reason); + } + if (!WritableStreamHasOperationMarkedInFlight(stream) && controller._started) { + WritableStreamFinishErroring(stream); + } + } + function WritableStreamFinishErroring(stream) { + stream._state = "errored"; + stream._writableStreamController[ErrorSteps](); + const storedError = stream._storedError; + stream._writeRequests.forEach((writeRequest) => { + writeRequest._reject(storedError); + }); + stream._writeRequests = new SimpleQueue(); + if (stream._pendingAbortRequest === void 0) { + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const abortRequest = stream._pendingAbortRequest; + stream._pendingAbortRequest = void 0; + if (abortRequest._wasAlreadyErroring) { + abortRequest._reject(storedError); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + return; + } + const promise = stream._writableStreamController[AbortSteps](abortRequest._reason); + uponPromise(promise, () => { + abortRequest._resolve(); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }, (reason) => { + abortRequest._reject(reason); + WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream); + }); + } + function WritableStreamFinishInFlightWrite(stream) { + stream._inFlightWriteRequest._resolve(void 0); + stream._inFlightWriteRequest = void 0; + } + function WritableStreamFinishInFlightWriteWithError(stream, error) { + stream._inFlightWriteRequest._reject(error); + stream._inFlightWriteRequest = void 0; + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamFinishInFlightClose(stream) { + stream._inFlightCloseRequest._resolve(void 0); + stream._inFlightCloseRequest = void 0; + const state = stream._state; + if (state === "erroring") { + stream._storedError = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._resolve(); + stream._pendingAbortRequest = void 0; + } + } + stream._state = "closed"; + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseResolve(writer); + } + } + function WritableStreamFinishInFlightCloseWithError(stream, error) { + stream._inFlightCloseRequest._reject(error); + stream._inFlightCloseRequest = void 0; + if (stream._pendingAbortRequest !== void 0) { + stream._pendingAbortRequest._reject(error); + stream._pendingAbortRequest = void 0; + } + WritableStreamDealWithRejection(stream, error); + } + function WritableStreamCloseQueuedOrInFlight(stream) { + if (stream._closeRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamHasOperationMarkedInFlight(stream) { + if (stream._inFlightWriteRequest === void 0 && stream._inFlightCloseRequest === void 0) { + return false; + } + return true; + } + function WritableStreamMarkCloseRequestInFlight(stream) { + stream._inFlightCloseRequest = stream._closeRequest; + stream._closeRequest = void 0; + } + function WritableStreamMarkFirstWriteRequestInFlight(stream) { + stream._inFlightWriteRequest = stream._writeRequests.shift(); + } + function WritableStreamRejectCloseAndClosedPromiseIfNeeded(stream) { + if (stream._closeRequest !== void 0) { + stream._closeRequest._reject(stream._storedError); + stream._closeRequest = void 0; + } + const writer = stream._writer; + if (writer !== void 0) { + defaultWriterClosedPromiseReject(writer, stream._storedError); + } + } + function WritableStreamUpdateBackpressure(stream, backpressure) { + const writer = stream._writer; + if (writer !== void 0 && backpressure !== stream._backpressure) { + if (backpressure) { + defaultWriterReadyPromiseReset(writer); + } else { + defaultWriterReadyPromiseResolve(writer); + } + } + stream._backpressure = backpressure; + } + class WritableStreamDefaultWriter { + constructor(stream) { + assertRequiredArgument(stream, 1, "WritableStreamDefaultWriter"); + assertWritableStream(stream, "First parameter"); + if (IsWritableStreamLocked(stream)) { + throw new TypeError("This stream has already been locked for exclusive writing by another writer"); + } + this._ownerWritableStream = stream; + stream._writer = this; + const state = stream._state; + if (state === "writable") { + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._backpressure) { + defaultWriterReadyPromiseInitialize(this); + } else { + defaultWriterReadyPromiseInitializeAsResolved(this); + } + defaultWriterClosedPromiseInitialize(this); + } else if (state === "erroring") { + defaultWriterReadyPromiseInitializeAsRejected(this, stream._storedError); + defaultWriterClosedPromiseInitialize(this); + } else if (state === "closed") { + defaultWriterReadyPromiseInitializeAsResolved(this); + defaultWriterClosedPromiseInitializeAsResolved(this); + } else { + const storedError = stream._storedError; + defaultWriterReadyPromiseInitializeAsRejected(this, storedError); + defaultWriterClosedPromiseInitializeAsRejected(this, storedError); + } + } + get closed() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("closed")); + } + return this._closedPromise; + } + get desiredSize() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("desiredSize"); + } + if (this._ownerWritableStream === void 0) { + throw defaultWriterLockException("desiredSize"); + } + return WritableStreamDefaultWriterGetDesiredSize(this); + } + get ready() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("ready")); + } + return this._readyPromise; + } + abort(reason = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("abort")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("abort")); + } + return WritableStreamDefaultWriterAbort(this, reason); + } + close() { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("close")); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return promiseRejectedWith(defaultWriterLockException("close")); + } + if (WritableStreamCloseQueuedOrInFlight(stream)) { + return promiseRejectedWith(new TypeError("Cannot close an already-closing stream")); + } + return WritableStreamDefaultWriterClose(this); + } + releaseLock() { + if (!IsWritableStreamDefaultWriter(this)) { + throw defaultWriterBrandCheckException("releaseLock"); + } + const stream = this._ownerWritableStream; + if (stream === void 0) { + return; + } + WritableStreamDefaultWriterRelease(this); + } + write(chunk = void 0) { + if (!IsWritableStreamDefaultWriter(this)) { + return promiseRejectedWith(defaultWriterBrandCheckException("write")); + } + if (this._ownerWritableStream === void 0) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + return WritableStreamDefaultWriterWrite(this, chunk); + } + } + Object.defineProperties(WritableStreamDefaultWriter.prototype, { + abort: { enumerable: true }, + close: { enumerable: true }, + releaseLock: { enumerable: true }, + write: { enumerable: true }, + closed: { enumerable: true }, + desiredSize: { enumerable: true }, + ready: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultWriter.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultWriter", + configurable: true + }); + } + function IsWritableStreamDefaultWriter(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_ownerWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultWriter; + } + function WritableStreamDefaultWriterAbort(writer, reason) { + const stream = writer._ownerWritableStream; + return WritableStreamAbort(stream, reason); + } + function WritableStreamDefaultWriterClose(writer) { + const stream = writer._ownerWritableStream; + return WritableStreamClose(stream); + } + function WritableStreamDefaultWriterCloseWithErrorPropagation(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseResolvedWith(void 0); + } + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + return WritableStreamDefaultWriterClose(writer); + } + function WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, error) { + if (writer._closedPromiseState === "pending") { + defaultWriterClosedPromiseReject(writer, error); + } else { + defaultWriterClosedPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, error) { + if (writer._readyPromiseState === "pending") { + defaultWriterReadyPromiseReject(writer, error); + } else { + defaultWriterReadyPromiseResetToRejected(writer, error); + } + } + function WritableStreamDefaultWriterGetDesiredSize(writer) { + const stream = writer._ownerWritableStream; + const state = stream._state; + if (state === "errored" || state === "erroring") { + return null; + } + if (state === "closed") { + return 0; + } + return WritableStreamDefaultControllerGetDesiredSize(stream._writableStreamController); + } + function WritableStreamDefaultWriterRelease(writer) { + const stream = writer._ownerWritableStream; + const releasedError = new TypeError(`Writer was released and can no longer be used to monitor the stream's closedness`); + WritableStreamDefaultWriterEnsureReadyPromiseRejected(writer, releasedError); + WritableStreamDefaultWriterEnsureClosedPromiseRejected(writer, releasedError); + stream._writer = void 0; + writer._ownerWritableStream = void 0; + } + function WritableStreamDefaultWriterWrite(writer, chunk) { + const stream = writer._ownerWritableStream; + const controller = stream._writableStreamController; + const chunkSize = WritableStreamDefaultControllerGetChunkSize(controller, chunk); + if (stream !== writer._ownerWritableStream) { + return promiseRejectedWith(defaultWriterLockException("write to")); + } + const state = stream._state; + if (state === "errored") { + return promiseRejectedWith(stream._storedError); + } + if (WritableStreamCloseQueuedOrInFlight(stream) || state === "closed") { + return promiseRejectedWith(new TypeError("The stream is closing or closed and cannot be written to")); + } + if (state === "erroring") { + return promiseRejectedWith(stream._storedError); + } + const promise = WritableStreamAddWriteRequest(stream); + WritableStreamDefaultControllerWrite(controller, chunk, chunkSize); + return promise; + } + const closeSentinel = {}; + class WritableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get abortReason() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("abortReason"); + } + return this._abortReason; + } + get signal() { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("signal"); + } + if (this._abortController === void 0) { + throw new TypeError("WritableStreamDefaultController.prototype.signal is not supported"); + } + return this._abortController.signal; + } + error(e2 = void 0) { + if (!IsWritableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$2("error"); + } + const state = this._controlledWritableStream._state; + if (state !== "writable") { + return; + } + WritableStreamDefaultControllerError(this, e2); + } + [AbortSteps](reason) { + const result = this._abortAlgorithm(reason); + WritableStreamDefaultControllerClearAlgorithms(this); + return result; + } + [ErrorSteps]() { + ResetQueue(this); + } + } + Object.defineProperties(WritableStreamDefaultController.prototype, { + abortReason: { enumerable: true }, + signal: { enumerable: true }, + error: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(WritableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "WritableStreamDefaultController", + configurable: true + }); + } + function IsWritableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledWritableStream")) { + return false; + } + return x2 instanceof WritableStreamDefaultController; + } + function SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledWritableStream = stream; + stream._writableStreamController = controller; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._abortReason = void 0; + controller._abortController = createAbortController(); + controller._started = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._writeAlgorithm = writeAlgorithm; + controller._closeAlgorithm = closeAlgorithm; + controller._abortAlgorithm = abortAlgorithm; + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + const startResult = startAlgorithm(); + const startPromise = promiseResolvedWith(startResult); + uponPromise(startPromise, () => { + controller._started = true; + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (r2) => { + controller._started = true; + WritableStreamDealWithRejection(stream, r2); + }); + } + function SetUpWritableStreamDefaultControllerFromUnderlyingSink(stream, underlyingSink, highWaterMark, sizeAlgorithm) { + const controller = Object.create(WritableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let writeAlgorithm = () => promiseResolvedWith(void 0); + let closeAlgorithm = () => promiseResolvedWith(void 0); + let abortAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSink.start !== void 0) { + startAlgorithm = () => underlyingSink.start(controller); + } + if (underlyingSink.write !== void 0) { + writeAlgorithm = (chunk) => underlyingSink.write(chunk, controller); + } + if (underlyingSink.close !== void 0) { + closeAlgorithm = () => underlyingSink.close(); + } + if (underlyingSink.abort !== void 0) { + abortAlgorithm = (reason) => underlyingSink.abort(reason); + } + SetUpWritableStreamDefaultController(stream, controller, startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, highWaterMark, sizeAlgorithm); + } + function WritableStreamDefaultControllerClearAlgorithms(controller) { + controller._writeAlgorithm = void 0; + controller._closeAlgorithm = void 0; + controller._abortAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function WritableStreamDefaultControllerClose(controller) { + EnqueueValueWithSize(controller, closeSentinel, 0); + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerGetChunkSize(controller, chunk) { + try { + return controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, chunkSizeE); + return 1; + } + } + function WritableStreamDefaultControllerGetDesiredSize(controller) { + return controller._strategyHWM - controller._queueTotalSize; + } + function WritableStreamDefaultControllerWrite(controller, chunk, chunkSize) { + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueE); + return; + } + const stream = controller._controlledWritableStream; + if (!WritableStreamCloseQueuedOrInFlight(stream) && stream._state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + } + function WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller) { + const stream = controller._controlledWritableStream; + if (!controller._started) { + return; + } + if (stream._inFlightWriteRequest !== void 0) { + return; + } + const state = stream._state; + if (state === "erroring") { + WritableStreamFinishErroring(stream); + return; + } + if (controller._queue.length === 0) { + return; + } + const value = PeekQueueValue(controller); + if (value === closeSentinel) { + WritableStreamDefaultControllerProcessClose(controller); + } else { + WritableStreamDefaultControllerProcessWrite(controller, value); + } + } + function WritableStreamDefaultControllerErrorIfNeeded(controller, error) { + if (controller._controlledWritableStream._state === "writable") { + WritableStreamDefaultControllerError(controller, error); + } + } + function WritableStreamDefaultControllerProcessClose(controller) { + const stream = controller._controlledWritableStream; + WritableStreamMarkCloseRequestInFlight(stream); + DequeueValue(controller); + const sinkClosePromise = controller._closeAlgorithm(); + WritableStreamDefaultControllerClearAlgorithms(controller); + uponPromise(sinkClosePromise, () => { + WritableStreamFinishInFlightClose(stream); + }, (reason) => { + WritableStreamFinishInFlightCloseWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerProcessWrite(controller, chunk) { + const stream = controller._controlledWritableStream; + WritableStreamMarkFirstWriteRequestInFlight(stream); + const sinkWritePromise = controller._writeAlgorithm(chunk); + uponPromise(sinkWritePromise, () => { + WritableStreamFinishInFlightWrite(stream); + const state = stream._state; + DequeueValue(controller); + if (!WritableStreamCloseQueuedOrInFlight(stream) && state === "writable") { + const backpressure = WritableStreamDefaultControllerGetBackpressure(controller); + WritableStreamUpdateBackpressure(stream, backpressure); + } + WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller); + }, (reason) => { + if (stream._state === "writable") { + WritableStreamDefaultControllerClearAlgorithms(controller); + } + WritableStreamFinishInFlightWriteWithError(stream, reason); + }); + } + function WritableStreamDefaultControllerGetBackpressure(controller) { + const desiredSize = WritableStreamDefaultControllerGetDesiredSize(controller); + return desiredSize <= 0; + } + function WritableStreamDefaultControllerError(controller, error) { + const stream = controller._controlledWritableStream; + WritableStreamDefaultControllerClearAlgorithms(controller); + WritableStreamStartErroring(stream, error); + } + function streamBrandCheckException$2(name) { + return new TypeError(`WritableStream.prototype.${name} can only be used on a WritableStream`); + } + function defaultControllerBrandCheckException$2(name) { + return new TypeError(`WritableStreamDefaultController.prototype.${name} can only be used on a WritableStreamDefaultController`); + } + function defaultWriterBrandCheckException(name) { + return new TypeError(`WritableStreamDefaultWriter.prototype.${name} can only be used on a WritableStreamDefaultWriter`); + } + function defaultWriterLockException(name) { + return new TypeError("Cannot " + name + " a stream using a released writer"); + } + function defaultWriterClosedPromiseInitialize(writer) { + writer._closedPromise = newPromise((resolve, reject) => { + writer._closedPromise_resolve = resolve; + writer._closedPromise_reject = reject; + writer._closedPromiseState = "pending"; + }); + } + function defaultWriterClosedPromiseInitializeAsRejected(writer, reason) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseReject(writer, reason); + } + function defaultWriterClosedPromiseInitializeAsResolved(writer) { + defaultWriterClosedPromiseInitialize(writer); + defaultWriterClosedPromiseResolve(writer); + } + function defaultWriterClosedPromiseReject(writer, reason) { + if (writer._closedPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._closedPromise); + writer._closedPromise_reject(reason); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "rejected"; + } + function defaultWriterClosedPromiseResetToRejected(writer, reason) { + defaultWriterClosedPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterClosedPromiseResolve(writer) { + if (writer._closedPromise_resolve === void 0) { + return; + } + writer._closedPromise_resolve(void 0); + writer._closedPromise_resolve = void 0; + writer._closedPromise_reject = void 0; + writer._closedPromiseState = "resolved"; + } + function defaultWriterReadyPromiseInitialize(writer) { + writer._readyPromise = newPromise((resolve, reject) => { + writer._readyPromise_resolve = resolve; + writer._readyPromise_reject = reject; + }); + writer._readyPromiseState = "pending"; + } + function defaultWriterReadyPromiseInitializeAsRejected(writer, reason) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseReject(writer, reason); + } + function defaultWriterReadyPromiseInitializeAsResolved(writer) { + defaultWriterReadyPromiseInitialize(writer); + defaultWriterReadyPromiseResolve(writer); + } + function defaultWriterReadyPromiseReject(writer, reason) { + if (writer._readyPromise_reject === void 0) { + return; + } + setPromiseIsHandledToTrue(writer._readyPromise); + writer._readyPromise_reject(reason); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "rejected"; + } + function defaultWriterReadyPromiseReset(writer) { + defaultWriterReadyPromiseInitialize(writer); + } + function defaultWriterReadyPromiseResetToRejected(writer, reason) { + defaultWriterReadyPromiseInitializeAsRejected(writer, reason); + } + function defaultWriterReadyPromiseResolve(writer) { + if (writer._readyPromise_resolve === void 0) { + return; + } + writer._readyPromise_resolve(void 0); + writer._readyPromise_resolve = void 0; + writer._readyPromise_reject = void 0; + writer._readyPromiseState = "fulfilled"; + } + const NativeDOMException = typeof DOMException !== "undefined" ? DOMException : void 0; + function isDOMExceptionConstructor(ctor) { + if (!(typeof ctor === "function" || typeof ctor === "object")) { + return false; + } + try { + new ctor(); + return true; + } catch (_a4) { + return false; + } + } + function createDOMExceptionPolyfill() { + const ctor = function DOMException3(message, name) { + this.message = message || ""; + this.name = name || "Error"; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + }; + ctor.prototype = Object.create(Error.prototype); + Object.defineProperty(ctor.prototype, "constructor", { value: ctor, writable: true, configurable: true }); + return ctor; + } + const DOMException$1 = isDOMExceptionConstructor(NativeDOMException) ? NativeDOMException : createDOMExceptionPolyfill(); + function ReadableStreamPipeTo(source, dest, preventClose, preventAbort, preventCancel, signal) { + const reader = AcquireReadableStreamDefaultReader(source); + const writer = AcquireWritableStreamDefaultWriter(dest); + source._disturbed = true; + let shuttingDown = false; + let currentWrite = promiseResolvedWith(void 0); + return newPromise((resolve, reject) => { + let abortAlgorithm; + if (signal !== void 0) { + abortAlgorithm = () => { + const error = new DOMException$1("Aborted", "AbortError"); + const actions = []; + if (!preventAbort) { + actions.push(() => { + if (dest._state === "writable") { + return WritableStreamAbort(dest, error); + } + return promiseResolvedWith(void 0); + }); + } + if (!preventCancel) { + actions.push(() => { + if (source._state === "readable") { + return ReadableStreamCancel(source, error); + } + return promiseResolvedWith(void 0); + }); + } + shutdownWithAction(() => Promise.all(actions.map((action) => action())), true, error); + }; + if (signal.aborted) { + abortAlgorithm(); + return; + } + signal.addEventListener("abort", abortAlgorithm); + } + function pipeLoop() { + return newPromise((resolveLoop, rejectLoop) => { + function next(done) { + if (done) { + resolveLoop(); + } else { + PerformPromiseThen(pipeStep(), next, rejectLoop); + } + } + next(false); + }); + } + function pipeStep() { + if (shuttingDown) { + return promiseResolvedWith(true); + } + return PerformPromiseThen(writer._readyPromise, () => { + return newPromise((resolveRead, rejectRead) => { + ReadableStreamDefaultReaderRead(reader, { + _chunkSteps: (chunk) => { + currentWrite = PerformPromiseThen(WritableStreamDefaultWriterWrite(writer, chunk), void 0, noop2); + resolveRead(false); + }, + _closeSteps: () => resolveRead(true), + _errorSteps: rejectRead + }); + }); + }); + } + isOrBecomesErrored(source, reader._closedPromise, (storedError) => { + if (!preventAbort) { + shutdownWithAction(() => WritableStreamAbort(dest, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesErrored(dest, writer._closedPromise, (storedError) => { + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, storedError), true, storedError); + } else { + shutdown(true, storedError); + } + }); + isOrBecomesClosed(source, reader._closedPromise, () => { + if (!preventClose) { + shutdownWithAction(() => WritableStreamDefaultWriterCloseWithErrorPropagation(writer)); + } else { + shutdown(); + } + }); + if (WritableStreamCloseQueuedOrInFlight(dest) || dest._state === "closed") { + const destClosed = new TypeError("the destination writable stream closed before all data could be piped to it"); + if (!preventCancel) { + shutdownWithAction(() => ReadableStreamCancel(source, destClosed), true, destClosed); + } else { + shutdown(true, destClosed); + } + } + setPromiseIsHandledToTrue(pipeLoop()); + function waitForWritesToFinish() { + const oldCurrentWrite = currentWrite; + return PerformPromiseThen(currentWrite, () => oldCurrentWrite !== currentWrite ? waitForWritesToFinish() : void 0); + } + function isOrBecomesErrored(stream, promise, action) { + if (stream._state === "errored") { + action(stream._storedError); + } else { + uponRejection(promise, action); + } + } + function isOrBecomesClosed(stream, promise, action) { + if (stream._state === "closed") { + action(); + } else { + uponFulfillment(promise, action); + } + } + function shutdownWithAction(action, originalIsError, originalError) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), doTheRest); + } else { + doTheRest(); + } + function doTheRest() { + uponPromise(action(), () => finalize(originalIsError, originalError), (newError) => finalize(true, newError)); + } + } + function shutdown(isError, error) { + if (shuttingDown) { + return; + } + shuttingDown = true; + if (dest._state === "writable" && !WritableStreamCloseQueuedOrInFlight(dest)) { + uponFulfillment(waitForWritesToFinish(), () => finalize(isError, error)); + } else { + finalize(isError, error); + } + } + function finalize(isError, error) { + WritableStreamDefaultWriterRelease(writer); + ReadableStreamReaderGenericRelease(reader); + if (signal !== void 0) { + signal.removeEventListener("abort", abortAlgorithm); + } + if (isError) { + reject(error); + } else { + resolve(void 0); + } + } + }); + } + class ReadableStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get desiredSize() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("desiredSize"); + } + return ReadableStreamDefaultControllerGetDesiredSize(this); + } + close() { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("close"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits close"); + } + ReadableStreamDefaultControllerClose(this); + } + enqueue(chunk = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("enqueue"); + } + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(this)) { + throw new TypeError("The stream is not in a state that permits enqueue"); + } + return ReadableStreamDefaultControllerEnqueue(this, chunk); + } + error(e2 = void 0) { + if (!IsReadableStreamDefaultController(this)) { + throw defaultControllerBrandCheckException$1("error"); + } + ReadableStreamDefaultControllerError(this, e2); + } + [CancelSteps](reason) { + ResetQueue(this); + const result = this._cancelAlgorithm(reason); + ReadableStreamDefaultControllerClearAlgorithms(this); + return result; + } + [PullSteps](readRequest) { + const stream = this._controlledReadableStream; + if (this._queue.length > 0) { + const chunk = DequeueValue(this); + if (this._closeRequested && this._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(this); + ReadableStreamClose(stream); + } else { + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + readRequest._chunkSteps(chunk); + } else { + ReadableStreamAddReadRequest(stream, readRequest); + ReadableStreamDefaultControllerCallPullIfNeeded(this); + } + } + } + Object.defineProperties(ReadableStreamDefaultController.prototype, { + close: { enumerable: true }, + enqueue: { enumerable: true }, + error: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStreamDefaultController", + configurable: true + }); + } + function IsReadableStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledReadableStream")) { + return false; + } + return x2 instanceof ReadableStreamDefaultController; + } + function ReadableStreamDefaultControllerCallPullIfNeeded(controller) { + const shouldPull = ReadableStreamDefaultControllerShouldCallPull(controller); + if (!shouldPull) { + return; + } + if (controller._pulling) { + controller._pullAgain = true; + return; + } + controller._pulling = true; + const pullPromise = controller._pullAlgorithm(); + uponPromise(pullPromise, () => { + controller._pulling = false; + if (controller._pullAgain) { + controller._pullAgain = false; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + }, (e2) => { + ReadableStreamDefaultControllerError(controller, e2); + }); + } + function ReadableStreamDefaultControllerShouldCallPull(controller) { + const stream = controller._controlledReadableStream; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return false; + } + if (!controller._started) { + return false; + } + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + return true; + } + const desiredSize = ReadableStreamDefaultControllerGetDesiredSize(controller); + if (desiredSize > 0) { + return true; + } + return false; + } + function ReadableStreamDefaultControllerClearAlgorithms(controller) { + controller._pullAlgorithm = void 0; + controller._cancelAlgorithm = void 0; + controller._strategySizeAlgorithm = void 0; + } + function ReadableStreamDefaultControllerClose(controller) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + controller._closeRequested = true; + if (controller._queue.length === 0) { + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamClose(stream); + } + } + function ReadableStreamDefaultControllerEnqueue(controller, chunk) { + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(controller)) { + return; + } + const stream = controller._controlledReadableStream; + if (IsReadableStreamLocked(stream) && ReadableStreamGetNumReadRequests(stream) > 0) { + ReadableStreamFulfillReadRequest(stream, chunk, false); + } else { + let chunkSize; + try { + chunkSize = controller._strategySizeAlgorithm(chunk); + } catch (chunkSizeE) { + ReadableStreamDefaultControllerError(controller, chunkSizeE); + throw chunkSizeE; + } + try { + EnqueueValueWithSize(controller, chunk, chunkSize); + } catch (enqueueE) { + ReadableStreamDefaultControllerError(controller, enqueueE); + throw enqueueE; + } + } + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + } + function ReadableStreamDefaultControllerError(controller, e2) { + const stream = controller._controlledReadableStream; + if (stream._state !== "readable") { + return; + } + ResetQueue(controller); + ReadableStreamDefaultControllerClearAlgorithms(controller); + ReadableStreamError(stream, e2); + } + function ReadableStreamDefaultControllerGetDesiredSize(controller) { + const state = controller._controlledReadableStream._state; + if (state === "errored") { + return null; + } + if (state === "closed") { + return 0; + } + return controller._strategyHWM - controller._queueTotalSize; + } + function ReadableStreamDefaultControllerHasBackpressure(controller) { + if (ReadableStreamDefaultControllerShouldCallPull(controller)) { + return false; + } + return true; + } + function ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) { + const state = controller._controlledReadableStream._state; + if (!controller._closeRequested && state === "readable") { + return true; + } + return false; + } + function SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm) { + controller._controlledReadableStream = stream; + controller._queue = void 0; + controller._queueTotalSize = void 0; + ResetQueue(controller); + controller._started = false; + controller._closeRequested = false; + controller._pullAgain = false; + controller._pulling = false; + controller._strategySizeAlgorithm = sizeAlgorithm; + controller._strategyHWM = highWaterMark; + controller._pullAlgorithm = pullAlgorithm; + controller._cancelAlgorithm = cancelAlgorithm; + stream._readableStreamController = controller; + const startResult = startAlgorithm(); + uponPromise(promiseResolvedWith(startResult), () => { + controller._started = true; + ReadableStreamDefaultControllerCallPullIfNeeded(controller); + }, (r2) => { + ReadableStreamDefaultControllerError(controller, r2); + }); + } + function SetUpReadableStreamDefaultControllerFromUnderlyingSource(stream, underlyingSource, highWaterMark, sizeAlgorithm) { + const controller = Object.create(ReadableStreamDefaultController.prototype); + let startAlgorithm = () => void 0; + let pullAlgorithm = () => promiseResolvedWith(void 0); + let cancelAlgorithm = () => promiseResolvedWith(void 0); + if (underlyingSource.start !== void 0) { + startAlgorithm = () => underlyingSource.start(controller); + } + if (underlyingSource.pull !== void 0) { + pullAlgorithm = () => underlyingSource.pull(controller); + } + if (underlyingSource.cancel !== void 0) { + cancelAlgorithm = (reason) => underlyingSource.cancel(reason); + } + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + } + function defaultControllerBrandCheckException$1(name) { + return new TypeError(`ReadableStreamDefaultController.prototype.${name} can only be used on a ReadableStreamDefaultController`); + } + function ReadableStreamTee(stream, cloneForBranch2) { + if (IsReadableByteStreamController(stream._readableStreamController)) { + return ReadableByteStreamTee(stream); + } + return ReadableStreamDefaultTee(stream); + } + function ReadableStreamDefaultTee(stream, cloneForBranch2) { + const reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgain = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function pullAlgorithm() { + if (reading) { + readAgain = true; + return promiseResolvedWith(void 0); + } + reading = true; + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgain = false; + const chunk1 = chunk; + const chunk2 = chunk; + if (!canceled1) { + ReadableStreamDefaultControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableStreamDefaultControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgain) { + pullAlgorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableStreamDefaultControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableStreamDefaultControllerClose(branch2._readableStreamController); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + } + branch1 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm); + branch2 = CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm); + uponRejection(reader._closedPromise, (r2) => { + ReadableStreamDefaultControllerError(branch1._readableStreamController, r2); + ReadableStreamDefaultControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + return [branch1, branch2]; + } + function ReadableByteStreamTee(stream) { + let reader = AcquireReadableStreamDefaultReader(stream); + let reading = false; + let readAgainForBranch1 = false; + let readAgainForBranch2 = false; + let canceled1 = false; + let canceled2 = false; + let reason1; + let reason2; + let branch1; + let branch2; + let resolveCancelPromise; + const cancelPromise = newPromise((resolve) => { + resolveCancelPromise = resolve; + }); + function forwardReaderError(thisReader) { + uponRejection(thisReader._closedPromise, (r2) => { + if (thisReader !== reader) { + return; + } + ReadableByteStreamControllerError(branch1._readableStreamController, r2); + ReadableByteStreamControllerError(branch2._readableStreamController, r2); + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }); + } + function pullWithDefaultReader() { + if (IsReadableStreamBYOBReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamDefaultReader(stream); + forwardReaderError(reader); + } + const readRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const chunk1 = chunk; + let chunk2 = chunk; + if (!canceled1 && !canceled2) { + try { + chunk2 = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(branch1._readableStreamController, cloneE); + ReadableByteStreamControllerError(branch2._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + } + if (!canceled1) { + ReadableByteStreamControllerEnqueue(branch1._readableStreamController, chunk1); + } + if (!canceled2) { + ReadableByteStreamControllerEnqueue(branch2._readableStreamController, chunk2); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: () => { + reading = false; + if (!canceled1) { + ReadableByteStreamControllerClose(branch1._readableStreamController); + } + if (!canceled2) { + ReadableByteStreamControllerClose(branch2._readableStreamController); + } + if (branch1._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch1._readableStreamController, 0); + } + if (branch2._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(branch2._readableStreamController, 0); + } + if (!canceled1 || !canceled2) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamDefaultReaderRead(reader, readRequest); + } + function pullWithBYOBReader(view, forBranch2) { + if (IsReadableStreamDefaultReader(reader)) { + ReadableStreamReaderGenericRelease(reader); + reader = AcquireReadableStreamBYOBReader(stream); + forwardReaderError(reader); + } + const byobBranch = forBranch2 ? branch2 : branch1; + const otherBranch = forBranch2 ? branch1 : branch2; + const readIntoRequest = { + _chunkSteps: (chunk) => { + queueMicrotask(() => { + readAgainForBranch1 = false; + readAgainForBranch2 = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!otherCanceled) { + let clonedChunk; + try { + clonedChunk = CloneAsUint8Array(chunk); + } catch (cloneE) { + ReadableByteStreamControllerError(byobBranch._readableStreamController, cloneE); + ReadableByteStreamControllerError(otherBranch._readableStreamController, cloneE); + resolveCancelPromise(ReadableStreamCancel(stream, cloneE)); + return; + } + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + ReadableByteStreamControllerEnqueue(otherBranch._readableStreamController, clonedChunk); + } else if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + reading = false; + if (readAgainForBranch1) { + pull1Algorithm(); + } else if (readAgainForBranch2) { + pull2Algorithm(); + } + }); + }, + _closeSteps: (chunk) => { + reading = false; + const byobCanceled = forBranch2 ? canceled2 : canceled1; + const otherCanceled = forBranch2 ? canceled1 : canceled2; + if (!byobCanceled) { + ReadableByteStreamControllerClose(byobBranch._readableStreamController); + } + if (!otherCanceled) { + ReadableByteStreamControllerClose(otherBranch._readableStreamController); + } + if (chunk !== void 0) { + if (!byobCanceled) { + ReadableByteStreamControllerRespondWithNewView(byobBranch._readableStreamController, chunk); + } + if (!otherCanceled && otherBranch._readableStreamController._pendingPullIntos.length > 0) { + ReadableByteStreamControllerRespond(otherBranch._readableStreamController, 0); + } + } + if (!byobCanceled || !otherCanceled) { + resolveCancelPromise(void 0); + } + }, + _errorSteps: () => { + reading = false; + } + }; + ReadableStreamBYOBReaderRead(reader, view, readIntoRequest); + } + function pull1Algorithm() { + if (reading) { + readAgainForBranch1 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch1._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, false); + } + return promiseResolvedWith(void 0); + } + function pull2Algorithm() { + if (reading) { + readAgainForBranch2 = true; + return promiseResolvedWith(void 0); + } + reading = true; + const byobRequest = ReadableByteStreamControllerGetBYOBRequest(branch2._readableStreamController); + if (byobRequest === null) { + pullWithDefaultReader(); + } else { + pullWithBYOBReader(byobRequest._view, true); + } + return promiseResolvedWith(void 0); + } + function cancel1Algorithm(reason) { + canceled1 = true; + reason1 = reason; + if (canceled2) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function cancel2Algorithm(reason) { + canceled2 = true; + reason2 = reason; + if (canceled1) { + const compositeReason = CreateArrayFromList([reason1, reason2]); + const cancelResult = ReadableStreamCancel(stream, compositeReason); + resolveCancelPromise(cancelResult); + } + return cancelPromise; + } + function startAlgorithm() { + return; + } + branch1 = CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm); + branch2 = CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm); + forwardReaderError(reader); + return [branch1, branch2]; + } + function convertUnderlyingDefaultOrByteSource(source, context) { + assertDictionary(source, context); + const original = source; + const autoAllocateChunkSize = original === null || original === void 0 ? void 0 : original.autoAllocateChunkSize; + const cancel = original === null || original === void 0 ? void 0 : original.cancel; + const pull = original === null || original === void 0 ? void 0 : original.pull; + const start = original === null || original === void 0 ? void 0 : original.start; + const type = original === null || original === void 0 ? void 0 : original.type; + return { + autoAllocateChunkSize: autoAllocateChunkSize === void 0 ? void 0 : convertUnsignedLongLongWithEnforceRange(autoAllocateChunkSize, `${context} has member 'autoAllocateChunkSize' that`), + cancel: cancel === void 0 ? void 0 : convertUnderlyingSourceCancelCallback(cancel, original, `${context} has member 'cancel' that`), + pull: pull === void 0 ? void 0 : convertUnderlyingSourcePullCallback(pull, original, `${context} has member 'pull' that`), + start: start === void 0 ? void 0 : convertUnderlyingSourceStartCallback(start, original, `${context} has member 'start' that`), + type: type === void 0 ? void 0 : convertReadableStreamType(type, `${context} has member 'type' that`) + }; + } + function convertUnderlyingSourceCancelCallback(fn, original, context) { + assertFunction(fn, context); + return (reason) => promiseCall(fn, original, [reason]); + } + function convertUnderlyingSourcePullCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertUnderlyingSourceStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertReadableStreamType(type, context) { + type = `${type}`; + if (type !== "bytes") { + throw new TypeError(`${context} '${type}' is not a valid enumeration value for ReadableStreamType`); + } + return type; + } + function convertReaderOptions(options, context) { + assertDictionary(options, context); + const mode = options === null || options === void 0 ? void 0 : options.mode; + return { + mode: mode === void 0 ? void 0 : convertReadableStreamReaderMode(mode, `${context} has member 'mode' that`) + }; + } + function convertReadableStreamReaderMode(mode, context) { + mode = `${mode}`; + if (mode !== "byob") { + throw new TypeError(`${context} '${mode}' is not a valid enumeration value for ReadableStreamReaderMode`); + } + return mode; + } + function convertIteratorOptions(options, context) { + assertDictionary(options, context); + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + return { preventCancel: Boolean(preventCancel) }; + } + function convertPipeOptions(options, context) { + assertDictionary(options, context); + const preventAbort = options === null || options === void 0 ? void 0 : options.preventAbort; + const preventCancel = options === null || options === void 0 ? void 0 : options.preventCancel; + const preventClose = options === null || options === void 0 ? void 0 : options.preventClose; + const signal = options === null || options === void 0 ? void 0 : options.signal; + if (signal !== void 0) { + assertAbortSignal(signal, `${context} has member 'signal' that`); + } + return { + preventAbort: Boolean(preventAbort), + preventCancel: Boolean(preventCancel), + preventClose: Boolean(preventClose), + signal + }; + } + function assertAbortSignal(signal, context) { + if (!isAbortSignal2(signal)) { + throw new TypeError(`${context} is not an AbortSignal.`); + } + } + function convertReadableWritablePair(pair, context) { + assertDictionary(pair, context); + const readable = pair === null || pair === void 0 ? void 0 : pair.readable; + assertRequiredField(readable, "readable", "ReadableWritablePair"); + assertReadableStream(readable, `${context} has member 'readable' that`); + const writable = pair === null || pair === void 0 ? void 0 : pair.writable; + assertRequiredField(writable, "writable", "ReadableWritablePair"); + assertWritableStream(writable, `${context} has member 'writable' that`); + return { readable, writable }; + } + class ReadableStream2 { + constructor(rawUnderlyingSource = {}, rawStrategy = {}) { + if (rawUnderlyingSource === void 0) { + rawUnderlyingSource = null; + } else { + assertObject(rawUnderlyingSource, "First parameter"); + } + const strategy = convertQueuingStrategy(rawStrategy, "Second parameter"); + const underlyingSource = convertUnderlyingDefaultOrByteSource(rawUnderlyingSource, "First parameter"); + InitializeReadableStream(this); + if (underlyingSource.type === "bytes") { + if (strategy.size !== void 0) { + throw new RangeError("The strategy for a byte stream cannot have a size function"); + } + const highWaterMark = ExtractHighWaterMark(strategy, 0); + SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, highWaterMark); + } else { + const sizeAlgorithm = ExtractSizeAlgorithm(strategy); + const highWaterMark = ExtractHighWaterMark(strategy, 1); + SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, highWaterMark, sizeAlgorithm); + } + } + get locked() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("locked"); + } + return IsReadableStreamLocked(this); + } + cancel(reason = void 0) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("cancel")); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("Cannot cancel a stream that already has a reader")); + } + return ReadableStreamCancel(this, reason); + } + getReader(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("getReader"); + } + const options = convertReaderOptions(rawOptions, "First parameter"); + if (options.mode === void 0) { + return AcquireReadableStreamDefaultReader(this); + } + return AcquireReadableStreamBYOBReader(this); + } + pipeThrough(rawTransform, rawOptions = {}) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("pipeThrough"); + } + assertRequiredArgument(rawTransform, 1, "pipeThrough"); + const transform = convertReadableWritablePair(rawTransform, "First parameter"); + const options = convertPipeOptions(rawOptions, "Second parameter"); + if (IsReadableStreamLocked(this)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked ReadableStream"); + } + if (IsWritableStreamLocked(transform.writable)) { + throw new TypeError("ReadableStream.prototype.pipeThrough cannot be used on a locked WritableStream"); + } + const promise = ReadableStreamPipeTo(this, transform.writable, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + setPromiseIsHandledToTrue(promise); + return transform.readable; + } + pipeTo(destination, rawOptions = {}) { + if (!IsReadableStream(this)) { + return promiseRejectedWith(streamBrandCheckException$1("pipeTo")); + } + if (destination === void 0) { + return promiseRejectedWith(`Parameter 1 is required in 'pipeTo'.`); + } + if (!IsWritableStream(destination)) { + return promiseRejectedWith(new TypeError(`ReadableStream.prototype.pipeTo's first argument must be a WritableStream`)); + } + let options; + try { + options = convertPipeOptions(rawOptions, "Second parameter"); + } catch (e2) { + return promiseRejectedWith(e2); + } + if (IsReadableStreamLocked(this)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream")); + } + if (IsWritableStreamLocked(destination)) { + return promiseRejectedWith(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream")); + } + return ReadableStreamPipeTo(this, destination, options.preventClose, options.preventAbort, options.preventCancel, options.signal); + } + tee() { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("tee"); + } + const branches = ReadableStreamTee(this); + return CreateArrayFromList(branches); + } + values(rawOptions = void 0) { + if (!IsReadableStream(this)) { + throw streamBrandCheckException$1("values"); + } + const options = convertIteratorOptions(rawOptions, "First parameter"); + return AcquireReadableStreamAsyncIterator(this, options.preventCancel); + } + } + Object.defineProperties(ReadableStream2.prototype, { + cancel: { enumerable: true }, + getReader: { enumerable: true }, + pipeThrough: { enumerable: true }, + pipeTo: { enumerable: true }, + tee: { enumerable: true }, + values: { enumerable: true }, + locked: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.toStringTag, { + value: "ReadableStream", + configurable: true + }); + } + if (typeof SymbolPolyfill.asyncIterator === "symbol") { + Object.defineProperty(ReadableStream2.prototype, SymbolPolyfill.asyncIterator, { + value: ReadableStream2.prototype.values, + writable: true, + configurable: true + }); + } + function CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark = 1, sizeAlgorithm = () => 1) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableStreamDefaultController.prototype); + SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm); + return stream; + } + function CreateReadableByteStream(startAlgorithm, pullAlgorithm, cancelAlgorithm) { + const stream = Object.create(ReadableStream2.prototype); + InitializeReadableStream(stream); + const controller = Object.create(ReadableByteStreamController.prototype); + SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, void 0); + return stream; + } + function InitializeReadableStream(stream) { + stream._state = "readable"; + stream._reader = void 0; + stream._storedError = void 0; + stream._disturbed = false; + } + function IsReadableStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_readableStreamController")) { + return false; + } + return x2 instanceof ReadableStream2; + } + function IsReadableStreamLocked(stream) { + if (stream._reader === void 0) { + return false; + } + return true; + } + function ReadableStreamCancel(stream, reason) { + stream._disturbed = true; + if (stream._state === "closed") { + return promiseResolvedWith(void 0); + } + if (stream._state === "errored") { + return promiseRejectedWith(stream._storedError); + } + ReadableStreamClose(stream); + const reader = stream._reader; + if (reader !== void 0 && IsReadableStreamBYOBReader(reader)) { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._closeSteps(void 0); + }); + reader._readIntoRequests = new SimpleQueue(); + } + const sourceCancelPromise = stream._readableStreamController[CancelSteps](reason); + return transformPromiseWith(sourceCancelPromise, noop2); + } + function ReadableStreamClose(stream) { + stream._state = "closed"; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseResolve(reader); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._closeSteps(); + }); + reader._readRequests = new SimpleQueue(); + } + } + function ReadableStreamError(stream, e2) { + stream._state = "errored"; + stream._storedError = e2; + const reader = stream._reader; + if (reader === void 0) { + return; + } + defaultReaderClosedPromiseReject(reader, e2); + if (IsReadableStreamDefaultReader(reader)) { + reader._readRequests.forEach((readRequest) => { + readRequest._errorSteps(e2); + }); + reader._readRequests = new SimpleQueue(); + } else { + reader._readIntoRequests.forEach((readIntoRequest) => { + readIntoRequest._errorSteps(e2); + }); + reader._readIntoRequests = new SimpleQueue(); + } + } + function streamBrandCheckException$1(name) { + return new TypeError(`ReadableStream.prototype.${name} can only be used on a ReadableStream`); + } + function convertQueuingStrategyInit(init, context) { + assertDictionary(init, context); + const highWaterMark = init === null || init === void 0 ? void 0 : init.highWaterMark; + assertRequiredField(highWaterMark, "highWaterMark", "QueuingStrategyInit"); + return { + highWaterMark: convertUnrestrictedDouble(highWaterMark) + }; + } + const byteLengthSizeFunction = (chunk) => { + return chunk.byteLength; + }; + try { + Object.defineProperty(byteLengthSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class ByteLengthQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "ByteLengthQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._byteLengthQueuingStrategyHighWaterMark = options.highWaterMark; + } + get highWaterMark() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("highWaterMark"); + } + return this._byteLengthQueuingStrategyHighWaterMark; + } + get size() { + if (!IsByteLengthQueuingStrategy(this)) { + throw byteLengthBrandCheckException("size"); + } + return byteLengthSizeFunction; + } + } + Object.defineProperties(ByteLengthQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(ByteLengthQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "ByteLengthQueuingStrategy", + configurable: true + }); + } + function byteLengthBrandCheckException(name) { + return new TypeError(`ByteLengthQueuingStrategy.prototype.${name} can only be used on a ByteLengthQueuingStrategy`); + } + function IsByteLengthQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_byteLengthQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof ByteLengthQueuingStrategy; + } + const countSizeFunction = () => { + return 1; + }; + try { + Object.defineProperty(countSizeFunction, "name", { + value: "size", + configurable: true + }); + } catch (_a4) { + } + class CountQueuingStrategy { + constructor(options) { + assertRequiredArgument(options, 1, "CountQueuingStrategy"); + options = convertQueuingStrategyInit(options, "First parameter"); + this._countQueuingStrategyHighWaterMark = options.highWaterMark; + } + get highWaterMark() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("highWaterMark"); + } + return this._countQueuingStrategyHighWaterMark; + } + get size() { + if (!IsCountQueuingStrategy(this)) { + throw countBrandCheckException("size"); + } + return countSizeFunction; + } + } + Object.defineProperties(CountQueuingStrategy.prototype, { + highWaterMark: { enumerable: true }, + size: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(CountQueuingStrategy.prototype, SymbolPolyfill.toStringTag, { + value: "CountQueuingStrategy", + configurable: true + }); + } + function countBrandCheckException(name) { + return new TypeError(`CountQueuingStrategy.prototype.${name} can only be used on a CountQueuingStrategy`); + } + function IsCountQueuingStrategy(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_countQueuingStrategyHighWaterMark")) { + return false; + } + return x2 instanceof CountQueuingStrategy; + } + function convertTransformer(original, context) { + assertDictionary(original, context); + const flush = original === null || original === void 0 ? void 0 : original.flush; + const readableType = original === null || original === void 0 ? void 0 : original.readableType; + const start = original === null || original === void 0 ? void 0 : original.start; + const transform = original === null || original === void 0 ? void 0 : original.transform; + const writableType = original === null || original === void 0 ? void 0 : original.writableType; + return { + flush: flush === void 0 ? void 0 : convertTransformerFlushCallback(flush, original, `${context} has member 'flush' that`), + readableType, + start: start === void 0 ? void 0 : convertTransformerStartCallback(start, original, `${context} has member 'start' that`), + transform: transform === void 0 ? void 0 : convertTransformerTransformCallback(transform, original, `${context} has member 'transform' that`), + writableType + }; + } + function convertTransformerFlushCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => promiseCall(fn, original, [controller]); + } + function convertTransformerStartCallback(fn, original, context) { + assertFunction(fn, context); + return (controller) => reflectCall(fn, original, [controller]); + } + function convertTransformerTransformCallback(fn, original, context) { + assertFunction(fn, context); + return (chunk, controller) => promiseCall(fn, original, [chunk, controller]); + } + class TransformStream { + constructor(rawTransformer = {}, rawWritableStrategy = {}, rawReadableStrategy = {}) { + if (rawTransformer === void 0) { + rawTransformer = null; + } + const writableStrategy = convertQueuingStrategy(rawWritableStrategy, "Second parameter"); + const readableStrategy = convertQueuingStrategy(rawReadableStrategy, "Third parameter"); + const transformer = convertTransformer(rawTransformer, "First parameter"); + if (transformer.readableType !== void 0) { + throw new RangeError("Invalid readableType specified"); + } + if (transformer.writableType !== void 0) { + throw new RangeError("Invalid writableType specified"); + } + const readableHighWaterMark = ExtractHighWaterMark(readableStrategy, 0); + const readableSizeAlgorithm = ExtractSizeAlgorithm(readableStrategy); + const writableHighWaterMark = ExtractHighWaterMark(writableStrategy, 1); + const writableSizeAlgorithm = ExtractSizeAlgorithm(writableStrategy); + let startPromise_resolve; + const startPromise = newPromise((resolve) => { + startPromise_resolve = resolve; + }); + InitializeTransformStream(this, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + SetUpTransformStreamDefaultControllerFromTransformer(this, transformer); + if (transformer.start !== void 0) { + startPromise_resolve(transformer.start(this._transformStreamController)); + } else { + startPromise_resolve(void 0); + } + } + get readable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("readable"); + } + return this._readable; + } + get writable() { + if (!IsTransformStream(this)) { + throw streamBrandCheckException("writable"); + } + return this._writable; + } + } + Object.defineProperties(TransformStream.prototype, { + readable: { enumerable: true }, + writable: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStream.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStream", + configurable: true + }); + } + function InitializeTransformStream(stream, startPromise, writableHighWaterMark, writableSizeAlgorithm, readableHighWaterMark, readableSizeAlgorithm) { + function startAlgorithm() { + return startPromise; + } + function writeAlgorithm(chunk) { + return TransformStreamDefaultSinkWriteAlgorithm(stream, chunk); + } + function abortAlgorithm(reason) { + return TransformStreamDefaultSinkAbortAlgorithm(stream, reason); + } + function closeAlgorithm() { + return TransformStreamDefaultSinkCloseAlgorithm(stream); + } + stream._writable = CreateWritableStream(startAlgorithm, writeAlgorithm, closeAlgorithm, abortAlgorithm, writableHighWaterMark, writableSizeAlgorithm); + function pullAlgorithm() { + return TransformStreamDefaultSourcePullAlgorithm(stream); + } + function cancelAlgorithm(reason) { + TransformStreamErrorWritableAndUnblockWrite(stream, reason); + return promiseResolvedWith(void 0); + } + stream._readable = CreateReadableStream(startAlgorithm, pullAlgorithm, cancelAlgorithm, readableHighWaterMark, readableSizeAlgorithm); + stream._backpressure = void 0; + stream._backpressureChangePromise = void 0; + stream._backpressureChangePromise_resolve = void 0; + TransformStreamSetBackpressure(stream, true); + stream._transformStreamController = void 0; + } + function IsTransformStream(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_transformStreamController")) { + return false; + } + return x2 instanceof TransformStream; + } + function TransformStreamError(stream, e2) { + ReadableStreamDefaultControllerError(stream._readable._readableStreamController, e2); + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + } + function TransformStreamErrorWritableAndUnblockWrite(stream, e2) { + TransformStreamDefaultControllerClearAlgorithms(stream._transformStreamController); + WritableStreamDefaultControllerErrorIfNeeded(stream._writable._writableStreamController, e2); + if (stream._backpressure) { + TransformStreamSetBackpressure(stream, false); + } + } + function TransformStreamSetBackpressure(stream, backpressure) { + if (stream._backpressureChangePromise !== void 0) { + stream._backpressureChangePromise_resolve(); + } + stream._backpressureChangePromise = newPromise((resolve) => { + stream._backpressureChangePromise_resolve = resolve; + }); + stream._backpressure = backpressure; + } + class TransformStreamDefaultController { + constructor() { + throw new TypeError("Illegal constructor"); + } + get desiredSize() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("desiredSize"); + } + const readableController = this._controlledTransformStream._readable._readableStreamController; + return ReadableStreamDefaultControllerGetDesiredSize(readableController); + } + enqueue(chunk = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("enqueue"); + } + TransformStreamDefaultControllerEnqueue(this, chunk); + } + error(reason = void 0) { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("error"); + } + TransformStreamDefaultControllerError(this, reason); + } + terminate() { + if (!IsTransformStreamDefaultController(this)) { + throw defaultControllerBrandCheckException("terminate"); + } + TransformStreamDefaultControllerTerminate(this); + } + } + Object.defineProperties(TransformStreamDefaultController.prototype, { + enqueue: { enumerable: true }, + error: { enumerable: true }, + terminate: { enumerable: true }, + desiredSize: { enumerable: true } + }); + if (typeof SymbolPolyfill.toStringTag === "symbol") { + Object.defineProperty(TransformStreamDefaultController.prototype, SymbolPolyfill.toStringTag, { + value: "TransformStreamDefaultController", + configurable: true + }); + } + function IsTransformStreamDefaultController(x2) { + if (!typeIsObject(x2)) { + return false; + } + if (!Object.prototype.hasOwnProperty.call(x2, "_controlledTransformStream")) { + return false; + } + return x2 instanceof TransformStreamDefaultController; + } + function SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm) { + controller._controlledTransformStream = stream; + stream._transformStreamController = controller; + controller._transformAlgorithm = transformAlgorithm; + controller._flushAlgorithm = flushAlgorithm; + } + function SetUpTransformStreamDefaultControllerFromTransformer(stream, transformer) { + const controller = Object.create(TransformStreamDefaultController.prototype); + let transformAlgorithm = (chunk) => { + try { + TransformStreamDefaultControllerEnqueue(controller, chunk); + return promiseResolvedWith(void 0); + } catch (transformResultE) { + return promiseRejectedWith(transformResultE); + } + }; + let flushAlgorithm = () => promiseResolvedWith(void 0); + if (transformer.transform !== void 0) { + transformAlgorithm = (chunk) => transformer.transform(chunk, controller); + } + if (transformer.flush !== void 0) { + flushAlgorithm = () => transformer.flush(controller); + } + SetUpTransformStreamDefaultController(stream, controller, transformAlgorithm, flushAlgorithm); + } + function TransformStreamDefaultControllerClearAlgorithms(controller) { + controller._transformAlgorithm = void 0; + controller._flushAlgorithm = void 0; + } + function TransformStreamDefaultControllerEnqueue(controller, chunk) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + if (!ReadableStreamDefaultControllerCanCloseOrEnqueue(readableController)) { + throw new TypeError("Readable side is not in a state that permits enqueue"); + } + try { + ReadableStreamDefaultControllerEnqueue(readableController, chunk); + } catch (e2) { + TransformStreamErrorWritableAndUnblockWrite(stream, e2); + throw stream._readable._storedError; + } + const backpressure = ReadableStreamDefaultControllerHasBackpressure(readableController); + if (backpressure !== stream._backpressure) { + TransformStreamSetBackpressure(stream, true); + } + } + function TransformStreamDefaultControllerError(controller, e2) { + TransformStreamError(controller._controlledTransformStream, e2); + } + function TransformStreamDefaultControllerPerformTransform(controller, chunk) { + const transformPromise = controller._transformAlgorithm(chunk); + return transformPromiseWith(transformPromise, void 0, (r2) => { + TransformStreamError(controller._controlledTransformStream, r2); + throw r2; + }); + } + function TransformStreamDefaultControllerTerminate(controller) { + const stream = controller._controlledTransformStream; + const readableController = stream._readable._readableStreamController; + ReadableStreamDefaultControllerClose(readableController); + const error = new TypeError("TransformStream terminated"); + TransformStreamErrorWritableAndUnblockWrite(stream, error); + } + function TransformStreamDefaultSinkWriteAlgorithm(stream, chunk) { + const controller = stream._transformStreamController; + if (stream._backpressure) { + const backpressureChangePromise = stream._backpressureChangePromise; + return transformPromiseWith(backpressureChangePromise, () => { + const writable = stream._writable; + const state = writable._state; + if (state === "erroring") { + throw writable._storedError; + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + }); + } + return TransformStreamDefaultControllerPerformTransform(controller, chunk); + } + function TransformStreamDefaultSinkAbortAlgorithm(stream, reason) { + TransformStreamError(stream, reason); + return promiseResolvedWith(void 0); + } + function TransformStreamDefaultSinkCloseAlgorithm(stream) { + const readable = stream._readable; + const controller = stream._transformStreamController; + const flushPromise = controller._flushAlgorithm(); + TransformStreamDefaultControllerClearAlgorithms(controller); + return transformPromiseWith(flushPromise, () => { + if (readable._state === "errored") { + throw readable._storedError; + } + ReadableStreamDefaultControllerClose(readable._readableStreamController); + }, (r2) => { + TransformStreamError(stream, r2); + throw readable._storedError; + }); + } + function TransformStreamDefaultSourcePullAlgorithm(stream) { + TransformStreamSetBackpressure(stream, false); + return stream._backpressureChangePromise; + } + function defaultControllerBrandCheckException(name) { + return new TypeError(`TransformStreamDefaultController.prototype.${name} can only be used on a TransformStreamDefaultController`); + } + function streamBrandCheckException(name) { + return new TypeError(`TransformStream.prototype.${name} can only be used on a TransformStream`); + } + exports2.ByteLengthQueuingStrategy = ByteLengthQueuingStrategy; + exports2.CountQueuingStrategy = CountQueuingStrategy; + exports2.ReadableByteStreamController = ReadableByteStreamController; + exports2.ReadableStream = ReadableStream2; + exports2.ReadableStreamBYOBReader = ReadableStreamBYOBReader; + exports2.ReadableStreamBYOBRequest = ReadableStreamBYOBRequest; + exports2.ReadableStreamDefaultController = ReadableStreamDefaultController; + exports2.ReadableStreamDefaultReader = ReadableStreamDefaultReader; + exports2.TransformStream = TransformStream; + exports2.TransformStreamDefaultController = TransformStreamDefaultController; + exports2.WritableStream = WritableStream; + exports2.WritableStreamDefaultController = WritableStreamDefaultController; + exports2.WritableStreamDefaultWriter = WritableStreamDefaultWriter; + Object.defineProperty(exports2, "__esModule", { value: true }); + }); + } +}); + +// node_modules/fetch-blob/streams.cjs +var require_streams = __commonJS({ + "node_modules/fetch-blob/streams.cjs"() { + var POOL_SIZE2 = 65536; + if (!globalThis.ReadableStream) { + try { + const process2 = require("node:process"); + const { emitWarning } = process2; + try { + process2.emitWarning = () => { + }; + Object.assign(globalThis, require("node:stream/web")); + process2.emitWarning = emitWarning; + } catch (error) { + process2.emitWarning = emitWarning; + throw error; + } + } catch (error) { + Object.assign(globalThis, require_ponyfill_es2018()); + } + } + try { + const { Blob: Blob2 } = require("buffer"); + if (Blob2 && !Blob2.prototype.stream) { + Blob2.prototype.stream = function name(params) { + let position = 0; + const blob = this; + return new ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = blob.slice(position, Math.min(blob.size, position + POOL_SIZE2)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + ctrl.enqueue(new Uint8Array(buffer)); + if (position === blob.size) { + ctrl.close(); + } + } + }); + }; + } + } catch (error) { + } + } +}); + +// node_modules/fetch-blob/index.js +async function* toIterator(parts, clone2 = true) { + for (const part of parts) { + if ("stream" in part) { + yield* part.stream(); + } else if (ArrayBuffer.isView(part)) { + if (clone2) { + let position = part.byteOffset; + const end = part.byteOffset + part.byteLength; + while (position !== end) { + const size = Math.min(end - position, POOL_SIZE); + const chunk = part.buffer.slice(position, position + size); + position += chunk.byteLength; + yield new Uint8Array(chunk); + } + } else { + yield part; + } + } else { + let position = 0, b = part; + while (position !== b.size) { + const chunk = b.slice(position, Math.min(b.size, position + POOL_SIZE)); + const buffer = await chunk.arrayBuffer(); + position += buffer.byteLength; + yield new Uint8Array(buffer); + } + } + } +} +var import_streams, POOL_SIZE, _parts, _type, _size, _endings, _a, _Blob, Blob, fetch_blob_default; +var init_fetch_blob = __esm({ + "node_modules/fetch-blob/index.js"() { + import_streams = __toESM(require_streams(), 1); + POOL_SIZE = 65536; + _Blob = (_a = class { + constructor(blobParts = [], options = {}) { + __privateAdd(this, _parts, []); + __privateAdd(this, _type, ""); + __privateAdd(this, _size, 0); + __privateAdd(this, _endings, "transparent"); + if (typeof blobParts !== "object" || blobParts === null) { + throw new TypeError("Failed to construct 'Blob': The provided value cannot be converted to a sequence."); + } + if (typeof blobParts[Symbol.iterator] !== "function") { + throw new TypeError("Failed to construct 'Blob': The object must have a callable @@iterator property."); + } + if (typeof options !== "object" && typeof options !== "function") { + throw new TypeError("Failed to construct 'Blob': parameter 2 cannot convert to dictionary."); + } + if (options === null) + options = {}; + const encoder = new TextEncoder(); + for (const element of blobParts) { + let part; + if (ArrayBuffer.isView(element)) { + part = new Uint8Array(element.buffer.slice(element.byteOffset, element.byteOffset + element.byteLength)); + } else if (element instanceof ArrayBuffer) { + part = new Uint8Array(element.slice(0)); + } else if (element instanceof _a) { + part = element; + } else { + part = encoder.encode(`${element}`); + } + __privateSet(this, _size, __privateGet(this, _size) + (ArrayBuffer.isView(part) ? part.byteLength : part.size)); + __privateGet(this, _parts).push(part); + } + __privateSet(this, _endings, `${options.endings === void 0 ? "transparent" : options.endings}`); + const type = options.type === void 0 ? "" : String(options.type); + __privateSet(this, _type, /^[\x20-\x7E]*$/.test(type) ? type : ""); + } + get size() { + return __privateGet(this, _size); + } + get type() { + return __privateGet(this, _type); + } + async text() { + const decoder = new TextDecoder(); + let str = ""; + for await (const part of toIterator(__privateGet(this, _parts), false)) { + str += decoder.decode(part, { stream: true }); + } + str += decoder.decode(); + return str; + } + async arrayBuffer() { + const data = new Uint8Array(this.size); + let offset = 0; + for await (const chunk of toIterator(__privateGet(this, _parts), false)) { + data.set(chunk, offset); + offset += chunk.length; + } + return data.buffer; + } + stream() { + const it = toIterator(__privateGet(this, _parts), true); + return new globalThis.ReadableStream({ + type: "bytes", + async pull(ctrl) { + const chunk = await it.next(); + chunk.done ? ctrl.close() : ctrl.enqueue(chunk.value); + }, + async cancel() { + await it.return(); + } + }); + } + slice(start = 0, end = this.size, type = "") { + const { size } = this; + let relativeStart = start < 0 ? Math.max(size + start, 0) : Math.min(start, size); + let relativeEnd = end < 0 ? Math.max(size + end, 0) : Math.min(end, size); + const span = Math.max(relativeEnd - relativeStart, 0); + const parts = __privateGet(this, _parts); + const blobParts = []; + let added = 0; + for (const part of parts) { + if (added >= span) { + break; + } + const size2 = ArrayBuffer.isView(part) ? part.byteLength : part.size; + if (relativeStart && size2 <= relativeStart) { + relativeStart -= size2; + relativeEnd -= size2; + } else { + let chunk; + if (ArrayBuffer.isView(part)) { + chunk = part.subarray(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.byteLength; + } else { + chunk = part.slice(relativeStart, Math.min(size2, relativeEnd)); + added += chunk.size; + } + relativeEnd -= size2; + blobParts.push(chunk); + relativeStart = 0; + } + } + const blob = new _a([], { type: String(type).toLowerCase() }); + __privateSet(blob, _size, span); + __privateSet(blob, _parts, blobParts); + return blob; + } + get [Symbol.toStringTag]() { + return "Blob"; + } + static [Symbol.hasInstance](object) { + return object && typeof object === "object" && typeof object.constructor === "function" && (typeof object.stream === "function" || typeof object.arrayBuffer === "function") && /^(Blob|File)$/.test(object[Symbol.toStringTag]); + } + }, _parts = new WeakMap(), _type = new WeakMap(), _size = new WeakMap(), _endings = new WeakMap(), _a); + Object.defineProperties(_Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } + }); + Blob = _Blob; + fetch_blob_default = Blob; + } +}); + +// node_modules/fetch-blob/file.js +var _lastModified, _name, _a2, _File, File, file_default; +var init_file = __esm({ + "node_modules/fetch-blob/file.js"() { + init_fetch_blob(); + _File = (_a2 = class extends fetch_blob_default { + constructor(fileBits, fileName, options = {}) { + if (arguments.length < 2) { + throw new TypeError(`Failed to construct 'File': 2 arguments required, but only ${arguments.length} present.`); + } + super(fileBits, options); + __privateAdd(this, _lastModified, 0); + __privateAdd(this, _name, ""); + if (options === null) + options = {}; + const lastModified = options.lastModified === void 0 ? Date.now() : Number(options.lastModified); + if (!Number.isNaN(lastModified)) { + __privateSet(this, _lastModified, lastModified); + } + __privateSet(this, _name, String(fileName)); + } + get name() { + return __privateGet(this, _name); + } + get lastModified() { + return __privateGet(this, _lastModified); + } + get [Symbol.toStringTag]() { + return "File"; + } + static [Symbol.hasInstance](object) { + return !!object && object instanceof fetch_blob_default && /^(File)$/.test(object[Symbol.toStringTag]); + } + }, _lastModified = new WeakMap(), _name = new WeakMap(), _a2); + File = _File; + file_default = File; + } +}); + +// node_modules/formdata-polyfill/esm.min.js +function formDataToBlob(F2, B = fetch_blob_default) { + var b = `${r()}${r()}`.replace(/\./g, "").slice(-28).padStart(32, "-"), c = [], p = `--${b}\r +Content-Disposition: form-data; name="`; + F2.forEach((v, n) => typeof v == "string" ? c.push(p + e(n) + `"\r +\r +${v.replace(/\r(?!\n)|(? (a += "", /^(Blob|File)$/.test(b && b[t]) ? [(c = c !== void 0 ? c + "" : b[t] == "File" ? b.name : "blob", a), b.name !== c || b[t] == "blob" ? new file_default([b], c, b) : b] : [a, b + ""]); + e = (c, f3) => (f3 ? c : c.replace(/\r?\n|\r/g, "\r\n")).replace(/\n/g, "%0A").replace(/\r/g, "%0D").replace(/"/g, "%22"); + x = (n, a, e2) => { + if (a.length < e2) { + throw new TypeError(`Failed to execute '${n}' on 'FormData': ${e2} arguments required, but only ${a.length} present.`); + } + }; + FormData = (_a3 = class { + constructor(...a) { + __privateAdd(this, _d, []); + if (a.length) + throw new TypeError(`Failed to construct 'FormData': parameter 1 is not of type 'HTMLFormElement'.`); + } + get [t]() { + return "FormData"; + } + [i]() { + return this.entries(); + } + static [h](o) { + return o && typeof o === "object" && o[t] === "FormData" && !m.some((m2) => typeof o[m2] != "function"); + } + append(...a) { + x("append", arguments, 2); + __privateGet(this, _d).push(f(...a)); + } + delete(a) { + x("delete", arguments, 1); + a += ""; + __privateSet(this, _d, __privateGet(this, _d).filter(([b]) => b !== a)); + } + get(a) { + x("get", arguments, 1); + a += ""; + for (var b = __privateGet(this, _d), l = b.length, c = 0; c < l; c++) + if (b[c][0] === a) + return b[c][1]; + return null; + } + getAll(a, b) { + x("getAll", arguments, 1); + b = []; + a += ""; + __privateGet(this, _d).forEach((c) => c[0] === a && b.push(c[1])); + return b; + } + has(a) { + x("has", arguments, 1); + a += ""; + return __privateGet(this, _d).some((b) => b[0] === a); + } + forEach(a, b) { + x("forEach", arguments, 1); + for (var [c, d] of this) + a.call(b, d, c, this); + } + set(...a) { + x("set", arguments, 2); + var b = [], c = true; + a = f(...a); + __privateGet(this, _d).forEach((d) => { + d[0] === a[0] ? c && (c = !b.push(a)) : b.push(d); + }); + c && b.push(a); + __privateSet(this, _d, b); + } + *entries() { + yield* __privateGet(this, _d); + } + *keys() { + for (var [a] of this) + yield a; + } + *values() { + for (var [, a] of this) + yield a; + } + }, _d = new WeakMap(), _a3); + } +}); + +// node_modules/node-domexception/index.js +var require_node_domexception = __commonJS({ + "node_modules/node-domexception/index.js"(exports, module2) { + if (!globalThis.DOMException) { + try { + const { MessageChannel } = require("worker_threads"), port = new MessageChannel().port1, ab = new ArrayBuffer(); + port.postMessage(ab, [ab, ab]); + } catch (err) { + err.constructor.name === "DOMException" && (globalThis.DOMException = err.constructor); + } + } + module2.exports = globalThis.DOMException; + } +}); + +// node_modules/fetch-blob/from.js +var import_node_fs, import_node_path, import_node_domexception, stat, _path, _start, _BlobDataItem, BlobDataItem; +var init_from = __esm({ + "node_modules/fetch-blob/from.js"() { + import_node_fs = require("node:fs"); + import_node_path = require("node:path"); + import_node_domexception = __toESM(require_node_domexception(), 1); + init_file(); + init_fetch_blob(); + ({ stat } = import_node_fs.promises); + _BlobDataItem = class { + constructor(options) { + __privateAdd(this, _path, void 0); + __privateAdd(this, _start, void 0); + __privateSet(this, _path, options.path); + __privateSet(this, _start, options.start); + this.size = options.size; + this.lastModified = options.lastModified; + } + slice(start, end) { + return new _BlobDataItem({ + path: __privateGet(this, _path), + lastModified: this.lastModified, + size: end - start, + start: __privateGet(this, _start) + start + }); + } + async *stream() { + const { mtimeMs } = await stat(__privateGet(this, _path)); + if (mtimeMs > this.lastModified) { + throw new import_node_domexception.default("The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", "NotReadableError"); + } + yield* (0, import_node_fs.createReadStream)(__privateGet(this, _path), { + start: __privateGet(this, _start), + end: __privateGet(this, _start) + this.size - 1 + }); + } + get [Symbol.toStringTag]() { + return "Blob"; + } + }; + BlobDataItem = _BlobDataItem; + _path = new WeakMap(); + _start = new WeakMap(); + } +}); + +// node_modules/node-fetch/src/utils/multipart-parser.js +var multipart_parser_exports = {}; +__export(multipart_parser_exports, { + toFormData: () => toFormData +}); +function _fileName(headerValue) { + const m2 = headerValue.match(/\bfilename=("(.*?)"|([^()<>@,;:\\"/[\]?={}\s\t]+))($|;\s)/i); + if (!m2) { + return; + } + const match = m2[2] || m2[3] || ""; + let filename = match.slice(match.lastIndexOf("\\") + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#(\d{4});/g, (m3, code) => { + return String.fromCharCode(code); + }); + return filename; +} +async function toFormData(Body2, ct) { + if (!/multipart/i.test(ct)) { + throw new TypeError("Failed to fetch"); + } + const m2 = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (!m2) { + throw new TypeError("no or bad content-type header, no multipart boundary"); + } + const parser = new MultipartParser(m2[1] || m2[2]); + let headerField; + let headerValue; + let entryValue; + let entryName; + let contentType; + let filename; + const entryChunks = []; + const formData = new FormData(); + const onPartData = (ui8a) => { + entryValue += decoder.decode(ui8a, { stream: true }); + }; + const appendToFile = (ui8a) => { + entryChunks.push(ui8a); + }; + const appendFileToFormData = () => { + const file = new file_default(entryChunks, filename, { type: contentType }); + formData.append(entryName, file); + }; + const appendEntryToFormData = () => { + formData.append(entryName, entryValue); + }; + const decoder = new TextDecoder("utf-8"); + decoder.decode(); + parser.onPartBegin = function() { + parser.onPartData = onPartData; + parser.onPartEnd = appendEntryToFormData; + headerField = ""; + headerValue = ""; + entryValue = ""; + entryName = ""; + contentType = ""; + filename = null; + entryChunks.length = 0; + }; + parser.onHeaderField = function(ui8a) { + headerField += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderValue = function(ui8a) { + headerValue += decoder.decode(ui8a, { stream: true }); + }; + parser.onHeaderEnd = function() { + headerValue += decoder.decode(); + headerField = headerField.toLowerCase(); + if (headerField === "content-disposition") { + const m3 = headerValue.match(/\bname=("([^"]*)"|([^()<>@,;:\\"/[\]?={}\s\t]+))/i); + if (m3) { + entryName = m3[2] || m3[3] || ""; + } + filename = _fileName(headerValue); + if (filename) { + parser.onPartData = appendToFile; + parser.onPartEnd = appendFileToFormData; + } + } else if (headerField === "content-type") { + contentType = headerValue; + } + headerValue = ""; + headerField = ""; + }; + for await (const chunk of Body2) { + parser.write(chunk); + } + parser.end(); + return formData; +} +var s, S, f2, F, LF, CR, SPACE, HYPHEN, COLON, A, Z, lower, noop, MultipartParser; +var init_multipart_parser = __esm({ + "node_modules/node-fetch/src/utils/multipart-parser.js"() { + init_from(); + init_esm_min(); + s = 0; + S = { + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + END: s++ + }; + f2 = 1; + F = { + PART_BOUNDARY: f2, + LAST_BOUNDARY: f2 *= 2 + }; + LF = 10; + CR = 13; + SPACE = 32; + HYPHEN = 45; + COLON = 58; + A = 97; + Z = 122; + lower = (c) => c | 32; + noop = () => { + }; + MultipartParser = class { + constructor(boundary) { + this.index = 0; + this.flags = 0; + this.onHeaderEnd = noop; + this.onHeaderField = noop; + this.onHeadersEnd = noop; + this.onHeaderValue = noop; + this.onPartBegin = noop; + this.onPartData = noop; + this.onPartEnd = noop; + this.boundaryChars = {}; + boundary = "\r\n--" + boundary; + const ui8a = new Uint8Array(boundary.length); + for (let i2 = 0; i2 < boundary.length; i2++) { + ui8a[i2] = boundary.charCodeAt(i2); + this.boundaryChars[ui8a[i2]] = true; + } + this.boundary = ui8a; + this.lookbehind = new Uint8Array(this.boundary.length + 8); + this.state = S.START_BOUNDARY; + } + write(data) { + let i2 = 0; + const length_ = data.length; + let previousIndex = this.index; + let { lookbehind, boundary, boundaryChars, index, state, flags } = this; + const boundaryLength = this.boundary.length; + const boundaryEnd = boundaryLength - 1; + const bufferLength = data.length; + let c; + let cl; + const mark = (name) => { + this[name + "Mark"] = i2; + }; + const clear = (name) => { + delete this[name + "Mark"]; + }; + const callback = (callbackSymbol, start, end, ui8a) => { + if (start === void 0 || start !== end) { + this[callbackSymbol](ui8a && ui8a.subarray(start, end)); + } + }; + const dataCallback = (name, clear2) => { + const markSymbol = name + "Mark"; + if (!(markSymbol in this)) { + return; + } + if (clear2) { + callback(name, this[markSymbol], i2, data); + delete this[markSymbol]; + } else { + callback(name, this[markSymbol], data.length, data); + this[markSymbol] = 0; + } + }; + for (i2 = 0; i2 < length_; i2++) { + c = data[i2]; + switch (state) { + case S.START_BOUNDARY: + if (index === boundary.length - 2) { + if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c !== CR) { + return; + } + index++; + break; + } else if (index - 1 === boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c === HYPHEN) { + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c === LF) { + index = 0; + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + } else { + return; + } + break; + } + if (c !== boundary[index + 2]) { + index = -2; + } + if (c === boundary[index + 2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark("onHeaderField"); + index = 0; + case S.HEADER_FIELD: + if (c === CR) { + clear("onHeaderField"); + state = S.HEADERS_ALMOST_DONE; + break; + } + index++; + if (c === HYPHEN) { + break; + } + if (c === COLON) { + if (index === 1) { + return; + } + dataCallback("onHeaderField", true); + state = S.HEADER_VALUE_START; + break; + } + cl = lower(c); + if (cl < A || cl > Z) { + return; + } + break; + case S.HEADER_VALUE_START: + if (c === SPACE) { + break; + } + mark("onHeaderValue"); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c === CR) { + dataCallback("onHeaderValue", true); + callback("onHeaderEnd"); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c !== LF) { + return; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c !== LF) { + return; + } + callback("onHeadersEnd"); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark("onPartData"); + case S.PART_DATA: + previousIndex = index; + if (index === 0) { + i2 += boundaryEnd; + while (i2 < bufferLength && !(data[i2] in boundaryChars)) { + i2 += boundaryLength; + } + i2 -= boundaryEnd; + c = data[i2]; + } + if (index < boundary.length) { + if (boundary[index] === c) { + if (index === 0) { + dataCallback("onPartData", true); + } + index++; + } else { + index = 0; + } + } else if (index === boundary.length) { + index++; + if (c === CR) { + flags |= F.PART_BOUNDARY; + } else if (c === HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 === boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c === LF) { + flags &= ~F.PART_BOUNDARY; + callback("onPartEnd"); + callback("onPartBegin"); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c === HYPHEN) { + callback("onPartEnd"); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } + if (index > 0) { + lookbehind[index - 1] = c; + } else if (previousIndex > 0) { + const _lookbehind = new Uint8Array(lookbehind.buffer, lookbehind.byteOffset, lookbehind.byteLength); + callback("onPartData", 0, previousIndex, _lookbehind); + previousIndex = 0; + mark("onPartData"); + i2--; + } + break; + case S.END: + break; + default: + throw new Error(`Unexpected state entered: ${state}`); + } + } + dataCallback("onHeaderField"); + dataCallback("onHeaderValue"); + dataCallback("onPartData"); + this.index = index; + this.state = state; + this.flags = flags; + } + end() { + if (this.state === S.HEADER_FIELD_START && this.index === 0 || this.state === S.PART_DATA && this.index === this.boundary.length) { + this.onPartEnd(); + } else if (this.state !== S.END) { + throw new Error("MultipartParser.end(): stream ended unexpectedly"); + } + } + }; + } +}); + +// src/main.ts +var main_exports = {}; +__export(main_exports, { + default: () => Khoj +}); +module.exports = __toCommonJS(main_exports); +var import_obsidian5 = require("obsidian"); + +// src/settings.ts +var import_obsidian = require("obsidian"); +var DEFAULT_SETTINGS = { + enableOfflineChat: false, + resultsCount: 6, + khojUrl: "http://127.0.0.1:42110", + connectedToBackend: false, + autoConfigure: true, + openaiApiKey: "" +}; +var KhojSettingTab = class extends import_obsidian.PluginSettingTab { + constructor(app2, plugin) { + super(app2, plugin); + this.plugin = plugin; + } + display() { + const { containerEl } = this; + containerEl.empty(); + containerEl.createEl("small", { text: this.getBackendStatusMessage() }); + new import_obsidian.Setting(containerEl).setName("Khoj URL").setDesc("The URL of the Khoj backend.").addText((text) => text.setValue(`${this.plugin.settings.khojUrl}`).onChange(async (value) => { + var _a4; + this.plugin.settings.khojUrl = value.trim(); + await this.plugin.saveSettings(); + (_a4 = containerEl.firstElementChild) == null ? void 0 : _a4.setText(this.getBackendStatusMessage()); + })); + new import_obsidian.Setting(containerEl).setName("OpenAI API Key").setDesc("Use OpenAI for Khoj Chat with your API key.").addText((text) => text.setValue(`${this.plugin.settings.openaiApiKey}`).onChange(async (value) => { + this.plugin.settings.openaiApiKey = value.trim(); + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Enable Offline Chat").setDesc("Chat privately without an internet connection. Enabling this will use offline chat even if OpenAI is configured.").addToggle((toggle) => toggle.setValue(this.plugin.settings.enableOfflineChat).onChange(async (value) => { + this.plugin.settings.enableOfflineChat = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Results Count").setDesc("The number of results to show in search and use for chat.").addSlider((slider) => slider.setLimits(1, 10, 1).setValue(this.plugin.settings.resultsCount).setDynamicTooltip().onChange(async (value) => { + this.plugin.settings.resultsCount = value; + await this.plugin.saveSettings(); + })); + new import_obsidian.Setting(containerEl).setName("Auto Configure").setDesc("Automatically configure the Khoj backend.").addToggle((toggle) => toggle.setValue(this.plugin.settings.autoConfigure).onChange(async (value) => { + this.plugin.settings.autoConfigure = value; + await this.plugin.saveSettings(); + })); + let indexVaultSetting = new import_obsidian.Setting(containerEl); + indexVaultSetting.setName("Index Vault").setDesc("Manually force Khoj to re-index your Obsidian Vault.").addButton((button) => button.setButtonText("Update").setCta().onClick(async () => { + button.setButtonText("Updating \u{1F311}"); + button.removeCta(); + indexVaultSetting = indexVaultSetting.setDisabled(true); + const progress_indicator = window.setInterval(() => { + if (button.buttonEl.innerText === "Updating \u{1F311}") { + button.setButtonText("Updating \u{1F318}"); + } else if (button.buttonEl.innerText === "Updating \u{1F318}") { + button.setButtonText("Updating \u{1F317}"); + } else if (button.buttonEl.innerText === "Updating \u{1F317}") { + button.setButtonText("Updating \u{1F316}"); + } else if (button.buttonEl.innerText === "Updating \u{1F316}") { + button.setButtonText("Updating \u{1F315}"); + } else if (button.buttonEl.innerText === "Updating \u{1F315}") { + button.setButtonText("Updating \u{1F314}"); + } else if (button.buttonEl.innerText === "Updating \u{1F314}") { + button.setButtonText("Updating \u{1F313}"); + } else if (button.buttonEl.innerText === "Updating \u{1F313}") { + button.setButtonText("Updating \u{1F312}"); + } else if (button.buttonEl.innerText === "Updating \u{1F312}") { + button.setButtonText("Updating \u{1F311}"); + } + }, 300); + this.plugin.registerInterval(progress_indicator); + await (0, import_obsidian.request)(`${this.plugin.settings.khojUrl}/api/update?t=markdown&force=true&client=obsidian`); + await (0, import_obsidian.request)(`${this.plugin.settings.khojUrl}/api/update?t=pdf&force=true&client=obsidian`); + new import_obsidian.Notice("\u2705 Updated Khoj index."); + window.clearInterval(progress_indicator); + button.setButtonText("Update"); + button.setCta(); + indexVaultSetting = indexVaultSetting.setDisabled(false); + })); + } + getBackendStatusMessage() { + return !this.plugin.settings.connectedToBackend ? "\u2757Disconnected from Khoj backend. Ensure Khoj backend is running and Khoj URL is correctly set below." : "\u2705 Connected to Khoj backend."; + } +}; + +// src/search_modal.ts +var import_obsidian3 = require("obsidian"); + +// src/utils.ts +var import_obsidian2 = require("obsidian"); +function getVaultAbsolutePath(vault) { + let adaptor = vault.adapter; + if (adaptor instanceof import_obsidian2.FileSystemAdapter) { + return adaptor.getBasePath(); + } + return ""; +} +async function configureKhojBackend(vault, setting, notify = true) { + let vaultPath = getVaultAbsolutePath(vault); + let mdInVault = `${vaultPath}/**/*.md`; + let pdfInVault = `${vaultPath}/**/*.pdf`; + let khojConfigUrl = `${setting.khojUrl}/api/config/data`; + let khoj_already_configured = await (0, import_obsidian2.request)(khojConfigUrl).then((response) => { + setting.connectedToBackend = true; + return response !== "null"; + }).catch((error) => { + setting.connectedToBackend = false; + if (notify) + new import_obsidian2.Notice(`\u2757\uFE0FEnsure Khoj backend is running and Khoj URL is pointing to it in the plugin settings. + +${error}`); + }); + if (!setting.connectedToBackend) + return; + let indexName = vaultPath.replace(/\//g, "_").replace(/\\/g, "_").replace(/ /g, "_").replace(/:/g, "_"); + let defaultConfig = await (0, import_obsidian2.request)(`${khojConfigUrl}/default`).then((response) => JSON.parse(response)); + let khojDefaultMdIndexDirectory = getIndexDirectoryFromBackendConfig(defaultConfig["content-type"]["markdown"]["embeddings-file"]); + let khojDefaultPdfIndexDirectory = getIndexDirectoryFromBackendConfig(defaultConfig["content-type"]["pdf"]["embeddings-file"]); + let khojDefaultChatDirectory = getIndexDirectoryFromBackendConfig(defaultConfig["processor"]["conversation"]["conversation-logfile"]); + let khojDefaultChatModelName = defaultConfig["processor"]["conversation"]["openai"]["chat-model"]; + await (0, import_obsidian2.request)(khoj_already_configured ? khojConfigUrl : `${khojConfigUrl}/default`).then((response) => JSON.parse(response)).then((data) => { + var _a4, _b, _c, _d2, _e, _f, _g; + if (!khoj_already_configured) { + data["content-type"] = { + "markdown": { + "input-filter": [mdInVault], + "input-files": null, + "embeddings-file": `${khojDefaultMdIndexDirectory}/${indexName}.pt`, + "compressed-jsonl": `${khojDefaultMdIndexDirectory}/${indexName}.jsonl.gz` + } + }; + const hasPdfFiles = app.vault.getFiles().some((file) => file.extension === "pdf"); + if (hasPdfFiles) { + data["content-type"]["pdf"] = { + "input-filter": [pdfInVault], + "input-files": null, + "embeddings-file": `${khojDefaultPdfIndexDirectory}/${indexName}.pt`, + "compressed-jsonl": `${khojDefaultPdfIndexDirectory}/${indexName}.jsonl.gz` + }; + } + } else if (!data["content-type"]["markdown"]) { + data["content-type"]["markdown"] = { + "input-filter": [mdInVault], + "input-files": null, + "embeddings-file": `${khojDefaultMdIndexDirectory}/${indexName}.pt`, + "compressed-jsonl": `${khojDefaultMdIndexDirectory}/${indexName}.jsonl.gz` + }; + } else if (data["content-type"]["markdown"]["input-files"] != null || data["content-type"]["markdown"]["input-filter"] == null || data["content-type"]["markdown"]["input-filter"].length != 1 || data["content-type"]["markdown"]["input-filter"][0] !== mdInVault) { + let khojMdIndexDirectory = getIndexDirectoryFromBackendConfig(data["content-type"]["markdown"]["embeddings-file"]); + data["content-type"]["markdown"] = { + "input-filter": [mdInVault], + "input-files": null, + "embeddings-file": `${khojMdIndexDirectory}/${indexName}.pt`, + "compressed-jsonl": `${khojMdIndexDirectory}/${indexName}.jsonl.gz` + }; + } + if (khoj_already_configured && !data["content-type"]["pdf"]) { + const hasPdfFiles = app.vault.getFiles().some((file) => file.extension === "pdf"); + if (hasPdfFiles) { + data["content-type"]["pdf"] = { + "input-filter": [pdfInVault], + "input-files": null, + "embeddings-file": `${khojDefaultPdfIndexDirectory}/${indexName}.pt`, + "compressed-jsonl": `${khojDefaultPdfIndexDirectory}/${indexName}.jsonl.gz` + }; + } else { + data["content-type"]["pdf"] = null; + } + } else if (khoj_already_configured && (data["content-type"]["pdf"]["input-files"] != null || data["content-type"]["pdf"]["input-filter"] == null || data["content-type"]["pdf"]["input-filter"].length != 1 || data["content-type"]["pdf"]["input-filter"][0] !== pdfInVault)) { + let hasPdfFiles = app.vault.getFiles().some((file) => file.extension === "pdf"); + if (hasPdfFiles) { + let khojPdfIndexDirectory = getIndexDirectoryFromBackendConfig(data["content-type"]["pdf"]["embeddings-file"]); + data["content-type"]["pdf"] = { + "input-filter": [pdfInVault], + "input-files": null, + "embeddings-file": `${khojPdfIndexDirectory}/${indexName}.pt`, + "compressed-jsonl": `${khojPdfIndexDirectory}/${indexName}.jsonl.gz` + }; + } else { + data["content-type"]["pdf"] = null; + } + } + let conversationLogFile = (_c = (_b = (_a4 = data == null ? void 0 : data["processor"]) == null ? void 0 : _a4["conversation"]) == null ? void 0 : _b["conversation-logfile"]) != null ? _c : `${khojDefaultChatDirectory}/conversation.json`; + let processorData = { + "conversation": { + "conversation-logfile": conversationLogFile, + "openai": null, + "enable-offline-chat": setting.enableOfflineChat + } + }; + if (!!setting.openaiApiKey) { + let openAIChatModel = (_g = (_f = (_e = (_d2 = data == null ? void 0 : data["processor"]) == null ? void 0 : _d2["conversation"]) == null ? void 0 : _e["openai"]) == null ? void 0 : _f["chat-model"]) != null ? _g : khojDefaultChatModelName; + processorData = { + "conversation": { + "conversation-logfile": conversationLogFile, + "openai": { + "chat-model": openAIChatModel, + "api-key": setting.openaiApiKey + }, + "enable-offline-chat": setting.enableOfflineChat + } + }; + } + data["processor"] = processorData; + updateKhojBackend(setting.khojUrl, data); + if (!khoj_already_configured) + console.log(`Khoj: Created khoj backend config: +${JSON.stringify(data)}`); + else + console.log(`Khoj: Updated khoj backend config: +${JSON.stringify(data)}`); + }).catch((error) => { + if (notify) + new import_obsidian2.Notice(`\u2757\uFE0FFailed to configure Khoj backend. Contact developer on Github. + +Error: ${error}`); + }); +} +async function updateKhojBackend(khojUrl, khojConfig) { + let requestContent = { + url: `${khojUrl}/api/config/data`, + body: JSON.stringify(khojConfig), + method: "POST", + contentType: "application/json" + }; + await (0, import_obsidian2.request)(requestContent).then((_) => (0, import_obsidian2.request)(`${khojUrl}/api/update?t=markdown`)).then((_) => (0, import_obsidian2.request)(`${khojUrl}/api/update?t=pdf`)); +} +function getIndexDirectoryFromBackendConfig(filepath) { + return filepath.split("/").slice(0, -1).join("/"); +} +async function createNote(name, newLeaf = false) { + var _a4, _b; + try { + let pathPrefix; + switch (app.vault.getConfig("newFileLocation")) { + case "current": + pathPrefix = ((_b = (_a4 = app.workspace.getActiveFile()) == null ? void 0 : _a4.parent.path) != null ? _b : "") + "/"; + break; + case "folder": + pathPrefix = this.app.vault.getConfig("newFileFolderPath") + "/"; + break; + default: + pathPrefix = ""; + break; + } + await app.workspace.openLinkText(`${pathPrefix}${name}.md`, "", newLeaf); + } catch (e2) { + console.error("Khoj: Could not create note.\n" + e2.message); + throw e2; + } +} +async function createNoteAndCloseModal(query, modal, opt) { + try { + await createNote(query, opt == null ? void 0 : opt.newLeaf); + } catch (e2) { + new import_obsidian2.Notice(e2.message); + return; + } + modal.close(); +} + +// src/search_modal.ts +var KhojSearchModal = class extends import_obsidian3.SuggestModal { + constructor(app2, setting, find_similar_notes = false) { + super(app2); + this.rerank = false; + this.query = ""; + this.app = app2; + this.setting = setting; + this.find_similar_notes = find_similar_notes; + this.inputEl.hidden = this.find_similar_notes; + this.scope.register(["Mod"], "Enter", async () => { + this.rerank = true; + this.inputEl.dispatchEvent(new Event("input")); + this.rerank = false; + }); + this.scope.register(["Shift"], "Enter", async () => { + if (this.query != "") + createNoteAndCloseModal(this.query, this); + }); + this.scope.register(["Ctrl", "Shift"], "Enter", async () => { + if (this.query != "") + createNoteAndCloseModal(this.query, this, { newLeaf: true }); + }); + const modalInstructions = [ + { + command: "\u2191\u2193", + purpose: "to navigate" + }, + { + command: "\u21B5", + purpose: "to open" + }, + { + command: import_obsidian3.Platform.isMacOS ? "cmd \u21B5" : "ctrl \u21B5", + purpose: "to rerank" + }, + { + command: "esc", + purpose: "to dismiss" + } + ]; + this.setInstructions(modalInstructions); + this.setPlaceholder("Search with Khoj..."); + } + async onOpen() { + if (this.find_similar_notes) { + let file = this.app.workspace.getActiveFile(); + if (file && file.extension === "md") { + this.rerank = true; + this.inputEl.value = await this.app.vault.read(file).then((file_str) => file_str.slice(0, 42110)); + this.inputEl.dispatchEvent(new Event("input")); + this.rerank = false; + } else { + this.resultContainerEl.setText("Cannot find similar notes for non-markdown files"); + } + } + } + async getSuggestions(query) { + let encodedQuery = encodeURIComponent(query); + let searchUrl = `${this.setting.khojUrl}/api/search?q=${encodedQuery}&n=${this.setting.resultsCount}&r=${this.rerank}&client=obsidian`; + let mdResponse = await (0, import_obsidian3.request)(`${searchUrl}&t=markdown`); + let pdfResponse = await (0, import_obsidian3.request)(`${searchUrl}&t=pdf`); + let mdData = JSON.parse(mdResponse).filter((result) => { + var _a4; + return !this.find_similar_notes || !result.additional.file.endsWith((_a4 = this.app.workspace.getActiveFile()) == null ? void 0 : _a4.path); + }).map((result) => { + return { entry: result.entry, score: result.score, file: result.additional.file }; + }); + let pdfData = JSON.parse(pdfResponse).filter((result) => { + var _a4; + return !this.find_similar_notes || !result.additional.file.endsWith((_a4 = this.app.workspace.getActiveFile()) == null ? void 0 : _a4.path); + }).map((result) => { + return { entry: `## ${result.additional.compiled}`, score: result.score, file: result.additional.file }; + }); + let results = mdData.concat(pdfData).sort((a, b) => b.score - a.score).map((result) => { + return { entry: result.entry, file: result.file }; + }); + this.query = query; + return results; + } + async renderSuggestion(result, el) { + let lines_to_render = 8; + let os_path_separator = result.file.includes("\\") ? "\\" : "/"; + let filename = result.file.split(os_path_separator).pop(); + result.entry = result.entry.replace(/---[\n\r][\s\S]*---[\n\r]/, ""); + let entry_snipped_indicator = result.entry.split("\n").length > lines_to_render ? " **...**" : ""; + let snipped_entry = result.entry.split("\n").slice(0, lines_to_render).join("\n"); + el.createEl("div", { cls: "khoj-result-file" }).setText(filename != null ? filename : ""); + let result_el = el.createEl("div", { cls: "khoj-result-entry" }); + import_obsidian3.MarkdownRenderer.renderMarkdown(snipped_entry + entry_snipped_indicator, result_el, null, null); + } + async onChooseSuggestion(result, _) { + const mdFiles = this.app.vault.getMarkdownFiles(); + const pdfFiles = this.app.vault.getFiles().filter((file) => file.extension === "pdf"); + let file_match = mdFiles.concat(pdfFiles).sort((a, b) => b.path.length - a.path.length).find((file) => result.file.replace(/\\/g, "/").endsWith(file.path)); + if (file_match) { + let resultHeading = file_match.extension !== "pdf" ? result.entry.split("\n", 1)[0] : ""; + let linkToEntry = resultHeading.startsWith("#") ? `${file_match.path}${resultHeading}` : file_match.path; + this.app.workspace.openLinkText(linkToEntry, ""); + console.log(`Link: ${linkToEntry}, File: ${file_match.path}, Heading: ${resultHeading}`); + } + } +}; + +// src/chat_modal.ts +var import_obsidian4 = require("obsidian"); + +// node_modules/node-fetch/src/index.js +var import_node_http2 = __toESM(require("node:http"), 1); +var import_node_https = __toESM(require("node:https"), 1); +var import_node_zlib = __toESM(require("node:zlib"), 1); +var import_node_stream2 = __toESM(require("node:stream"), 1); +var import_node_buffer2 = require("node:buffer"); + +// node_modules/data-uri-to-buffer/dist/index.js +function dataUriToBuffer(uri) { + if (!/^data:/i.test(uri)) { + throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")'); + } + uri = uri.replace(/\r?\n/g, ""); + const firstComma = uri.indexOf(","); + if (firstComma === -1 || firstComma <= 4) { + throw new TypeError("malformed data: URI"); + } + const meta = uri.substring(5, firstComma).split(";"); + let charset = ""; + let base64 = false; + const type = meta[0] || "text/plain"; + let typeFull = type; + for (let i2 = 1; i2 < meta.length; i2++) { + if (meta[i2] === "base64") { + base64 = true; + } else if (meta[i2]) { + typeFull += `;${meta[i2]}`; + if (meta[i2].indexOf("charset=") === 0) { + charset = meta[i2].substring(8); + } + } + } + if (!meta[0] && !charset.length) { + typeFull += ";charset=US-ASCII"; + charset = "US-ASCII"; + } + const encoding = base64 ? "base64" : "ascii"; + const data = unescape(uri.substring(firstComma + 1)); + const buffer = Buffer.from(data, encoding); + buffer.type = type; + buffer.typeFull = typeFull; + buffer.charset = charset; + return buffer; +} +var dist_default = dataUriToBuffer; + +// node_modules/node-fetch/src/body.js +var import_node_stream = __toESM(require("node:stream"), 1); +var import_node_util = require("node:util"); +var import_node_buffer = require("node:buffer"); +init_fetch_blob(); +init_esm_min(); + +// node_modules/node-fetch/src/errors/base.js +var FetchBaseError = class extends Error { + constructor(message, type) { + super(message); + Error.captureStackTrace(this, this.constructor); + this.type = type; + } + get name() { + return this.constructor.name; + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } +}; + +// node_modules/node-fetch/src/errors/fetch-error.js +var FetchError = class extends FetchBaseError { + constructor(message, type, systemError) { + super(message, type); + if (systemError) { + this.code = this.errno = systemError.code; + this.erroredSysCall = systemError.syscall; + } + } +}; + +// node_modules/node-fetch/src/utils/is.js +var NAME = Symbol.toStringTag; +var isURLSearchParameters = (object) => { + return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams"; +}; +var isBlob = (object) => { + return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]); +}; +var isAbortSignal = (object) => { + return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget"); +}; +var isDomainOrSubdomain = (destination, original) => { + const orig = new URL(original).hostname; + const dest = new URL(destination).hostname; + return orig === dest || orig.endsWith(`.${dest}`); +}; +var isSameProtocol = (destination, original) => { + const orig = new URL(original).protocol; + const dest = new URL(destination).protocol; + return orig === dest; +}; + +// node_modules/node-fetch/src/body.js +var pipeline = (0, import_node_util.promisify)(import_node_stream.default.pipeline); +var INTERNALS = Symbol("Body internals"); +var Body = class { + constructor(body, { + size = 0 + } = {}) { + let boundary = null; + if (body === null) { + body = null; + } else if (isURLSearchParameters(body)) { + body = import_node_buffer.Buffer.from(body.toString()); + } else if (isBlob(body)) { + } else if (import_node_buffer.Buffer.isBuffer(body)) { + } else if (import_node_util.types.isAnyArrayBuffer(body)) { + body = import_node_buffer.Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + body = import_node_buffer.Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof import_node_stream.default) { + } else if (body instanceof FormData) { + body = formDataToBlob(body); + boundary = body.type.split("=")[1]; + } else { + body = import_node_buffer.Buffer.from(String(body)); + } + let stream = body; + if (import_node_buffer.Buffer.isBuffer(body)) { + stream = import_node_stream.default.Readable.from(body); + } else if (isBlob(body)) { + stream = import_node_stream.default.Readable.from(body.stream()); + } + this[INTERNALS] = { + body, + stream, + boundary, + disturbed: false, + error: null + }; + this.size = size; + if (body instanceof import_node_stream.default) { + body.on("error", (error_) => { + const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_); + this[INTERNALS].error = error; + }); + } + } + get body() { + return this[INTERNALS].stream; + } + get bodyUsed() { + return this[INTERNALS].disturbed; + } + async arrayBuffer() { + const { buffer, byteOffset, byteLength } = await consumeBody(this); + return buffer.slice(byteOffset, byteOffset + byteLength); + } + async formData() { + const ct = this.headers.get("content-type"); + if (ct.startsWith("application/x-www-form-urlencoded")) { + const formData = new FormData(); + const parameters = new URLSearchParams(await this.text()); + for (const [name, value] of parameters) { + formData.append(name, value); + } + return formData; + } + const { toFormData: toFormData2 } = await Promise.resolve().then(() => (init_multipart_parser(), multipart_parser_exports)); + return toFormData2(this.body, ct); + } + async blob() { + const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || ""; + const buf = await this.arrayBuffer(); + return new fetch_blob_default([buf], { + type: ct + }); + } + async json() { + const text = await this.text(); + return JSON.parse(text); + } + async text() { + const buffer = await consumeBody(this); + return new TextDecoder().decode(buffer); + } + buffer() { + return consumeBody(this); + } +}; +Body.prototype.buffer = (0, import_node_util.deprecate)(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer"); +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true }, + data: { get: (0, import_node_util.deprecate)(() => { + }, "data doesn't exist, use json(), text(), arrayBuffer(), or body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (response)") } +}); +async function consumeBody(data) { + if (data[INTERNALS].disturbed) { + throw new TypeError(`body used already for: ${data.url}`); + } + data[INTERNALS].disturbed = true; + if (data[INTERNALS].error) { + throw data[INTERNALS].error; + } + const { body } = data; + if (body === null) { + return import_node_buffer.Buffer.alloc(0); + } + if (!(body instanceof import_node_stream.default)) { + return import_node_buffer.Buffer.alloc(0); + } + const accum = []; + let accumBytes = 0; + try { + for await (const chunk of body) { + if (data.size > 0 && accumBytes + chunk.length > data.size) { + const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size"); + body.destroy(error); + throw error; + } + accumBytes += chunk.length; + accum.push(chunk); + } + } catch (error) { + const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error); + throw error_; + } + if (body.readableEnded === true || body._readableState.ended === true) { + try { + if (accum.every((c) => typeof c === "string")) { + return import_node_buffer.Buffer.from(accum.join("")); + } + return import_node_buffer.Buffer.concat(accum, accumBytes); + } catch (error) { + throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error); + } + } else { + throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`); + } +} +var clone = (instance, highWaterMark) => { + let p1; + let p2; + let { body } = instance[INTERNALS]; + if (instance.bodyUsed) { + throw new Error("cannot clone body after it is used"); + } + if (body instanceof import_node_stream.default && typeof body.getBoundary !== "function") { + p1 = new import_node_stream.PassThrough({ highWaterMark }); + p2 = new import_node_stream.PassThrough({ highWaterMark }); + body.pipe(p1); + body.pipe(p2); + instance[INTERNALS].stream = p1; + body = p2; + } + return body; +}; +var getNonSpecFormDataBoundary = (0, import_node_util.deprecate)((body) => body.getBoundary(), "form-data doesn't follow the spec and requires special treatment. Use alternative package", "https://github.com/node-fetch/node-fetch/issues/1167"); +var extractContentType = (body, request5) => { + if (body === null) { + return null; + } + if (typeof body === "string") { + return "text/plain;charset=UTF-8"; + } + if (isURLSearchParameters(body)) { + return "application/x-www-form-urlencoded;charset=UTF-8"; + } + if (isBlob(body)) { + return body.type || null; + } + if (import_node_buffer.Buffer.isBuffer(body) || import_node_util.types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) { + return null; + } + if (body instanceof FormData) { + return `multipart/form-data; boundary=${request5[INTERNALS].boundary}`; + } + if (body && typeof body.getBoundary === "function") { + return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`; + } + if (body instanceof import_node_stream.default) { + return null; + } + return "text/plain;charset=UTF-8"; +}; +var getTotalBytes = (request5) => { + const { body } = request5[INTERNALS]; + if (body === null) { + return 0; + } + if (isBlob(body)) { + return body.size; + } + if (import_node_buffer.Buffer.isBuffer(body)) { + return body.length; + } + if (body && typeof body.getLengthSync === "function") { + return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null; + } + return null; +}; +var writeToStream = async (dest, { body }) => { + if (body === null) { + dest.end(); + } else { + await pipeline(body, dest); + } +}; + +// node_modules/node-fetch/src/headers.js +var import_node_util2 = require("node:util"); +var import_node_http = __toESM(require("node:http"), 1); +var validateHeaderName = typeof import_node_http.default.validateHeaderName === "function" ? import_node_http.default.validateHeaderName : (name) => { + if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) { + const error = new TypeError(`Header name must be a valid HTTP token [${name}]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" }); + throw error; + } +}; +var validateHeaderValue = typeof import_node_http.default.validateHeaderValue === "function" ? import_node_http.default.validateHeaderValue : (name, value) => { + if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) { + const error = new TypeError(`Invalid character in header content ["${name}"]`); + Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" }); + throw error; + } +}; +var Headers = class extends URLSearchParams { + constructor(init) { + let result = []; + if (init instanceof Headers) { + const raw = init.raw(); + for (const [name, values] of Object.entries(raw)) { + result.push(...values.map((value) => [name, value])); + } + } else if (init == null) { + } else if (typeof init === "object" && !import_node_util2.types.isBoxedPrimitive(init)) { + const method = init[Symbol.iterator]; + if (method == null) { + result.push(...Object.entries(init)); + } else { + if (typeof method !== "function") { + throw new TypeError("Header pairs must be iterable"); + } + result = [...init].map((pair) => { + if (typeof pair !== "object" || import_node_util2.types.isBoxedPrimitive(pair)) { + throw new TypeError("Each header pair must be an iterable object"); + } + return [...pair]; + }).map((pair) => { + if (pair.length !== 2) { + throw new TypeError("Each header pair must be a name/value tuple"); + } + return [...pair]; + }); + } + } else { + throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence> or record)"); + } + result = result.length > 0 ? result.map(([name, value]) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return [String(name).toLowerCase(), String(value)]; + }) : void 0; + super(result); + return new Proxy(this, { + get(target, p, receiver) { + switch (p) { + case "append": + case "set": + return (name, value) => { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return URLSearchParams.prototype[p].call(target, String(name).toLowerCase(), String(value)); + }; + case "delete": + case "has": + case "getAll": + return (name) => { + validateHeaderName(name); + return URLSearchParams.prototype[p].call(target, String(name).toLowerCase()); + }; + case "keys": + return () => { + target.sort(); + return new Set(URLSearchParams.prototype.keys.call(target)).keys(); + }; + default: + return Reflect.get(target, p, receiver); + } + } + }); + } + get [Symbol.toStringTag]() { + return this.constructor.name; + } + toString() { + return Object.prototype.toString.call(this); + } + get(name) { + const values = this.getAll(name); + if (values.length === 0) { + return null; + } + let value = values.join(", "); + if (/^content-encoding$/i.test(name)) { + value = value.toLowerCase(); + } + return value; + } + forEach(callback, thisArg = void 0) { + for (const name of this.keys()) { + Reflect.apply(callback, thisArg, [this.get(name), name, this]); + } + } + *values() { + for (const name of this.keys()) { + yield this.get(name); + } + } + *entries() { + for (const name of this.keys()) { + yield [name, this.get(name)]; + } + } + [Symbol.iterator]() { + return this.entries(); + } + raw() { + return [...this.keys()].reduce((result, key) => { + result[key] = this.getAll(key); + return result; + }, {}); + } + [Symbol.for("nodejs.util.inspect.custom")]() { + return [...this.keys()].reduce((result, key) => { + const values = this.getAll(key); + if (key === "host") { + result[key] = values[0]; + } else { + result[key] = values.length > 1 ? values : values[0]; + } + return result; + }, {}); + } +}; +Object.defineProperties(Headers.prototype, ["get", "entries", "forEach", "values"].reduce((result, property) => { + result[property] = { enumerable: true }; + return result; +}, {})); +function fromRawHeaders(headers = []) { + return new Headers(headers.reduce((result, value, index, array) => { + if (index % 2 === 0) { + result.push(array.slice(index, index + 2)); + } + return result; + }, []).filter(([name, value]) => { + try { + validateHeaderName(name); + validateHeaderValue(name, String(value)); + return true; + } catch (e2) { + return false; + } + })); +} + +// node_modules/node-fetch/src/utils/is-redirect.js +var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]); +var isRedirect = (code) => { + return redirectStatus.has(code); +}; + +// node_modules/node-fetch/src/response.js +var INTERNALS2 = Symbol("Response internals"); +var Response = class extends Body { + constructor(body = null, options = {}) { + super(body, options); + const status = options.status != null ? options.status : 200; + const headers = new Headers(options.headers); + if (body !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(body, this); + if (contentType) { + headers.append("Content-Type", contentType); + } + } + this[INTERNALS2] = { + type: "default", + url: options.url, + status, + statusText: options.statusText || "", + headers, + counter: options.counter, + highWaterMark: options.highWaterMark + }; + } + get type() { + return this[INTERNALS2].type; + } + get url() { + return this[INTERNALS2].url || ""; + } + get status() { + return this[INTERNALS2].status; + } + get ok() { + return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300; + } + get redirected() { + return this[INTERNALS2].counter > 0; + } + get statusText() { + return this[INTERNALS2].statusText; + } + get headers() { + return this[INTERNALS2].headers; + } + get highWaterMark() { + return this[INTERNALS2].highWaterMark; + } + clone() { + return new Response(clone(this, this.highWaterMark), { + type: this.type, + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected, + size: this.size, + highWaterMark: this.highWaterMark + }); + } + static redirect(url, status = 302) { + if (!isRedirect(status)) { + throw new RangeError('Failed to execute "redirect" on "response": Invalid status code'); + } + return new Response(null, { + headers: { + location: new URL(url).toString() + }, + status + }); + } + static error() { + const response = new Response(null, { status: 0, statusText: "" }); + response[INTERNALS2].type = "error"; + return response; + } + static json(data = void 0, init = {}) { + const body = JSON.stringify(data); + if (body === void 0) { + throw new TypeError("data is not JSON serializable"); + } + const headers = new Headers(init && init.headers); + if (!headers.has("content-type")) { + headers.set("content-type", "application/json"); + } + return new Response(body, { + ...init, + headers + }); + } + get [Symbol.toStringTag]() { + return "Response"; + } +}; +Object.defineProperties(Response.prototype, { + type: { enumerable: true }, + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); + +// node_modules/node-fetch/src/request.js +var import_node_url = require("node:url"); +var import_node_util3 = require("node:util"); + +// node_modules/node-fetch/src/utils/get-search.js +var getSearch = (parsedURL) => { + if (parsedURL.search) { + return parsedURL.search; + } + const lastOffset = parsedURL.href.length - 1; + const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : ""); + return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : ""; +}; + +// node_modules/node-fetch/src/utils/referrer.js +var import_node_net = require("node:net"); +function stripURLForUseAsAReferrer(url, originOnly = false) { + if (url == null) { + return "no-referrer"; + } + url = new URL(url); + if (/^(about|blob|data):$/.test(url.protocol)) { + return "no-referrer"; + } + url.username = ""; + url.password = ""; + url.hash = ""; + if (originOnly) { + url.pathname = ""; + url.search = ""; + } + return url; +} +var ReferrerPolicy = /* @__PURE__ */ new Set([ + "", + "no-referrer", + "no-referrer-when-downgrade", + "same-origin", + "origin", + "strict-origin", + "origin-when-cross-origin", + "strict-origin-when-cross-origin", + "unsafe-url" +]); +var DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin"; +function validateReferrerPolicy(referrerPolicy) { + if (!ReferrerPolicy.has(referrerPolicy)) { + throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`); + } + return referrerPolicy; +} +function isOriginPotentiallyTrustworthy(url) { + if (/^(http|ws)s:$/.test(url.protocol)) { + return true; + } + const hostIp = url.host.replace(/(^\[)|(]$)/g, ""); + const hostIPVersion = (0, import_node_net.isIP)(hostIp); + if (hostIPVersion === 4 && /^127\./.test(hostIp)) { + return true; + } + if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) { + return true; + } + if (url.host === "localhost" || url.host.endsWith(".localhost")) { + return false; + } + if (url.protocol === "file:") { + return true; + } + return false; +} +function isUrlPotentiallyTrustworthy(url) { + if (/^about:(blank|srcdoc)$/.test(url)) { + return true; + } + if (url.protocol === "data:") { + return true; + } + if (/^(blob|filesystem):$/.test(url.protocol)) { + return true; + } + return isOriginPotentiallyTrustworthy(url); +} +function determineRequestsReferrer(request5, { referrerURLCallback, referrerOriginCallback } = {}) { + if (request5.referrer === "no-referrer" || request5.referrerPolicy === "") { + return null; + } + const policy = request5.referrerPolicy; + if (request5.referrer === "about:client") { + return "no-referrer"; + } + const referrerSource = request5.referrer; + let referrerURL = stripURLForUseAsAReferrer(referrerSource); + let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true); + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + if (referrerURLCallback) { + referrerURL = referrerURLCallback(referrerURL); + } + if (referrerOriginCallback) { + referrerOrigin = referrerOriginCallback(referrerOrigin); + } + const currentURL = new URL(request5.url); + switch (policy) { + case "no-referrer": + return "no-referrer"; + case "origin": + return referrerOrigin; + case "unsafe-url": + return referrerURL; + case "strict-origin": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin.toString(); + case "strict-origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerOrigin; + case "same-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return "no-referrer"; + case "origin-when-cross-origin": + if (referrerURL.origin === currentURL.origin) { + return referrerURL; + } + return referrerOrigin; + case "no-referrer-when-downgrade": + if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) { + return "no-referrer"; + } + return referrerURL; + default: + throw new TypeError(`Invalid referrerPolicy: ${policy}`); + } +} +function parseReferrerPolicyFromHeader(headers) { + const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/); + let policy = ""; + for (const token of policyTokens) { + if (token && ReferrerPolicy.has(token)) { + policy = token; + } + } + return policy; +} + +// node_modules/node-fetch/src/request.js +var INTERNALS3 = Symbol("Request internals"); +var isRequest = (object) => { + return typeof object === "object" && typeof object[INTERNALS3] === "object"; +}; +var doBadDataWarn = (0, import_node_util3.deprecate)(() => { +}, ".data is not a valid RequestInit property, use .body instead", "https://github.com/node-fetch/node-fetch/issues/1000 (request)"); +var Request = class extends Body { + constructor(input, init = {}) { + let parsedURL; + if (isRequest(input)) { + parsedURL = new URL(input.url); + } else { + parsedURL = new URL(input); + input = {}; + } + if (parsedURL.username !== "" || parsedURL.password !== "") { + throw new TypeError(`${parsedURL} is an url with embedded credentials.`); + } + let method = init.method || input.method || "GET"; + if (/^(delete|get|head|options|post|put)$/i.test(method)) { + method = method.toUpperCase(); + } + if (!isRequest(init) && "data" in init) { + doBadDataWarn(); + } + if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) { + throw new TypeError("Request with GET/HEAD method cannot have body"); + } + const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + super(inputBody, { + size: init.size || input.size || 0 + }); + const headers = new Headers(init.headers || input.headers || {}); + if (inputBody !== null && !headers.has("Content-Type")) { + const contentType = extractContentType(inputBody, this); + if (contentType) { + headers.set("Content-Type", contentType); + } + } + let signal = isRequest(input) ? input.signal : null; + if ("signal" in init) { + signal = init.signal; + } + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget"); + } + let referrer = init.referrer == null ? input.referrer : init.referrer; + if (referrer === "") { + referrer = "no-referrer"; + } else if (referrer) { + const parsedReferrer = new URL(referrer); + referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer; + } else { + referrer = void 0; + } + this[INTERNALS3] = { + method, + redirect: init.redirect || input.redirect || "follow", + headers, + parsedURL, + signal, + referrer + }; + this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow; + this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384; + this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false; + this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || ""; + } + get method() { + return this[INTERNALS3].method; + } + get url() { + return (0, import_node_url.format)(this[INTERNALS3].parsedURL); + } + get headers() { + return this[INTERNALS3].headers; + } + get redirect() { + return this[INTERNALS3].redirect; + } + get signal() { + return this[INTERNALS3].signal; + } + get referrer() { + if (this[INTERNALS3].referrer === "no-referrer") { + return ""; + } + if (this[INTERNALS3].referrer === "client") { + return "about:client"; + } + if (this[INTERNALS3].referrer) { + return this[INTERNALS3].referrer.toString(); + } + return void 0; + } + get referrerPolicy() { + return this[INTERNALS3].referrerPolicy; + } + set referrerPolicy(referrerPolicy) { + this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy); + } + clone() { + return new Request(this); + } + get [Symbol.toStringTag]() { + return "Request"; + } +}; +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true }, + referrer: { enumerable: true }, + referrerPolicy: { enumerable: true } +}); +var getNodeRequestOptions = (request5) => { + const { parsedURL } = request5[INTERNALS3]; + const headers = new Headers(request5[INTERNALS3].headers); + if (!headers.has("Accept")) { + headers.set("Accept", "*/*"); + } + let contentLengthValue = null; + if (request5.body === null && /^(post|put)$/i.test(request5.method)) { + contentLengthValue = "0"; + } + if (request5.body !== null) { + const totalBytes = getTotalBytes(request5); + if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set("Content-Length", contentLengthValue); + } + if (request5.referrerPolicy === "") { + request5.referrerPolicy = DEFAULT_REFERRER_POLICY; + } + if (request5.referrer && request5.referrer !== "no-referrer") { + request5[INTERNALS3].referrer = determineRequestsReferrer(request5); + } else { + request5[INTERNALS3].referrer = "no-referrer"; + } + if (request5[INTERNALS3].referrer instanceof URL) { + headers.set("Referer", request5.referrer); + } + if (!headers.has("User-Agent")) { + headers.set("User-Agent", "node-fetch"); + } + if (request5.compress && !headers.has("Accept-Encoding")) { + headers.set("Accept-Encoding", "gzip, deflate, br"); + } + let { agent } = request5; + if (typeof agent === "function") { + agent = agent(parsedURL); + } + if (!headers.has("Connection") && !agent) { + headers.set("Connection", "close"); + } + const search = getSearch(parsedURL); + const options = { + path: parsedURL.pathname + search, + method: request5.method, + headers: headers[Symbol.for("nodejs.util.inspect.custom")](), + insecureHTTPParser: request5.insecureHTTPParser, + agent + }; + return { + parsedURL, + options + }; +}; + +// node_modules/node-fetch/src/errors/abort-error.js +var AbortError = class extends FetchBaseError { + constructor(message, type = "aborted") { + super(message, type); + } +}; + +// node_modules/node-fetch/src/index.js +init_esm_min(); +init_from(); +var supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]); +async function fetch(url, options_) { + return new Promise((resolve, reject) => { + const request5 = new Request(url, options_); + const { parsedURL, options } = getNodeRequestOptions(request5); + if (!supportedSchemas.has(parsedURL.protocol)) { + throw new TypeError(`node-fetch cannot load ${url}. URL scheme "${parsedURL.protocol.replace(/:$/, "")}" is not supported.`); + } + if (parsedURL.protocol === "data:") { + const data = dist_default(request5.url); + const response2 = new Response(data, { headers: { "Content-Type": data.typeFull } }); + resolve(response2); + return; + } + const send = (parsedURL.protocol === "https:" ? import_node_https.default : import_node_http2.default).request; + const { signal } = request5; + let response = null; + const abort = () => { + const error = new AbortError("The operation was aborted."); + reject(error); + if (request5.body && request5.body instanceof import_node_stream2.default.Readable) { + request5.body.destroy(error); + } + if (!response || !response.body) { + return; + } + response.body.emit("error", error); + }; + if (signal && signal.aborted) { + abort(); + return; + } + const abortAndFinalize = () => { + abort(); + finalize(); + }; + const request_ = send(parsedURL.toString(), options); + if (signal) { + signal.addEventListener("abort", abortAndFinalize); + } + const finalize = () => { + request_.abort(); + if (signal) { + signal.removeEventListener("abort", abortAndFinalize); + } + }; + request_.on("error", (error) => { + reject(new FetchError(`request to ${request5.url} failed, reason: ${error.message}`, "system", error)); + finalize(); + }); + fixResponseChunkedTransferBadEnding(request_, (error) => { + if (response && response.body) { + response.body.destroy(error); + } + }); + if (process.version < "v14") { + request_.on("socket", (s2) => { + let endedWithEventsCount; + s2.prependListener("end", () => { + endedWithEventsCount = s2._eventsCount; + }); + s2.prependListener("close", (hadError) => { + if (response && endedWithEventsCount < s2._eventsCount && !hadError) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + response.body.emit("error", error); + } + }); + }); + } + request_.on("response", (response_) => { + request_.setTimeout(0); + const headers = fromRawHeaders(response_.rawHeaders); + if (isRedirect(response_.statusCode)) { + const location = headers.get("Location"); + let locationURL = null; + try { + locationURL = location === null ? null : new URL(location, request5.url); + } catch (e2) { + if (request5.redirect !== "manual") { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, "invalid-redirect")); + finalize(); + return; + } + } + switch (request5.redirect) { + case "error": + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request5.url}`, "no-redirect")); + finalize(); + return; + case "manual": + break; + case "follow": { + if (locationURL === null) { + break; + } + if (request5.counter >= request5.follow) { + reject(new FetchError(`maximum redirect reached at: ${request5.url}`, "max-redirect")); + finalize(); + return; + } + const requestOptions = { + headers: new Headers(request5.headers), + follow: request5.follow, + counter: request5.counter + 1, + agent: request5.agent, + compress: request5.compress, + method: request5.method, + body: clone(request5), + signal: request5.signal, + size: request5.size, + referrer: request5.referrer, + referrerPolicy: request5.referrerPolicy + }; + if (!isDomainOrSubdomain(request5.url, locationURL) || !isSameProtocol(request5.url, locationURL)) { + for (const name of ["authorization", "www-authenticate", "cookie", "cookie2"]) { + requestOptions.headers.delete(name); + } + } + if (response_.statusCode !== 303 && request5.body && options_.body instanceof import_node_stream2.default.Readable) { + reject(new FetchError("Cannot follow redirect with body being a readable stream", "unsupported-redirect")); + finalize(); + return; + } + if (response_.statusCode === 303 || (response_.statusCode === 301 || response_.statusCode === 302) && request5.method === "POST") { + requestOptions.method = "GET"; + requestOptions.body = void 0; + requestOptions.headers.delete("content-length"); + } + const responseReferrerPolicy = parseReferrerPolicyFromHeader(headers); + if (responseReferrerPolicy) { + requestOptions.referrerPolicy = responseReferrerPolicy; + } + resolve(fetch(new Request(locationURL, requestOptions))); + finalize(); + return; + } + default: + return reject(new TypeError(`Redirect option '${request5.redirect}' is not a valid value of RequestRedirect`)); + } + } + if (signal) { + response_.once("end", () => { + signal.removeEventListener("abort", abortAndFinalize); + }); + } + let body = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + if (process.version < "v12.10") { + response_.on("aborted", abortAndFinalize); + } + const responseOptions = { + url: request5.url, + status: response_.statusCode, + statusText: response_.statusMessage, + headers, + size: request5.size, + counter: request5.counter, + highWaterMark: request5.highWaterMark + }; + const codings = headers.get("Content-Encoding"); + if (!request5.compress || request5.method === "HEAD" || codings === null || response_.statusCode === 204 || response_.statusCode === 304) { + response = new Response(body, responseOptions); + resolve(response); + return; + } + const zlibOptions = { + flush: import_node_zlib.default.Z_SYNC_FLUSH, + finishFlush: import_node_zlib.default.Z_SYNC_FLUSH + }; + if (codings === "gzip" || codings === "x-gzip") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createGunzip(zlibOptions), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + if (codings === "deflate" || codings === "x-deflate") { + const raw = (0, import_node_stream2.pipeline)(response_, new import_node_stream2.PassThrough(), (error) => { + if (error) { + reject(error); + } + }); + raw.once("data", (chunk) => { + if ((chunk[0] & 15) === 8) { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflate(), (error) => { + if (error) { + reject(error); + } + }); + } else { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createInflateRaw(), (error) => { + if (error) { + reject(error); + } + }); + } + response = new Response(body, responseOptions); + resolve(response); + }); + raw.once("end", () => { + if (!response) { + response = new Response(body, responseOptions); + resolve(response); + } + }); + return; + } + if (codings === "br") { + body = (0, import_node_stream2.pipeline)(body, import_node_zlib.default.createBrotliDecompress(), (error) => { + if (error) { + reject(error); + } + }); + response = new Response(body, responseOptions); + resolve(response); + return; + } + response = new Response(body, responseOptions); + resolve(response); + }); + writeToStream(request_, request5).catch(reject); + }); +} +function fixResponseChunkedTransferBadEnding(request5, errorCallback) { + const LAST_CHUNK = import_node_buffer2.Buffer.from("0\r\n\r\n"); + let isChunkedTransfer = false; + let properLastChunkReceived = false; + let previousChunk; + request5.on("response", (response) => { + const { headers } = response; + isChunkedTransfer = headers["transfer-encoding"] === "chunked" && !headers["content-length"]; + }); + request5.on("socket", (socket) => { + const onSocketClose = () => { + if (isChunkedTransfer && !properLastChunkReceived) { + const error = new Error("Premature close"); + error.code = "ERR_STREAM_PREMATURE_CLOSE"; + errorCallback(error); + } + }; + const onData = (buf) => { + properLastChunkReceived = import_node_buffer2.Buffer.compare(buf.slice(-5), LAST_CHUNK) === 0; + if (!properLastChunkReceived && previousChunk) { + properLastChunkReceived = import_node_buffer2.Buffer.compare(previousChunk.slice(-3), LAST_CHUNK.slice(0, 3)) === 0 && import_node_buffer2.Buffer.compare(buf.slice(-2), LAST_CHUNK.slice(3)) === 0; + } + previousChunk = buf; + }; + socket.prependListener("close", onSocketClose); + socket.on("data", onData); + request5.on("close", () => { + socket.removeListener("close", onSocketClose); + socket.removeListener("data", onData); + }); + }); +} + +// src/chat_modal.ts +var KhojChatModal = class extends import_obsidian4.Modal { + constructor(app2, setting) { + super(app2); + this.setting = setting; + this.scope.register([], "Enter", async () => { + let input_el = this.contentEl.getElementsByClassName("khoj-chat-input")[0]; + let user_message = input_el.value; + input_el.value = ""; + await this.getChatResponse(user_message); + }); + } + async onOpen() { + let { contentEl } = this; + contentEl.addClass("khoj-chat"); + contentEl.createEl("h1", { attr: { id: "khoj-chat-title" }, text: "Khoj Chat" }); + contentEl.createDiv({ attr: { id: "khoj-chat-body", class: "khoj-chat-body" } }); + await this.getChatHistory(); + contentEl.createEl("input", { + attr: { + type: "text", + id: "khoj-chat-input", + autofocus: "autofocus", + placeholder: "Chat with Khoj [Hit Enter to send message]", + class: "khoj-chat-input option" + } + }).addEventListener("change", (event) => { + this.result = event.target.value; + }); + this.modalEl.scrollTop = this.modalEl.scrollHeight; + } + generateReference(messageEl, reference, index) { + let escaped_ref = reference.replace(/"/g, """); + return messageEl.createEl("sup").createEl("abbr", { + attr: { + title: escaped_ref, + tabindex: "0" + }, + text: `[${index}] ` + }); + } + renderMessageWithReferences(message, sender, context, dt) { + let messageEl = this.renderMessage(message, sender, dt); + if (context && !!messageEl) { + context.map((reference, index) => this.generateReference(messageEl, reference, index + 1)); + } + } + renderMessage(message, sender, dt) { + let message_time = this.formatDate(dt != null ? dt : new Date()); + let emojified_sender = sender == "khoj" ? "\u{1F3EE} Khoj" : "\u{1F914} You"; + let chat_body_el = this.contentEl.getElementsByClassName("khoj-chat-body")[0]; + let chat_message_el = chat_body_el.createDiv({ + attr: { + "data-meta": `${emojified_sender} at ${message_time}`, + class: `khoj-chat-message ${sender}` + } + }).createDiv({ + attr: { + class: `khoj-chat-message-text ${sender}` + }, + text: `${message}` + }); + chat_message_el.style.userSelect = "text"; + this.modalEl.scrollTop = this.modalEl.scrollHeight; + return chat_message_el; + } + createKhojResponseDiv(dt) { + let message_time = this.formatDate(dt != null ? dt : new Date()); + let chat_body_el = this.contentEl.getElementsByClassName("khoj-chat-body")[0]; + let chat_message_el = chat_body_el.createDiv({ + attr: { + "data-meta": `\u{1F3EE} Khoj at ${message_time}`, + class: `khoj-chat-message khoj` + } + }).createDiv({ + attr: { + class: `khoj-chat-message-text khoj` + } + }); + this.modalEl.scrollTop = this.modalEl.scrollHeight; + return chat_message_el; + } + renderIncrementalMessage(htmlElement, additionalMessage) { + htmlElement.innerHTML += additionalMessage; + this.modalEl.scrollTop = this.modalEl.scrollHeight; + } + formatDate(date) { + let time_string = date.toLocaleTimeString("en-IN", { hour: "2-digit", minute: "2-digit", hour12: false }); + let date_string = date.toLocaleString("en-IN", { year: "numeric", month: "short", day: "2-digit" }).replace(/-/g, " "); + return `${time_string}, ${date_string}`; + } + async getChatHistory() { + let chatUrl = `${this.setting.khojUrl}/api/chat/history?client=obsidian`; + let response = await (0, import_obsidian4.request)(chatUrl); + let chatLogs = JSON.parse(response).response; + chatLogs.forEach((chatLog) => { + this.renderMessageWithReferences(chatLog.message, chatLog.by, chatLog.context, new Date(chatLog.created)); + }); + } + async getChatResponse(query) { + if (!query || query === "") + return; + this.renderMessage(query, "you"); + let encodedQuery = encodeURIComponent(query); + let chatUrl = `${this.setting.khojUrl}/api/chat?q=${encodedQuery}&n=${this.setting.resultsCount}&client=obsidian&stream=true`; + let responseElement = this.createKhojResponseDiv(); + this.renderIncrementalMessage(responseElement, "\u{1F914}"); + let response = await fetch(chatUrl, { + method: "GET", + headers: { + "Access-Control-Allow-Origin": "*", + "Content-Type": "text/event-stream" + } + }); + try { + if (response.body == null) { + throw new Error("Response body is null"); + } + if (responseElement.innerHTML === "\u{1F914}") { + responseElement.innerHTML = ""; + } + for await (const chunk of response.body) { + const responseText = chunk.toString(); + if (responseText.startsWith("### compiled references:")) { + return; + } + this.renderIncrementalMessage(responseElement, responseText); + } + } catch (err) { + this.renderIncrementalMessage(responseElement, "Sorry, unable to get response from Khoj backend \u2764\uFE0F\u200D\u{1FA79}. Contact developer for help at team@khoj.dev or in Discord"); + } + } +}; + +// src/main.ts +var Khoj = class extends import_obsidian5.Plugin { + async onload() { + await this.loadSettings(); + this.addCommand({ + id: "search", + name: "Search", + checkCallback: (checking) => { + if (!checking && this.settings.connectedToBackend) + new KhojSearchModal(this.app, this.settings).open(); + return this.settings.connectedToBackend; + } + }); + this.addCommand({ + id: "similar", + name: "Find similar notes", + editorCheckCallback: (checking) => { + if (!checking && this.settings.connectedToBackend) + new KhojSearchModal(this.app, this.settings, true).open(); + return this.settings.connectedToBackend; + } + }); + this.addCommand({ + id: "chat", + name: "Chat", + checkCallback: (checking) => { + if (!checking && this.settings.connectedToBackend && (!!this.settings.openaiApiKey || this.settings.enableOfflineChat)) + new KhojChatModal(this.app, this.settings).open(); + return !!this.settings.openaiApiKey || this.settings.enableOfflineChat; + } + }); + this.addRibbonIcon("search", "Khoj", (_) => { + this.settings.connectedToBackend ? new KhojSearchModal(this.app, this.settings).open() : new import_obsidian5.Notice(`\u2757\uFE0FEnsure Khoj backend is running and Khoj URL is pointing to it in the plugin settings`); + }); + this.addSettingTab(new KhojSettingTab(this.app, this)); + } + async loadSettings() { + this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); + if (this.settings.autoConfigure) { + await configureKhojBackend(this.app.vault, this.settings); + } + } + async saveSettings() { + if (this.settings.autoConfigure) { + await configureKhojBackend(this.app.vault, this.settings, false); + } + this.saveData(this.settings); + } +}; +/*! fetch-blob. MIT License. Jimmy Wärting */ +/*! formdata-polyfill. MIT License. Jimmy Wärting */ +/*! node-domexception. MIT License. Jimmy Wärting */ diff --git a/enter/.obsidian/plugins/khoj/manifest.json b/enter/.obsidian/plugins/khoj/manifest.json new file mode 100644 index 0000000..cd7ae94 --- /dev/null +++ b/enter/.obsidian/plugins/khoj/manifest.json @@ -0,0 +1,10 @@ +{ + "id": "khoj", + "name": "Khoj", + "version": "0.11.1", + "minAppVersion": "0.15.0", + "description": "An AI Personal Assistant for your Digital Brain", + "author": "Debanjum Singh Solanky", + "authorUrl": "https://github.com/debanjum", + "isDesktopOnly": true +} diff --git a/enter/.obsidian/plugins/khoj/styles.css b/enter/.obsidian/plugins/khoj/styles.css new file mode 100644 index 0000000..3e3808f --- /dev/null +++ b/enter/.obsidian/plugins/khoj/styles.css @@ -0,0 +1,176 @@ +/* + +This CSS file will be included with your plugin, and +available in the app when your plugin is enabled. + +If your plugin does not need CSS, delete this file. + +*/ + +:root { + --khoj-chat-primary: #ffb300; + --khoj-chat-dark-grey: #475569; + } + +.khoj-chat { + display: grid; + background: var(--background-primary); + color: var(--text-normal); + text-align: center; + font-family: roboto, karma, segoe ui, sans-serif; + font-size: var(--font-ui-large); + font-weight: 300; + line-height: 1.5em; +} +.khoj-chat > * { + padding: 10px; + margin: 10px; +} + +#khoj-chat-title { + font-weight: 200; + color: var(--khoj-chat-primary); +} + +#khoj-chat-body { + font-size: var(--font-ui-medium); + margin: 0px; + line-height: 20px; + overflow-y: scroll; /* Make chat body scroll to see history */ +} +/* add chat metatdata to bottom of bubble */ +.khoj-chat-message::after { + content: attr(data-meta); + display: block; + font-size: var(--font-ui-smaller); + color: var(--text-muted); + margin: -12px 7px 0 -5px; +} +/* move message by khoj to left */ +.khoj-chat-message.khoj { + margin-left: auto; + text-align: left; +} +/* move message by you to right */ +.khoj-chat-message.you { + margin-right: auto; + text-align: right; +} +/* basic style chat message text */ +.khoj-chat-message-text { + margin: 10px; + border-radius: 10px; + padding: 10px; + position: relative; + display: inline-block; + max-width: 80%; + text-align: left; +} +/* color chat bubble by khoj blue */ +.khoj-chat-message-text.khoj { + color: var(--text-on-accent); + background: var(--khoj-chat-primary); + margin-left: auto; + white-space: pre-line; +} +/* add left protrusion to khoj chat bubble */ +.khoj-chat-message-text.khoj:after { + content: ''; + position: absolute; + bottom: -2px; + left: -7px; + border: 10px solid transparent; + border-top-color: var(--khoj-chat-primary); + border-bottom: 0; + transform: rotate(-60deg); +} +/* color chat bubble by you dark grey */ +.khoj-chat-message-text.you { + color: var(--text-on-accent); + background: var(--khoj-chat-dark-grey); + margin-right: auto; +} +/* add right protrusion to you chat bubble */ +.khoj-chat-message-text.you:after { + content: ''; + position: absolute; + top: 91%; + right: -2px; + border: 10px solid transparent; + border-left-color: var(--khoj-chat-dark-grey); + border-right: 0; + margin-top: -10px; + transform: rotate(-60deg) +} + +#khoj-chat-footer { + padding: 0; + display: grid; + grid-template-columns: minmax(70px, 100%); + grid-column-gap: 10px; + grid-row-gap: 10px; +} +#khoj-chat-footer > * { + padding: 15px; + background: #f9fafc +} +#khoj-chat-input.option:hover { + box-shadow: 0 0 11px var(--background-modifier-box-shadow); +} +#khoj-chat-input { + font-size: var(--font-ui-medium); + padding: 25px 20px; +} + +@media (pointer: coarse), (hover: none) { + #khoj-chat-body.abbr[title] { + position: relative; + padding-left: 4px; /* space references out to ease tapping */ + } + #khoj-chat-body.abbr[title]:focus:after { + content: attr(title); + + /* position tooltip */ + position: absolute; + left: 16px; /* open tooltip to right of ref link, instead of on top of it */ + width: auto; + z-index: 1; /* show tooltip above chat messages */ + + /* style tooltip */ + background-color: var(--background-secondary); + color: var(--text-muted); + border-radius: 2px; + box-shadow: 1px 1px 4px 0 var(--background-modifier-box-shadow); + font-size: var(--font-ui-small); + padding: 2px 4px; + } +} + +.khoj-result-file { + font-weight: 600; +} + +.khoj-result-entry { + color: var(--text-muted); + margin-left: 2em; + padding-left: 0.5em; + line-height: normal; + margin-top: 0.2em; + margin-bottom: 0.2em; + border-left-style: solid; + border-left-color: var(--color-accent-2); + white-space: normal; +} + +.khoj-result-entry > * { + font-size: var(--font-ui-medium); +} + +.khoj-result-entry > p { + margin-top: 0.2em; + margin-bottom: 0.2em; +} + +.khoj-result-entry p br { + display: none; +}