Files
StudyDiary/.obsidian/plugins/obsidian42-brat/main.js

45 lines
78 KiB
JavaScript
Raw Normal View History

2025-10-25 20:35:10 +08:00
"use strict";var Qt=Object.create;var de=Object.defineProperty;var Jt=Object.getOwnPropertyDescriptor;var Zt=Object.getOwnPropertyNames;var es=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var $=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ss=(o,e)=>{for(var t in e)de(o,t,{get:e[t],enumerable:!0})},We=(o,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Zt(e))!ts.call(o,i)&&i!==t&&de(o,i,{get:()=>e[i],enumerable:!(s=Jt(e,i))||s.enumerable});return o};var is=(o,e,t)=>(t=o!=null?Qt(es(o)):{},We(e||!o||!o.__esModule?de(t,"default",{value:o,enumerable:!0}):t,o)),ns=o=>We(de({},"__esModule",{value:!0}),o);var ke=$((ri,Qe)=>{"use strict";var os=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...o)=>console.error("SEMVER",...o):()=>{};Qe.exports=os});var De=$((ai,Je)=>{"use strict";var rs="2.0.0",as=Number.MAX_SAFE_INTEGER||9007199254740991,ls=16,us=250,cs=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Je.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:ls,MAX_SAFE_BUILD_LENGTH:us,MAX_SAFE_INTEGER:as,RELEASE_TYPES:cs,SEMVER_SPEC_VERSION:rs,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Se=$((O,Ze)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:xe,MAX_SAFE_BUILD_LENGTH:gs,MAX_LENGTH:ds}=De(),ps=ke();O=Ze.exports={};var ms=O.re=[],hs=O.safeRe=[],g=O.src=[],fs=O.safeSrc=[],d=O.t={},bs=0,$e="[a-zA-Z0-9-]",ws=[["\\s",1],["\\d",ds],[$e,gs]],Ts=o=>{for(let[e,t]of ws)o=o.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return o},b=(o,e,t)=>{let s=Ts(e),i=bs++;ps(o,i,e),d[o]=i,g[i]=e,fs[i]=s,ms[i]=new RegExp(e,t?"g":void 0),hs[i]=new RegExp(s,t?"g":void 0)};b("NUMERICIDENTIFIER","0|[1-9]\\d*");b("NUMERICIDENTIFIERLOOSE","\\d+");b("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${$e}*`);b("MAINVERSION",`(${g[d.NUMERICIDENTIFIER]})\\.(${g[d.NUMERICIDENTIFIER]})\\.(${g[d.NUMERICIDENTIFIER]})`);b("MAINVERSIONLOOSE",`(${g[d.NUMERICIDENTIFIERLOOSE]})\\.(${g[d.NUMERICIDENTIFIERLOOSE]})\\.(${g[d.NUMERICIDENTIFIERLOOSE]})`);b("PRERELEASEIDENTIFIER",`(?:${g[d.NONNUMERICIDENTIFIER]}|${g[d.NUMERICIDENTIFIER]})`);b("PRERELEASEIDENTIFIERLOOSE",`(?:${g[d.NONNUMERICIDENTIFIER]}|${g[d.NUMERICIDENTIFIERLOOSE]})`);b("PRERELEASE",`(?:-(${g[d.PRERELEASEIDENTIFIER]}(?:\\.${g[d.PRERELEASEIDENTIFIER]})*))`);b("PRERELEASELOOSE",`(?:-?(${g[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${g[d.PRERELEASEIDENTIFIERLOOSE]})*))`);b("BUILDIDENTIFIER",`${$e}+`);b("BUILD",`(?:\\+(${g[d.BUILDIDENTIFIER]}(?:\\.${g[d.BUILDIDENTIFIER]})*))`);b("FULLPLAIN",`v?${g[d.MAINVERSION]}${g[d.PRERELEASE]}?${g[d.BUILD]}?`);b("FULL",`^${g[d.FULLPLAIN]}$`);b("LOOSEPLAIN",`[v=\\s]*${g[d.MAINVERSIONLOOSE]}${g[d.PRERELEASELOOSE]}?${g[d.BUILD]}?`);b("LOOSE",`^${g[d.LOOSEPLAIN]}$`);b("GTLT","((?:<|>)?=?)");b("XRANGEIDENTIFIERLOOSE",`${g[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);b("XRANGEIDENTIFIER",`${g[d.NUMERICIDENTIFIER]}|x|X|\\*`);b("XRANGEPLAIN",`[v=\\s]*(${g[d.XRANGEIDENTIFIER]})(?:\\.(${g[d.XRANGEIDENTIFIER]})(?:\\.(${g[d.XRANGEIDENTIFIER]})(?:${g[d.PRERELEASE]})?${g[d.BUILD]}?)?)?`);b("XRANGEPLAINLOOSE",`[v=\\s]*(${g[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${g[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${g[d.XRANGEIDENTIFIERLOOSE]})(?:${g[d.PRERELEASELOOSE]})?${g[d.BUILD]}?)?)?`);b("XRANGE",`^${g[d.GTLT]}\\s*${g[d.XRANGEPLAIN]}$`);b("XRANGELOOSE",`^${g[d.GTLT]}\\s*${g[d.XRANGEPLAINLOOSE]}$`);b("COERCEPLAIN",`(^|[^\\d])(\\d{1,${xe}})(?:\\.(\\d{1,${xe}}))?(?:\\.(\\d{1,${xe}}))?`);b("COERCE",`${g[d.COERCEPLAIN]}(?:$|[^\\d])`);b("COERCEFULL",g[d.COERCEPLAIN]+`(?:${g[d.PRERELEASE]})?(?:${g[d.BUILD]})?(?:$|[^\\d])`);b("COERCERTL",g[d.COERCE],!0);b("COERCERTLFULL",g[d.COERCEFULL],!0);b("LONETILDE","(?:~>?)");b("TILDETRIM",`(\\s*)${g[d.LONETILDE]}\\s+`,!0);O.tildeTrimReplace="$1~";b("TILDE",`^${g[d.LONETILDE]}${g[d.XRANGEPLAIN]}$`);b("TILDELOOSE",`^${g[d.LONETILDE]}${g[d.XRANGEPLAINLOOSE]}$`);b("LONECARET","(?:\\^)");b("CARETTRIM",`(\\s*)${g[d.LONECARET]}\\s+`,!0);O.caretTrimReplace="$1^";b("CARET",`^${g[d.LONECARET]}${g[d.XRANGEPLAIN]}$`);b("CARETLOOSE",`^${g[d.LONECARET]}${g[d.XRANGEPLAINL
GitHub API rate limit exceeded:`,`
Request: ${u.requestUrl}`,`
Rate limits - Remaining: ${u.remaining}`,`
Reset in: ${u.getMinutesToReset()} minutes`),u}throw e&&console.log("GitHub request failed:",n),r}};var Ue={pluginList:[],pluginSubListFrozenVersion:[],themesList:[],updateAtStartup:!0,updateThemesAtStartup:!0,enableAfterInstall:!0,loggingEnabled:!1,loggingPath:"BRAT-log",loggingVerboseEnabled:!1,debuggingMode:!1,notificationsEnabled:!0,personalAccessToken:"",selectLatestPluginVersionByDefault:!1,allowIncompatiblePlugins:!1};function vt(o,e,t="latest",s="",i=!1){let n=!1;o.settings.pluginList.contains(e)||(o.settings.pluginList.unshift(e),n=!0);let r=o.settings.pluginSubListFrozenVersion.find(a=>a.repo===e);r?(Object.assign(r,{repo:e,version:t,token:s.trim()!==""?s:void 0,isIncompatible:i||void 0}),n=!0):(o.settings.pluginSubListFrozenVersion.unshift({repo:e,version:t,token:s||void 0,isIncompatible:i||void 0}),n=!0),n&&o.saveSettings()}function Pt(o,e){return o.settings.pluginList.contains(e)}function It(o,e,t){let s={repo:e,lastUpdate:K(t)};o.settings.themesList.unshift(s),o.saveSettings()}function Rt(o,e){return!!o.settings.themesList.find(s=>s.repo===e)}function At(o,e,t){for(let s of o.settings.themesList)s.repo===e&&(s.lastUpdate=t,o.saveSettings())}var N=require("obsidian");var G=class{constructor(e,t){this.tokenEl=e,this.statusEl=t}async validateToken(e,t){var s,i,n,r,a,u,l,c,p,m,E,T,h;if((s=this.tokenEl)==null||s.inputEl.removeClass("valid-input","invalid-input"),!e)return(i=this.statusEl)==null||i.setText("No token provided"),(n=this.statusEl)==null||n.addClass("invalid"),(r=this.statusEl)==null||r.removeClass("valid"),!1;try{let f=await ft(e,t);return(a=this.statusEl)==null||a.removeClass("invalid","valid"),(u=this.statusEl)==null||u.empty(),f.validToken?((l=this.tokenEl)==null||l.inputEl.addClass("valid-input"),(c=this.statusEl)==null||c.addClass("valid"),this.showValidTokenInfo(f),!0):((p=this.tokenEl)==null||p.inputEl.addClass("invalid-input"),(m=this.statusEl)==null||m.addClass("invalid"),this.showErrorMessage(f.error),!1)}catch(f){return console.error("Token validation error:",f),(E=this.tokenEl)==null||E.inputEl.addClass("invalid-input"),(T=this.statusEl)==null||T.setText("Failed to validate token"),(h=this.statusEl)==null||h.addClass("invalid"),!1}}showValidTokenInfo(e){var s,i;let t=(s=this.statusEl)==null?void 0:s.createDiv({cls:"brat-token-details"});if(t&&(t.createDiv({text:"\u2713 Valid token",cls:"brat-token-status valid"}),(i=e.currentScopes)!=null&&i.length&&t.createDiv({text:`Scopes: ${e.currentScopes.join(", ")}`,cls:"brat-token-scopes"}),e.rateLimit&&t.createDiv({text:`Rate Limit: ${e.rateLimit.remaining}/${e.rateLimit.limit}`,cls:"brat-token-rate"}),e.expirationDate)){let n=new Date(e.expirationDate),r=Math.ceil((n.getTime()-Date.now())/(1e3*60*60*24));r<7&&t.createDiv({text:`\u26A0\uFE0F Token expires in ${r} days`,cls:"brat-token-warning"})}}showErrorMessage(e){var s,i,n;let t=(s=this.statusEl)==null?void 0:s.createDiv({cls:"brat-token-error"});if(t&&(t.createDiv({text:e.message}),e.details))switch(e.type){case"invalid_prefix":t.createDiv({text:`Valid prefixes: ${(i=e.details.validPrefixes)==null?void 0:i.join(", ")}`});break;case"insufficient_scope":t.createDiv({text:`Required scopes: ${(n=e.details.requiredScopes)==null?void 0:n.join(", ")}`});break}}};function Q(o,e){let t=new DocumentFragment,s=document.createElement("a");if(s.textContent=o,s.href=`https://github.com/${o}`,s.target="_blank",t.appendChild(s),e){let i=document.createTextNode(e);t.appendChild(i)}return t}function Ct({prependText:o,url:e,text:t,appendText:s}){let i=new DocumentFragment,n=document.createElement("a");if(n.textContent=t,n.href=e,o){let r=document.createTextNode(o);i.appendChild(r)}if(i.appendChild(n),s){let r=document.createTextNode(s);i.appendChild(r)}return i}var ve=require("obsidian");function w(o,e,t=10,s){if(!o.settings.notificationsEnabled)return;let i=s?ve.Platform.isDesktop?"(click=dismiss, right-click=Info)":"(click=dismiss)":"",n=new ve.Notice(`BRAT
${e}
${i}`,t*1e3);s&&(n.noticeEl.oncontextmenu=()=>{s()})}var j=(o,e=!0)=>{let t=o.createEl("div");t.style.float="right",e?(t.style.padding="15px",t.style.paddingLeft="15px",t.style.paddingRight="15px",t.style.marginLeft="15px"):(t.style.padding="10px",t.style.paddingLeft="15px",t.style.paddingRight="15px");let s=t.createDiv("coffee");s.addClass("ex-twitter-span"),s.style.paddingLeft="10px";let i=s.createDiv();i.innerText="Learn more about my work at:",s.appendChild(i);let n=s.createEl("a",{href:"https://tfthacker.com"});return n.innerText="https://tfthacker.com",t};var Nt=require("obsidian"),Pe=class extends Nt.SuggestModal{constructor(e,t,s,i,n){super(e),this.versions=s,this.selected=i,this.onChoose=n,this.setTitle("Select a version"),this.setPlaceholder(`Type to search for a version for ${t}`),this.setInstructions([{command:"\u2191\u2193",purpose:"Navigate versions"},{command:"\u21B5",purpose:"Select version"},{command:"esc",purpose:"Dismiss modal"}])}getSuggestions(e){let t=e.toLowerCase();return this.versions.filter(s=>s.version.toLowerCase().contains(t))}renderSuggestion(e,t){t.createEl("div",{text:`${e.version} ${e.prerelease?"(Prerelease)":""}`})}onChooseSuggestion(e){this.onChoose(e.version)}onNoSuggestion(){this.onChoose(this.selected?this.selected:""),this.close()}};var M=class extends N.Modal{constructor(t,s,i=!1,n=!1,r="",a="",u=""){super(t.app);this.versionSetting=null;this.repositoryAddressEl=null;this.tokenInputEl=null;this.validateButton=null;this.validator=null;this.addPluginButton=null;this.cancelButton=null;this.plugin=t,this.betaPlugins=s,this.address=r,this.version=a,this.privateApiKey=u,this.usePrivateApiKey=!(u===""||u===void 0),this.openSettingsTabAfterwards=i,this.updateVersion=n,this.enableAfterInstall=t.settings.enableAfterInstall}async submitForm(){var n,r,a,u,l,c,p,m;if(this.address==="")return;let t=Ee(this.address);if(this.plugin.settings.pluginSubListFrozenVersion.find(E=>E.repo===t)){await this.betaPlugins.addPlugin(t,!1,!1,!1,this.version,!0,this.enableAfterInstall,this.usePrivateApiKey?this.privateApiKey:void 0)&&this.close(),(n=this.cancelButton)==null||n.setDisabled(!1),(r=this.addPluginButton)==null||r.setDisabled(!1),(a=this.addPluginButton)==null||a.setButtonText("Add Plugin"),(u=this.versionSetting)==null||u.setDisabled(!1);return}if(!this.version&&Pt(this.plugin,t)){w(this.plugin,"This plugin is already in the list for beta testing",10);return}await this.betaPlugins.addPlugin(t,!1,!1,!1,this.version,!1,this.enableAfterInstall,this.usePrivateApiKey?this.privateApiKey:void 0)&&this.close(),(l=this.cancelButton)==null||l.setDisabled(!1),(c=this.addPluginButton)==null||c.setDisabled(!1),(p=this.addPluginButton)==null||p.setButtonText("Add Plugin"),(m=this.versionSetting)==null||m.setDisabled(!1)}updateVersionDropdown(t,s,i=""){let n;t.clear(),s.length>0&&!i&&this.plugin.settings.selectLatestPluginVersionByDefault?(n="latest",this.version="latest"):n=i,s.length<20||N.Platform.isMobile?t.addDropdown(a=>{a.addOption("","Select a version"),a.addOption("latest","Latest version");for(let u of s)a.addOption(u.version,`${u.version} ${u.prerelease?"(Prerelease)":""}`);a.onChange(u=>{var l;this.version=u,(l=this.addPluginButton)==null||l.setDisabled(this.version==="")}),a.setValue(n),a.selectEl.addClass("brat-version-selector"),a.selectEl.style.width="100%"}):t.addButton(a=>{a.setButtonText(n==="latest"?"Latest version":n||"Select a version...").setClass("brat-version-selector").setClass("button").onClick(u=>{u.preventDefault();let c=[{version:"latest",prerelease:!1},...s];new Pe(this.app,this.address,c,n,m=>{var E;this.version=m,a.setButtonText(m==="latest"?"Latest version":m||"Select a version..."),(E=this.addPluginButton)==null||E.setDisabled(this.version==="")}).open()})})}onOpen(){let t=this.contentEl.createEl("h4");this.address?(t.appendText("Change plugin version: "),t.appendChild(Q(this.address))):t.setText("Github repository for beta plugin:"),this.contentEl.createEl("form",{},s=>{s.addClass("brat-modal"),(!this.address||!this.updateVersion)&&new N.Setting(s).setClass("repository-setting
This does not seem to be an obsidian plugin with valid releases, as there are no releases available.`,15),console.error("BRAT: validateRepository",e,t,s)),null;let l=await Y(u,"manifest.json",this.plugin.settings.debuggingMode,a,n||this.plugin.settings.personalAccessToken);if(!l)return s&&(w(this.plugin,`${e}
This does not seem to be an obsidian plugin, as there is no manifest.json file.`,15),console.error("BRAT: validateRepository",e,t,s)),null;let c=JSON.parse(l);if(!("id"in c))return s&&w(this.plugin,`${e}
The plugin id attribute for the release is missing from the manifest file`,15),null;if(!("version"in c))return s&&w(this.plugin,`${e}
The version attribute for the release is missing from the manifest file`,15),null;let p=Re(u.tag_name,{includePrerelease:!0,loose:!0}),m=Re(c.version,{includePrerelease:!0,loose:!0});return kt(p,m)!==0&&(s&&w(this.plugin,`${e}
Version mismatch detected:
Release tag version: ${u.tag_name}
Manifest version: ${c.version}
The release tag version will be used to ensure consistency.`,15),c.version=p.version),c}catch(a){if(a instanceof D){let u=`GitHub API rate limit exceeded. Reset in ${a.getMinutesToReset()} minutes.`;throw s&&w(this.plugin,u,15),console.error(`BRAT: validateRepository ${a}`),w(this.plugin,`${a.message} Consider adding a personal access token in BRAT settings for higher limits. See documentation for details.`,20,()=>{window.open("https://github.com/TfTHacker/obsidian42-brat/blob/main/BRAT-DEVELOPER-GUIDE.md#github-api-rate-limits")}),a}if(a instanceof S)throw s&&(a.status===401?w(this.plugin,`${e}
GitHub API Authentication error. Please verify that your personal access token is valid and set correctly.`,15):w(this.plugin,`${e}
GitHub API error ${a.status}: ${a.message}`,15)),console.error(`BRAT: validateRepository ${a}`),a;return s&&w(this.plugin,`${e}
Unspecified error encountered: ${a}, verify debug for more information.`,15),null}}async getAllReleaseFiles(e,t,s,i="",n=""){let r=await Me(e,this.plugin.settings.debuggingMode,n),a=await Ve(e,i,s,this.plugin.settings.debuggingMode,r,n||this.plugin.settings.personalAccessToken);if(!a)return Promise.reject("No release found");let u=s||i!=="";return console.log({reallyGetManifestOrNot:u,version:a.tag_name}),{mainJs:await Y(a,"main.js",this.plugin.settings.debuggingMode,r,n||this.plugin.settings.personalAccessToken),manifest:u?await Y(a,"manifest.json",this.plugin.settings.debuggingMode,r,n||this.plugin.settings.personalAccessToken):"",styles:await Y(a,"styles.css",this.plugin.settings.debuggingMode,r,n||this.plugin.settings.personalAccessToken)}}async writeReleaseFilesToPluginFolder(e,t){var n,r;let s=`${(0,L.normalizePath)(`${this.plugin.app.vault.configDir}/plugins/${e}`)}/`,{adapter:i}=this.plugin.app.vault;await i.exists(s)||await i.mkdir(s),await i.write(`${s}main.js`,(n=t.mainJs)!=null?n:""),await i.write(`${s}manifest.json`,(r=t.manifest)!=null?r:""),t.styles&&await i.write(`${s}styles.css`,t.styles)}async addPlugin(e,t=!1,s=!1,i=!1,n="",r=!1,a=this.plugin.settings.enableAfterInstall,u=""){try{this.plugin.settings.debuggingMode&&console.log("BRAT: addPlugin",e,t,s,i,n,r,a,u?"private":"public");let l=10,c=await this.validateRepository(e,!0,!0,n,u),p=!!c;if(p||(c=await this.validateRepository(e,!1,!0,n,u)),c===null){let T=`${e}
A manifest.json file does not exist in the latest release of the repository. This plugin cannot be installed.`;return await this.plugin.log(T,!0),w(this.plugin,T,l),!1}if(!Object.hasOwn(c,"version")){let T=`${e}
The manifest.json file in the latest release or pre-release of the repository does not have a version number in the file. This plugin cannot be installed.`;return await this.plugin.log(T,!0),w(this.plugin,T,l),!1}let m=!1;if(Object.hasOwn(c,"minAppVersion")&&!(0,L.requireApiVersion)(c.minAppVersion)){if(n===""||n==="latest"||!this.plugin.settings.allowIncompatiblePlugins){let h=`Plugin: ${e}
The manifest.json for this plugin indicates that the Obsidian version of the app needs to be ${c.minAppVersion}, but this installation of Obsidian is ${L.apiVersion}.
You will need to update your Obsidian to use this plugin or contact the plugin developer for more information.`;return await this.plugin.log(h,!0),w(this.plugin,h,30),!1}if(!await _e({app:this.plugin.app,message:createFragment(h=>{h.appendText("Plugin: "),h.createEl("code",{text:e}),h.createEl("br"),h.appendText("The "),h.createEl("code",{text:"manifest.json"}),h.appendText(" for this plugin indicates that the Obsidian version of the app needs to be "),h.createEl("code",{text:c.minAppVersion}),h.appendText(", but this installation of Obsidian is "),h.createEl("code",{text:L.apiVersion}),h.appendText("."),h.createEl("br"),h.appendText("Using this plugin is not recommended and may not work as expected. Use at your own risk."),h.createEl("br"),h.appendText("Do you want to install it anyways?")})}))return!1;m=!0}let E=async()=>{var f,v;let T=await this.getAllReleaseFiles(e,c,p,n,u);console.log("rFiles",T),(p||T.manifest==="")&&(T.manifest=JSON.stringify(c));let h=JSON.parse((f=T.manifest)!=null?f:"");if(m&&(h.brat={isIncompatible:!0,minAppVersionOriginal:h.minAppVersion},h.minAppVersion=L.apiVersion),L.Platform.isMobile&&h.isDesktopOnly)if(this.plugin.settings.allowIncompatiblePlugins){if(!await _e({app:this.plugin.app,message:createFragment(P=>{P.appendText("Plugin: "),P.createEl("code",{text:e}),P.createEl("br"),P.appendText("The "),P.createEl("code",{text:"manifest.json"}),P.appendText(" for this plugin indicates that the plugin has "),P.createEl("code",{text:"isDesktopOnly: true"}),P.appendText(", but you are using a mobile device."),P.createEl("br"),P.appendText("Using this plugin is not recommended and may not work as expected. Use at your own risk."),P.createEl("br"),P.appendText("Do you want to forcefully run it on mobile anyways?")})}))return null;h.isDesktopOnly=!1,(v=h.brat)!=null||(h.brat={}),h.brat.isDesktopOnlyOriginal=!0,h.brat.isIncompatible=!0,m=!0}else{let C=`Plugin: ${e}
The manifest.json for this plugin indicates that the plugin has isDesktopOnly: true, but you are using a mobile device.
The plugin will not be installed.`;return await this.plugin.log(C,!0),w(this.plugin,C,30),null}if(m&&(T.manifest=JSON.stringify(h)),this.plugin.settings.debuggingMode&&console.log("BRAT: rFiles.manifest",p,T),T.mainJs===null){let C=`${e}
The release is not complete and cannot be downloaded. main.js is missing from the Release`;return await this.plugin.log(C,!0),w(this.plugin,C,l),null}return T};if(!t||r){let T=await E();if(T===null)return!1;if(await this.writeReleaseFilesToPluginFolder(c.id,T),vt(this.plugin,e,n,u,m),a){let{plugins:h}=this.plugin.app,f=(0,L.normalizePath)(`${h.getPluginFolder()}/${c.id}`);await h.loadManifest(f),await h.enablePluginAndSave(c.id)}if(await this.plugin.app.plugins.loadManifests(),r)await this.reloadPlugin(c.id),await this.plugin.log(`${e} reinstalled`,!0),w(this.plugin,`${e}
Plugin has been reinstalled and reloaded with version ${c.version}`,l);else{let h=n===""?"":` (version: ${n})`,f=`${e}${h}
The plugin has been registered with BRAT.`;a||(f+=" You may still need to enable it the Community Plugin List."),await this.plugin.log(f,!0),w(this.plugin,f,l)}}else{let T=`${this.plugin.app.vault.configDir}/plugins/${c.id}/`,h="";try{h=await this.plugin.app.vault.adapter.read(`${T}manifest.json`)}catch(P){if(P.errno===-4058||P.errno===-2)return await this.addPlugin(e,!1,p,!1,n,!1,a,u),!0;console.log("BRAT - Local Manifest Load",c.id,JSON.stringify(P,null,2))}if(n!==""&&n!=="latest")return w(this.plugin,`The version of ${e} is frozen, not updating.`,3),!1;let f=await JSON.parse(h),v=Re(f.version,{includePrerelease:!0,loose:!0}),C=Re(c.version,{includePrerelease:!0,loose:!0});if(kt(v,C)===-1){let P=await E();if(P===null)return!1;if(s){let A=`There is an update available for ${c.id} from version ${f.version} to ${c.version}. `;return await this.plugin.log(`${A}[Release Info](https://github.com/${e}/releases/tag/${c.version})`,!0),w(this.plugin,A,30,()=>{c&&window.open(`https://github.com/${e}/releases/tag/${c.version}`)}),!1}await this.writeReleaseFilesToPluginFolder(c.id,P),await this.plugin.app.plugins.loadManifests(),await this.reloadPlugin(c.id);let ge=`${c.id}
Plugin has been updated from version ${f.version} to ${c.version}. `;return await this.plugin.log(`${ge}[Release Info](https://github.com/${e}/releases/tag/${c.version})`,!0),w(this.plugin,ge,30,()=>{c&&window.open(`https://github.com/${e}/releases/tag/${c.version}`)}),!0}return i&&w(this.plugin,`No update available for ${e}`,3),!0}}catch(l){console.error(`BRAT: Error adding plugin ${e}:`,{error:l,updatePluginFiles:t,seeIfUpdatedOnly:s,specifyVersion:n,forceReinstall:r});let c=l instanceof Error?l.message:"Unknown error occurred";return await this.plugin.log(`Error ${t?"updating":"adding"} plugin ${e}: ${c}`,!0),!1}return!0}async reloadPlugin(e){let{plugins:t}=this.plugin.app;try{await t.disablePlugin(e),await t.enablePlugin(e)}catch(s){this.plugin.settings.debuggingMode&&console.log("reload plugin",s)}}async updatePlugin(e,t=!1,s=!1,i=!1,n=""){let r=await this.addPlugin(e,!0,t,s,"",i,!1,n);return!r&&!t&&w(this.plugin,`${e}
Update of plugin failed.`),r}async checkForPluginUpdatesAndInstallUpdates(e=!1,t=!1){var a,u;if(!await Ie()){console.log("BRAT: No internet detected.");return}let s,i="Checking for plugin updates STARTED";await this.plugin.log(i,!0),e&&this.plugin.settings.notificationsEnabled&&(s=new L.Notice(`BRAT
${i}`,3e4));let n=new Map(this.plugin.settings.pluginSubListFrozenVersion.map(l=>[l.repo,{version:l.version,token:l.token}]));for(let l of this.plugin.settings.pluginList)n.has(l)&&((a=n.get(l))==null?void 0:a.version)!=="latest"||await this.updatePlugin(l,t,!1,!1,(u=n.get(l))==null?void 0:u.token);let r="Checking for plugin updates COMPLETED";await this.plugin.log(r,!0),e&&(s&&s.hide(),w(this.plugin,r,10))}deletePlugin(e){let t=`Removed ${e} from BRAT plugin list`;this.plugin.log(t,!0),this.plugin.settings.pluginList=this.plugin.settings.pluginList.filter(s=>s!==e),this.plugin.settings.pluginSubListFrozenVersion=this.plugin.settings.pluginSubListFrozenVersion.filter(s=>s.repo!==e),this.plugin.saveSettings()}getEnabledDisabledPlugins(e){let t=this.plugin.app.plugins,s=Object.values(t.manifests),i=Object.values(t.plugins).map(n=>n.manifest);return e?s.filter(n=>i.find(r=>n.id===r.id)):s.filter(n=>!i.find(r=>n.id===r.id))}checkIncompatiblePlugins(){let e=this.plugin.settings.pluginSubListFrozenVersion.filter(t=>t.isIncompatible).map(t=>t.repo);e.length>0&&w(this.plugin,`The following incompatible plugins were forcefully installed by BRAT and may not work as expected:
${e.join(`
`)}`,30)}};var V=require("obsidian");var ee=async(o,e,t)=>{let s=await _(e,!0,o.settings.debuggingMode);if(s||(s=await _(e,!1,o.settings.debuggingMode)),!s)return w(o,"There is no theme.css or theme-beta.css file in the root path of this repository, so there is no theme to install."),!1;let i=await Et(e,o.settings.debuggingMode);if(!i)return w(o,"There is no manifest.json file in the root path of this repository, so theme cannot be installed."),!1;let n=await JSON.parse(i),r=(0,V.normalizePath)(Ss(o)+n.name),{adapter:a}=o.app.vault;await a.exists(r)||await a.mkdir(r),await a.write((0,V.normalizePath)(`${r}/theme.css`),s),await a.write((0,V.normalizePath)(`${r}/manifest.json`),i),At(o,e,K(s));let u="";return t?(It(o,e,s),u=`${n.name} theme installed from ${e}. `,setTimeout(()=>{o.app.customCss.setTheme(n.name)},500)):u=`${n.name} theme updated from ${e}.`,o.log(`${u}[Theme Info](https://github.com/${e})`,!1),w(o,u,20,()=>{window.open(`https://github.com/${e}`)}),!0},q=async(o,e)=>{if(!await Ie()){console.log("BRAT: No internet detected.");return}let t,s="Checking for beta theme updates STARTED";await o.log(s,!0),e&&o.settings.notificationsEnabled&&(t=new V.Notice(`BRAT
${s}`,3e4));for(let n of o.settings.themesList){let r=await W(n.repo,!0,o.settings.debuggingMode);r==="0"&&(r=await W(n.repo,!1,o.settings.debuggingMode)),console.log("BRAT: lastUpdateOnline",r),r!==n.lastUpdate&&await ee(o,n.repo,!1)}let i="Checking for beta theme updates COMPLETED";(async()=>await o.log(i,!0))(),e&&(o.settings.notificationsEnabled&&t&&t.hide(),w(o,i))},Ae=(o,e)=>{o.settings.themesList=o.settings.themesList.filter(s=>s.repo!==e),o.saveSettings();let t=`Removed ${e} from BRAT themes list and will no longer be updated. However, the theme files still exist in the vault. To remove them, go into Settings > Appearance and remove the theme.`;o.log(t,!0),w(o,t)},Ss=o=>`${(0,V.normalizePath)(`${o.app.vault.configDir}/themes`)}/`;var U=require("obsidian");var F=class extends U.Modal{constructor(e,t=!1){super(e.app),this.plugin=e,this.address="",this.openSettingsTabAfterwards=t}async submitForm(){if(this.address==="")return;let e=this.address.replace("https://github.com/","");if(Rt(this.plugin,e)){w(this.plugin,"This theme is already in the list for beta testing",10);return}await ee(this.plugin,e,!0)&&this.close()}onOpen(){this.contentEl.createEl("h4",{text:"Github repository for beta theme:"}),this.contentEl.createEl("form",{},e=>{e.addClass("brat-modal"),new U.Setting(e).addText(i=>{i.setPlaceholder("Repository (example: https://github.com/GitHubUserName/repository-name"),i.setValue(this.address),i.onChange(n=>{this.address=n.trim()}),i.inputEl.addEventListener("keydown",n=>{n.key==="Enter"&&this.address!==" "&&(n.preventDefault(),this.submitForm())}),i.inputEl.style.width="100%",window.setTimeout(()=>{let n=document.querySelector(".setting-item-info");n&&n.remove(),i.inputEl.focus()},10)}),e.createDiv("modal-button-container",i=>{new U.ButtonComponent(i).setButtonText("Never mind").onClick(()=>{this.close()}),new U.ButtonComponent(i).setButtonText("Add theme").setCta().onClick(n=>{n.preventDefault(),console.log("Add theme button clicked"),this.address!==""&&this.submitForm()})});let t=e.createDiv();t.style.borderTop="1px solid #ccc",t.style.marginTop="30px";let s=t.createSpan();s.innerHTML="BRAT by <a href='https://bit.ly/o42-twitter'>TFTHacker</a>",s.style.fontStyle="italic",t.appendChild(s),j(t,!1),window.setTimeout(()=>{let i=e.querySelectorAll(".brat-modal .setting-item-info");for(let n of Array.from(i))n.remove()},50)})}onClose(){this.openSettingsTabAfterwards&&(this.plugin.app.setting.openTab(),this.plugin.app.setting.openTabById(this.plugin.APP_ID))}};var Dt=require("obsidian"),k=class extends Dt.FuzzySuggestModal{constructor(t){super(t.app);this.data=[];this.scope.register(["Shift"],"Enter",s=>{this.enterTrigger(s)}),this.scope.register(["Ctrl"],"Enter",s=>{this.enterTrigger(s)})}setSuggesterData(t){this.data=t}display(t){this.callbackFunction=t,this.open()}getItems(){return this.data}getItemText(t){return t.display}onChooseItem(){}renderSuggestion(t,s){s.createEl("div",{text:t.item.display})}enterTrigger(t){var n;let s=(n=document.querySelector(".suggestion-item.is-selected div"))==null?void 0:n.textContent,i=this.data.find(r=>r.display===s);i&&(this.invokeCallback(i,t),this.close())}onChooseSuggestion(t,s){this.invokeCallback(t.item,s)}invokeCallback(t,s){typeof this.callbackFunction=="function"&&this.callbackFunction(t,s)}};var te=class{constructor(e){this.bratCommands=[{id:"AddBetaPlugin",icon:"BratIcon",name:"Plugins: Add a beta plugin for testing (with or without version)",showInRibbon:!0,callback:()=>{this.plugin.betaPlugins.displayAddNewPluginModal(!1,!0)}},{id:"checkForUpdatesAndUpdate",icon:"BratIcon",name:"Plugins: Check for updates to all beta plugins and UPDATE",showInRibbon:!0,callback:async()=>{await this.plugin.betaPlugins.checkForPluginUpdatesAndInstallUpdates(!0,!1)}},{id:"checkForUpdatesAndDontUpdate",icon:"BratIcon",name:"Plugins: Only check for updates to beta plugins, but don't Update",showInRibbon:!0,callback:async()=>{await this.plugin.betaPlugins.checkForPluginUpdatesAndInstallUpdates(!0,!0)}},{id:"updateOnePlugin",icon:"BratIcon",name:"Plugins: Choose a single plugin version t
${n}`,3),this.plugin.betaPlugins.updatePlugin(i.info,!1,!0,!1,r==null?void 0:r.token)})}},{id:"reinstallOnePlugin",icon:"BratIcon",name:"Plugins: Choose a single plugin to reinstall",showInRibbon:!0,callback:()=>{let e=new Set(this.plugin.settings.pluginSubListFrozenVersion.map(i=>i.repo)),t=Object.values(this.plugin.settings.pluginList).filter(i=>!e.has(i)).map(i=>({display:i,info:i})),s=new k(this.plugin);s.setSuggesterData(t),s.display(i=>{let n=`Reinstalling ${i.info}`;w(this.plugin,`
${n}`,3),this.plugin.log(n,!0),this.plugin.betaPlugins.updatePlugin(i.info,!1,!1,!0)})}},{id:"restartPlugin",icon:"BratIcon",name:"Plugins: Restart a plugin that is already installed",showInRibbon:!0,callback:()=>{let e=Object.values(this.plugin.app.plugins.manifests).map(s=>({display:s.id,info:s.id})),t=new k(this.plugin);t.setSuggesterData(e),t.display(s=>{w(this.plugin,`${s.info}
Plugin reloading .....`,5),this.plugin.betaPlugins.reloadPlugin(s.info)})}},{id:"disablePlugin",icon:"BratIcon",name:"Plugins: Disable a plugin - toggle it off",showInRibbon:!0,callback:()=>{let e=this.plugin.betaPlugins.getEnabledDisabledPlugins(!0).map(s=>({display:`${s.name} (${s.id})`,info:s.id})),t=new k(this.plugin);t.setSuggesterData(e),t.display(s=>{this.plugin.log(`${s.display} plugin disabled`,!1),this.plugin.settings.debuggingMode&&console.log(s.info),this.plugin.app.plugins.disablePluginAndSave(s.info)})}},{id:"enablePlugin",icon:"BratIcon",name:"Plugins: Enable a plugin - toggle it on",showInRibbon:!0,callback:()=>{let e=this.plugin.betaPlugins.getEnabledDisabledPlugins(!1).map(s=>({display:`${s.name} (${s.id})`,info:s.id})),t=new k(this.plugin);t.setSuggesterData(e),t.display(s=>{this.plugin.log(`${s.display} plugin enabled`,!1),this.plugin.app.plugins.enablePluginAndSave(s.info)})}},{id:"openGitHubZRepository",icon:"BratIcon",name:"Plugins: Open the GitHub repository for a plugin",showInRibbon:!0,callback:async()=>{let e=await wt(this.plugin.settings.debuggingMode);if(e){let t=Object.values(e).map(n=>({display:`Plugin: ${n.name} (${n.repo})`,info:n.repo})),s=Object.values(this.plugin.settings.pluginList).map(n=>({display:`BRAT: ${n}`,info:n}));for(let n of t)s.push(n);let i=new k(this.plugin);i.setSuggesterData(s),i.display(n=>{n.info&&window.open(`https://github.com/${n.info}`)})}}},{id:"openGitHubRepoTheme",icon:"BratIcon",name:"Themes: Open the GitHub repository for a theme (appearance)",showInRibbon:!0,callback:async()=>{let e=await Tt(this.plugin.settings.debuggingMode);if(e){let t=Object.values(e).map(i=>({display:`Theme: ${i.name} (${i.repo})`,info:i.repo})),s=new k(this.plugin);s.setSuggesterData(t),s.display(i=>{i.info&&window.open(`https://github.com/${i.info}`)})}}},{id:"opentPluginSettings",icon:"BratIcon",name:"Plugins: Open Plugin Settings Tab",showInRibbon:!0,callback:()=>{let e=this.plugin.app.setting,t=Object.values(e.pluginTabs).map(n=>({display:`Plugin: ${n.name}`,info:n.id})),s=new k(this.plugin),i=Object.values(e.settingTabs).map(n=>({display:`Core: ${n.name}`,info:n.id}));for(let n of t)i.push(n);s.setSuggesterData(i),s.display(n=>{e.open(),e.openTabById(n.info)})}},{id:"GrabBetaTheme",icon:"BratIcon",name:"Themes: Grab a beta theme for testing from a Github repository",showInRibbon:!0,callback:()=>{new F(this.plugin).open()}},{id:"updateBetaThemes",icon:"BratIcon",name:"Themes: Update beta themes",showInRibbon:!0,callback:async()=>{await q(this.plugin,!0)}},{id:"allCommands",icon:"BratIcon",name:"All Commands list",showInRibbon:!1,callback:()=>{this.ribbonDisplayCommands()}}];this.plugin=e;for(let t of this.bratCommands)this.plugin.addCommand({id:t.id,name:t.name,icon:t.icon,callback:()=>{t.callback()}})}ribbonDisplayCommands(){let e=[];for(let r of this.bratCommands)r.showInRibbon&&e.push({display:r.name,info:r.callback});let t=new k(this.plugin),s=this.plugin.app.setting,i=Object.values(s.settingTabs).map(r=>({display:`Core: ${r.name}`,info:()=>{s.open(),s.openTabById(r.id)}})),n=Object.values(s.pluginTabs).map(r=>({display:`Plugin: ${r.name}`,info:()=>{s.open(),s.openTabById(r.id)}}));e.push({display:"---- Core Plugin Settings ----",info:()=>{this.ribbonDisplayCommands()}});for(let r of i)e.push(r);e.push({display:"---- Plugin Settings ----",info:()=>{this.ribbonDisplayCommands()}});for(let r of n)e.push(r);t.setSuggesterData(e),t.display(r=>{typeof r.info=="function"&&r.info()})}};var R=require("obsidian");var Ce=class extends R.PluginSettingTab{constructor(t,s){super(t,s);this.accessTokenSetting=null;this.accessTokenButton=null;this.tokenInfo=null;this.validator=null;this.plugin=s}display(){let{containerEl:t}=this;t.empty(),t.addClass("brat-settings"),new R.Setting(t).setName("Auto-enable plugins after installation").setDesc('If enabled beta plugins will be automatically enabled after installtion by default. Note: you can toggle this on and off for each plugin in the "Add Plugin" form.').addToggle(i=>{i.setValue(this.plugin.settings.enableAfterInstall).onChange(async n=>{this
`," ")}
`,u=o.app.vault.getAbstractFileByPath(s);u?await o.app.vault.append(u,a):u=await o.app.vault.create(s,a)}}var Ne=class extends Wt.Plugin{constructor(){super(...arguments);this.APP_NAME="BRAT";this.APP_ID="obsidian42-brat";this.settings=Ue;this.betaPlugins=new Z(this);this.commands=new te(this);this.bratApi=new se(this);this.obsidianProtocolHandler=t=>{if(!t.plugin&&!t.theme){w(this,"Could not locate the repository from the URL.",10);return}for(let s of["plugin","theme"])if(t[s]){let i;switch(s){case"plugin":i=new M(this,this.betaPlugins,!0,!1,t[s],t.version?t.version:void 0),i.open();break;case"theme":i=new F(this),i.address=t[s],i.open();break}return}}}onload(){console.log(`loading ${this.APP_NAME}`),$t(),this.addRibbonIcon("BratIcon","BRAT",()=>{this.commands.ribbonDisplayCommands()}),this.loadSettings().then(()=>{this.app.workspace.onLayoutReady(()=>{this.addSettingTab(new Ce(this.app,this)),this.registerObsidianProtocolHandler("brat",this.obsidianProtocolHandler),this.betaPlugins.checkIncompatiblePlugins(),this.settings.updateAtStartup&&setTimeout(()=>{this.betaPlugins.checkForPluginUpdatesAndInstallUpdates(!1)},6e4),this.settings.updateThemesAtStartup&&setTimeout(()=>{q(this,!1)},12e4),setTimeout(()=>{window.bratAPI=this.bratApi},500)})}).catch(t=>{console.error("Failed to load settings:",t)})}async log(t,s=!1){await Kt(this,t,s)}onunload(){console.log(`unloading ${this.APP_NAME}`)}async loadSettings(){this.settings=Object.assign({},Ue,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}};
/* nosourcemap */