/* THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ var k=Object.defineProperty;var $=Object.getOwnPropertyDescriptor;var U=Object.getOwnPropertyNames;var q=Object.prototype.hasOwnProperty;var V=(l,t)=>{for(var e in t)k(l,e,{get:t[e],enumerable:!0})},X=(l,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of U(t))!q.call(l,s)&&s!==e&&k(l,s,{get:()=>t[s],enumerable:!(n=$(t,s))||n.enumerable});return l};var H=l=>X(k({},"__esModule",{value:!0}),l);var Y={};V(Y,{default:()=>R});module.exports=H(Y);var F=require("obsidian");var c=require("obsidian");var _=["claude-opus-4-1-20250805","claude-opus-4-20250514","claude-sonnet-4-20250514","claude-3-7-sonnet-latest","claude-3-5-haiku-latest","claude-3-haiku-20240307"],O=["constructive","encouraging","analytical","brief","custom"],A={constructive:"Provide balanced feedback on this freewriting, noting strengths and areas for development. Consider the flow of ideas, creativity, and any interesting themes that emerged.",encouraging:"Offer positive, supportive observations about this freewriting session. Focus on what worked well, creative insights, and encouraging the writer to continue exploring these ideas.",analytical:"Analyze the writing structure, themes, and patterns in this freewriting. Look at the progression of thoughts, recurring concepts, and the overall coherence of ideas.",brief:"Give 2-3 concise observations about this freewriting session. Keep it short but insightful."},u={MAX_TOKENS:2e5,MAX_CHARACTERS:8e5,DEFAULT_MAX_OUTPUT_TOKENS:8192};var D={apiKey:"",model:"claude-3-5-haiku-latest",cleanupPrompt:"I did some free writing. Please correct my jumbled typo mess. Only fix spelling, grammar, and punctuation. Add line breaks and paragraphs as appropriate. Do not make stylistic changes to the content or tone.",enableCommentary:!1,commentaryStyle:"constructive",customCommentaryPrompt:"Provide thoughtful feedback on this freewriting session, considering the writer's flow of thoughts and ideas."},x=class extends c.PluginSettingTab{constructor(e,n){super(e,n);this.modelDropdown=null;this.availableModels=[];this.saveDebounce=null;this.plugin=n}scheduleSave(){this.saveDebounce!==null&&window.clearTimeout(this.saveDebounce),this.saveDebounce=window.setTimeout(()=>{this.plugin.saveSettings(),this.saveDebounce=null},300)}display(){let{containerEl:e}=this;if(e.empty(),e.createEl("h2",{text:"Freewriting Cleanup Settings"}),this.loadModels().then(()=>{this.modelDropdown&&this.populateModelDropdown(this.modelDropdown)}).catch(o=>{console.error("Error loading models in background:",o)}),e.createEl("h3",{text:"API Configuration"}),new c.Setting(e).setName("Anthropic API Key").setDesc("Your Anthropic API key for Claude. Get one at https://console.anthropic.com/").addText(o=>o.setPlaceholder("sk-ant-...").setValue(this.plugin.settings.apiKey).onChange(async r=>{this.plugin.settings.apiKey=r,this.scheduleSave(),this.plugin.cleanupService.updateApiKey(r),r.trim().length>0?await this.refreshModels():this.modelDropdown&&(this.availableModels=this.plugin.modelService.getFallbackOptions(),this.populateModelDropdown(this.modelDropdown))})).then(o=>{var r;(r=o.controlEl.querySelector("input"))==null||r.setAttribute("type","password")}),new c.Setting(e).setName("Test API Key").setDesc("Test your API key to verify it works correctly").addButton(o=>o.setButtonText("Test Connection").onClick(async()=>{await this.testApiKey(o)})),new c.Setting(e).setName("Claude Model").setDesc("Which Claude model to use for text cleanup").addDropdown(o=>{this.modelDropdown=o,this.populateModelDropdown(o),o.setValue(this.plugin.settings.model).onChange(async r=>{this.plugin.settings.model=r,await this.plugin.saveSettings()})}),e.createEl("h3",{text:"Cleanup Configuration"}),new c.Setting(e).setName("Cleanup Prompt").setDesc("Instructions for how Claude should clean up your freewriting text").addTextArea(o=>{o.setPlaceholder("Enter your cleanup instructions...").setValue(this.plugin.settings.cleanupPrompt).onChange(async r=>{this.plugin.settings.cleanupPrompt=r,this.scheduleSave()}),o.inputEl.rows=4,o.inputEl.addClass("freewriting-cleanup-textarea")}),e.createEl("h3",{text:"AI Commentary"}),new c.Setting(e).setName("AI should comment on text").setDesc("After cleaning up your text, AI will provide thoughtful commentary on your freewriting session").addToggle(o=>o.setValue(this.plugin.settings.enableCommentary).onChange(async r=>{this.plugin.settings.enableCommentary=r,this.scheduleSave(),this.display()})),this.plugin.settings.enableCommentary)if(new c.Setting(e).setName("Commentary Style").setDesc("Choose the type of feedback AI should provide").addDropdown(o=>{O.forEach(r=>{let y=r.charAt(0).toUpperCase()+r.slice(1);o.addOption(r,y)}),o.setValue(this.plugin.settings.commentaryStyle).onChange(async r=>{this.plugin.settings.commentaryStyle=r,this.scheduleSave(),this.display()})}),this.plugin.settings.commentaryStyle==="custom")new c.Setting(e).setName("Custom Commentary Prompt").setDesc("Instructions for how AI should comment on your freewriting").addTextArea(o=>{o.setPlaceholder("Enter your commentary instructions...").setValue(this.plugin.settings.customCommentaryPrompt).onChange(async r=>{this.plugin.settings.customCommentaryPrompt=r,this.scheduleSave()}),o.inputEl.rows=3,o.inputEl.addClass("freewriting-cleanup-textarea-small")});else{let o=A[this.plugin.settings.commentaryStyle],r=e.createDiv({cls:"setting-item-description freewriting-cleanup-description"});r.empty(),r.createEl("strong",{text:"Selected style: "}),r.appendText(o)}e.createEl("h3",{text:"Usage Information"});let n=e.createDiv();n.empty(),n.createEl("p").createEl("strong",{text:"How to use:"});let i=n.createEl("ol");i.createEl("li",{text:"Select the text you want to clean up in any note"}),i.createEl("li",{text:'Run the "Clean up text" command (Ctrl/Cmd+P)'}),i.createEl("li",{text:"The cleaned text will appear below your original text"});let p=n.createEl("p");p.createEl("strong",{text:"Limits: "}),p.appendText(`Maximum ${u.MAX_TOKENS.toLocaleString()} tokens per cleanup (~${u.MAX_CHARACTERS.toLocaleString()} characters, varies by language)`);let a=n.createEl("p");a.createEl("strong",{text:"Format: "}),a.appendText("Original text \u2192 separator \u2192 cleaned text"),e.createEl("h3",{text:"Reset"}),new c.Setting(e).setName("Reset to Defaults").setDesc("Reset all settings to their default values").addButton(o=>o.setButtonText("Reset Settings").setWarning().onClick(async()=>{await this.resetSettings()}))}async loadModels(){try{this.availableModels=await this.plugin.modelService.getAvailableModels()}catch(e){console.error("Error loading models:",e)}}populateModelDropdown(e){if(this.availableModels.length===0){e.addOption("","Loading models..."),e.setDisabled(!0);return}e.selectEl.empty(),this.availableModels.forEach(n=>{e.addOption(n.id,n.displayName)}),e.setDisabled(!1)}async refreshModels(){try{if(this.modelDropdown&&(this.modelDropdown.setDisabled(!0),this.modelDropdown.selectEl.empty(),this.modelDropdown.addOption("","Refreshing models...")),this.availableModels=await this.plugin.modelService.refreshModels(),this.modelDropdown){this.populateModelDropdown(this.modelDropdown);let e=this.plugin.settings.model;if(this.availableModels.some(s=>s.id===e))this.modelDropdown.setValue(e);else if(this.availableModels.length>0){let s=this.availableModels[0].id;this.plugin.settings.model=s,this.modelDropdown.setValue(s),console.log(`Model '${e}' no longer available, switched to '${s}'`)}}await this.plugin.saveSettings()}catch(e){console.error("Error refreshing models:",e)}}async testApiKey(e){let n=e.buttonEl.textContent;e.setButtonText("Testing..."),e.setDisabled(!0);try{let s=await this.plugin.cleanupService.testConnection(this.plugin.settings);if(s.success){if(new c.Notice("\u2705 API connection successful!"),s.details){let i=s.details;new c.Notice(`Model: ${i.model}, Response time: ${i.responseTime}ms`)}}else new c.Notice(`\u274C API test failed: ${s.message}`)}catch(s){new c.Notice(`\u274C API test failed: ${s instanceof Error?s.message:"Unknown error"}`)}finally{e.setButtonText(n||"Test Connection"),e.setDisabled(!1)}}async resetSettings(){if(await this.showConfirmDialog("Reset Settings","Are you sure you want to reset all settings to their defaults? This cannot be undone.")){let n=this.plugin.settings.apiKey;this.plugin.settings={...D,apiKey:n},await this.plugin.saveSettings(),this.plugin.cleanupService.updateApiKey(n),this.display(),new c.Notice("Settings reset to defaults")}}async showConfirmDialog(e,n){return new Promise(s=>{new P(this.app,e,n,p=>{s(p)}).open()})}},P=class extends c.Modal{constructor(e,n,s,i){super(e);this.title=n,this.message=s,this.callback=i}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:this.title}),e.createEl("p",{text:this.message});let n=e.createDiv({cls:"modal-button-container"});n.createEl("button",{text:"Cancel"}).addEventListener("click",()=>{this.close(),this.callback(!1)});let i=n.createEl("button",{text:"Confirm",cls:"mod-warning"});i.addEventListener("click",()=>{this.close(),this.callback(!0)}),i.focus()}onClose(){let{contentEl:e}=this;e.empty()}};var I=require("obsidian");var h=class extends Error{constructor(t){super(t),this.name=this.constructor.name,Object.setPrototypeOf(this,new.target.prototype)}},m=class extends h{},f=class extends h{},C=class extends h{},g=class extends h{},E=class extends h{},T=class extends h{},w=class extends h{constructor(e,n,s){super(e);this.status=n;this.responseBody=s}};var S=class{constructor(t){this.messagesUrl="https://api.anthropic.com/v1/messages";this.modelsUrl="https://api.anthropic.com/v1/models";this.MAX_RETRIES=3;this.RETRY_DELAY_BASE=1e3;this.apiKey=t}async cleanupText(t,e,n,s=!1,i="constructive",p){if(!this.apiKey)throw new m("API key is required");if(t.length>u.MAX_CHARACTERS)throw new f(`Text too long. Maximum ${u.MAX_CHARACTERS} characters allowed.`);let a="";if(s)if(i==="custom"&&p)a=p;else{if(i==="custom")throw new E("Custom commentary style requires a custom prompt. Please provide customCommentaryPrompt.");a=A[i]}let o=`${n} ${s?`After cleaning the text, also provide commentary based on this instruction: ${a}`:""} CRITICAL OUTPUT REQUIREMENTS - YOU MUST FOLLOW THIS EXACT FORMAT: ===CLEANED TEXT=== [Put the cleaned up text here] - Fix spelling, grammar, and punctuation errors - Add line breaks and paragraphs as appropriate for readability - Preserve any existing markdown formatting (bold, italics, links, etc.) - Do not add quotation marks or any wrapper text ===END CLEANED TEXT=== ${s?` ===COMMENTARY=== [Put your commentary here based on the instruction above] ===END COMMENTARY=== `:""} You MUST use exactly these markers. Do not deviate from this format.`,r=`Please process this freewriting text according to the format requirements: ${t}`,y={model:e,max_tokens:u.DEFAULT_MAX_OUTPUT_TOKENS,messages:[{role:"user",content:[{type:"text",text:r}]}],system:[{type:"text",text:o}]},N=await this.makeRequestWithRetry(y),K=this.extractTextFromResponse(N);return{...this.parseStructuredResponse(K,s),usage:N.usage}}async testConnection(t){if(!this.validateApiKey())return{success:!1,message:"API key is empty or invalid format",error:"INVALID_KEY_FORMAT"};let e=Date.now(),n={model:t,max_tokens:50,messages:[{role:"user",content:[{type:"text",text:'Hello! Please respond with just "Test successful."'}]}],system:[{type:"text",text:'You are a test assistant. Respond only with "Test successful." and nothing else.'}]};try{let s=await this.makeRequest(n),i=Date.now()-e;return{success:!0,message:"API connection successful",details:{model:s.model,responseTime:i,inputTokens:s.usage.input_tokens,outputTokens:s.usage.output_tokens}}}catch(s){return{success:!1,message:s instanceof Error?s.message:"Unknown error",error:"CONNECTION_FAILED"}}}async makeRequestWithRetry(t){let e=new Error("No attempts made");for(let n=1;n<=this.MAX_RETRIES;n++)try{return await this.makeRequest(t)}catch(s){if(e=s instanceof Error?s:new Error("Unknown error"),s instanceof m||s instanceof E||s instanceof w&&s.status&&s.status>=400&&s.status<500&&s.status!==429)throw s;if(n=300)throw new w(`Models API request failed: ${t.status} ${t.text}`,t.status,t.text);return t.json}catch(t){throw t instanceof Error?t:new T(`Network request failed: ${String(t)}`)}}async makeRequest(t){try{let e=await(0,I.requestUrl)({url:this.messagesUrl,method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":"2023-06-01"},body:JSON.stringify(t)});if(e.status<200||e.status>=300){let n=e.text||"Unknown error";throw e.status===401||e.status===403?new m("API key is invalid or unauthorized."):e.status===429?new C("Rate limited by API. Please retry shortly."):new w(`API request failed (${e.status}): ${n}`,e.status,n)}return e.json}catch(e){throw e instanceof Error?e:new T(`Network request failed: ${String(e)}`)}}extractTextFromResponse(t){if(!t.content||t.content.length===0)throw new g("No content received from API");let e=t.content.map(n=>{var s;return(s=n.text)!=null?s:""}).join("").trim();if(!e)throw new g("Empty response from API");return e}sleep(t){return new Promise(e=>setTimeout(e,t))}updateApiKey(t){this.apiKey=t}validateApiKey(){return!!(this.apiKey&&this.apiKey.trim().length>0)}};var v=class{get anthropicClient(){return this.client}constructor(t){this.client=new S(t)}async cleanupText(t,e){var s,i;if(!t||t.trim().length===0)throw new Error("No text selected for cleanup");if(!this.client.validateApiKey())throw new m("API key is not configured. Please check your plugin settings.");if(t.length>u.MAX_CHARACTERS)throw new f(`Selected text is too long (${t.length} characters). Maximum allowed: ${u.MAX_CHARACTERS} characters.`);let n=Date.now();try{let{cleanedText:p,commentary:a,usage:o}=await this.client.cleanupText(t,e.model,e.cleanupPrompt,e.enableCommentary,e.commentaryStyle,e.customCommentaryPrompt),r=Date.now()-n;return{originalText:t,cleanedText:p,commentary:a,timestamp:new Date,model:e.model,tokensUsed:{input:(s=o==null?void 0:o.input_tokens)!=null?s:0,output:(i=o==null?void 0:o.output_tokens)!=null?i:0},duration:r}}catch(p){throw p}}async testConnection(t){if(!this.client.validateApiKey())return{success:!1,message:"API key is not configured"};try{return await this.client.testConnection(t.model)}catch(e){return{success:!1,message:e instanceof Error?e.message:"Unknown error"}}}formatCleanupResult(t){let e=` --- AI Cleanup: ${t.cleanedText}`;return t.commentary&&(e+=` --- AI Commentary: ${t.commentary}`),e}updateApiKey(t){this.client.updateApiKey(t)}validateSettings(t){let e=[];return(!t.apiKey||t.apiKey.trim().length===0)&&e.push("API key is required"),t.model||e.push("Model selection is required"),(!t.cleanupPrompt||t.cleanupPrompt.trim().length===0)&&e.push("Cleanup prompt is required"),t.enableCommentary&&t.commentaryStyle==="custom"&&(!t.customCommentaryPrompt||t.customCommentaryPrompt.trim().length===0)&&e.push('Custom commentary prompt is required when commentary style is "custom"'),{isValid:e.length===0,errors:e}}static getCharacterCount(t){return t.length}static estimateTokenCount(t){let e=Math.ceil(t.length/4);return Math.ceil(e*1.1)}static isWithinLimits(t){let e=this.getCharacterCount(t),n=this.estimateTokenCount(t);return{withinCharacterLimit:e<=u.MAX_CHARACTERS,withinTokenLimit:n<=u.MAX_TOKENS,characterCount:e,estimatedTokenCount:n}}};var L=require("obsidian");var M=class{constructor(t){this.modelCache=null;this.CACHE_TTL_MS=24*60*60*1e3;this.lastErrorNoticeTime=0;this.ERROR_NOTICE_THROTTLE_MS=60*1e3;this.anthropicClient=t}toModelInfo(t){return{id:t.id,display_name:t.displayName,created_at:"",type:"model"}}async getAvailableModels(){if(this.isCacheValid()&&this.modelCache)return this.formatModels(this.modelCache.models);if(!this.anthropicClient.validateApiKey())return this.cacheFallbackModels();try{let t=await this.anthropicClient.fetchModels();return this.updateCache(t.data),this.formatModels(t.data)}catch(t){return console.error("Failed to fetch models from API:",t),this.showThrottledErrorNotice(),this.cacheFallbackModels()}}async refreshModels(){if(!this.anthropicClient.validateApiKey())return this.cacheFallbackModels();try{let t=await this.anthropicClient.fetchModels();return this.updateCache(t.data),this.formatModels(t.data)}catch(t){return console.error("Failed to refresh models from API:",t),this.showThrottledErrorNotice(),this.cacheFallbackModels()}}loadCache(t){this.modelCache=t}getCache(){return this.modelCache}clearCache(){this.modelCache=null}getFallbackOptions(){return this.getFallbackModels()}cacheFallbackModels(){let t=this.getFallbackModels();return this.updateCache(t.map(e=>this.toModelInfo(e))),t}showThrottledErrorNotice(){let t=Date.now();t-this.lastErrorNoticeTime>this.ERROR_NOTICE_THROTTLE_MS&&(new L.Notice("Fetching current models failed. Using hardcoded fallback list."),this.lastErrorNoticeTime=t)}isCacheValid(){return this.modelCache?Date.now()-this.modelCache.fetchedAt({id:e.id,displayName:e.display_name})).sort((e,n)=>e.displayName.localeCompare(n.displayName))}getFallbackModels(){return _.map(t=>({id:t,displayName:t}))}};var d=require("obsidian");var b=class{constructor(t){this.cleanupService=t}async execute(t,e,n){try{let s=t.getSelection(),i=this.validateSelection(s);if(!i.isValid){new d.Notice(i.error||"Invalid text selection");return}let p=new d.Notice("Cleaning up text...",0);try{let a=await this.cleanupService.cleanupText(s,n),o=this.cleanupService.formatCleanupResult(a),r=t.getCursor("to"),y={line:r.line,ch:t.getLine(r.line).length};t.setCursor(y),t.replaceRange(o,y),new d.Notice(`Text cleanup completed in ${(a.duration/1e3).toFixed(1)}s`)}catch(a){a instanceof m?new d.Notice("API key error. Please check your settings."):a instanceof f?new d.Notice(a.message):a instanceof w?a.status===401||a.status===403?new d.Notice("API key was rejected by the server. Please verify your key."):a.status===429?new d.Notice("Rate limited by API. Please wait and try again."):new d.Notice(`API error (${a.status}): ${a.message}`):a instanceof C?new d.Notice(a.message):a instanceof g?new d.Notice("Received an unexpected response from Claude. Please try again."):a instanceof T?new d.Notice("Network error. Check your connection and try again."):a instanceof Error?new d.Notice(`Cleanup failed: ${a.message}`):new d.Notice("An unexpected error occurred during cleanup."),console.error("Cleanup command error:",a)}finally{p.hide()}}catch(s){console.error("Error in cleanup command:",s)}}validateSelection(t){if(!t||t.trim().length===0)return{isValid:!1,error:"No text selected"};let e=v.isWithinLimits(t);return e.withinCharacterLimit?e.withinTokenLimit?{isValid:!0}:{isValid:!1,error:`Text too long: ~${e.estimatedTokenCount.toLocaleString()} tokens (max: ${u.MAX_TOKENS.toLocaleString()})`}:{isValid:!1,error:`Text too long: ${e.characterCount.toLocaleString()} characters (max: ${u.MAX_CHARACTERS.toLocaleString()})`}}};var R=class extends F.Plugin{async onload(){let e=await this.loadSettings();this.cleanupService=new v(this.settings.apiKey),this.modelService=new M(this.cleanupService.anthropicClient),this.cleanupCommand=new b(this.cleanupService),e!=null&&e.modelCache&&this.modelService.loadCache(e.modelCache),this.registerCommand(),this.addSettingTab(new x(this.app,this))}onunload(){}async loadSettings(){let e=await this.loadData(),{modelCache:n,...s}=e!=null?e:{};return this.settings={...D,...s},e}async saveSettings(){var n;let e={...this.settings,modelCache:((n=this.modelService)==null?void 0:n.getCache())||void 0};await this.saveData(e),this.cleanupService&&this.cleanupService.updateApiKey(this.settings.apiKey)}registerCommand(){this.addCommand({id:"freewriting-cleanup-cleanup-text",name:"Clean up text",editorCallback:async(e,n)=>{await this.executeCleanupCommand(e,n)}})}async executeCleanupCommand(e,n){try{await this.cleanupCommand.execute(e,n,this.settings)}catch(s){console.error("Error executing cleanup command:",s)}}};