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

39 lines
75 KiB
JavaScript
Raw Normal View History

2025-08-20 15:34:47 +08:00
"use strict";var Kt=Object.create;var ge=Object.defineProperty;var Wt=Object.getOwnPropertyDescriptor;var Qt=Object.getOwnPropertyNames;var Zt=Object.getPrototypeOf,Jt=Object.prototype.hasOwnProperty;var D=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),es=(n,e)=>{for(var t in e)ge(n,t,{get:e[t],enumerable:!0})},ze=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Qt(e))!Jt.call(n,i)&&i!==t&&ge(n,i,{get:()=>e[i],enumerable:!(s=Wt(e,i))||s.enumerable});return n};var ts=(n,e,t)=>(t=n!=null?Kt(Zt(n)):{},ze(e||!n||!n.__esModule?ge(t,"default",{value:n,enumerable:!0}):t,n)),ss=n=>ze(ge({},"__esModule",{value:!0}),n);var Le=D((ni,Xe)=>{var is=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...n)=>console.error("SEMVER",...n):()=>{};Xe.exports=is});var Ce=D((oi,Ye)=>{var ns="2.0.0",os=Number.MAX_SAFE_INTEGER||9007199254740991,rs=16,as=250,ls=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Ye.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:rs,MAX_SAFE_BUILD_LENGTH:as,MAX_SAFE_INTEGER:os,RELEASE_TYPES:ls,SEMVER_SPEC_VERSION:ns,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var De=D((x,Ke)=>{var{MAX_SAFE_COMPONENT_LENGTH:ke,MAX_SAFE_BUILD_LENGTH:us,MAX_LENGTH:cs}=Ce(),gs=Le();x=Ke.exports={};var ds=x.re=[],ps=x.safeRe=[],g=x.src=[],ms=x.safeSrc=[],d=x.t={},hs=0,$e="[a-zA-Z0-9-]",fs=[["\\s",1],["\\d",cs],[$e,us]],bs=n=>{for(let[e,t]of fs)n=n.split(`${e}*`).join(`${e}{0,${t}}`).split(`${e}+`).join(`${e}{1,${t}}`);return n},f=(n,e,t)=>{let s=bs(e),i=hs++;gs(n,i,e),d[n]=i,g[i]=e,ms[i]=s,ds[i]=new RegExp(e,t?"g":void 0),ps[i]=new RegExp(s,t?"g":void 0)};f("NUMERICIDENTIFIER","0|[1-9]\\d*");f("NUMERICIDENTIFIERLOOSE","\\d+");f("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${$e}*`);f("MAINVERSION",`(${g[d.NUMERICIDENTIFIER]})\\.(${g[d.NUMERICIDENTIFIER]})\\.(${g[d.NUMERICIDENTIFIER]})`);f("MAINVERSIONLOOSE",`(${g[d.NUMERICIDENTIFIERLOOSE]})\\.(${g[d.NUMERICIDENTIFIERLOOSE]})\\.(${g[d.NUMERICIDENTIFIERLOOSE]})`);f("PRERELEASEIDENTIFIER",`(?:${g[d.NUMERICIDENTIFIER]}|${g[d.NONNUMERICIDENTIFIER]})`);f("PRERELEASEIDENTIFIERLOOSE",`(?:${g[d.NUMERICIDENTIFIERLOOSE]}|${g[d.NONNUMERICIDENTIFIER]})`);f("PRERELEASE",`(?:-(${g[d.PRERELEASEIDENTIFIER]}(?:\\.${g[d.PRERELEASEIDENTIFIER]})*))`);f("PRERELEASELOOSE",`(?:-?(${g[d.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${g[d.PRERELEASEIDENTIFIERLOOSE]})*))`);f("BUILDIDENTIFIER",`${$e}+`);f("BUILD",`(?:\\+(${g[d.BUILDIDENTIFIER]}(?:\\.${g[d.BUILDIDENTIFIER]})*))`);f("FULLPLAIN",`v?${g[d.MAINVERSION]}${g[d.PRERELEASE]}?${g[d.BUILD]}?`);f("FULL",`^${g[d.FULLPLAIN]}$`);f("LOOSEPLAIN",`[v=\\s]*${g[d.MAINVERSIONLOOSE]}${g[d.PRERELEASELOOSE]}?${g[d.BUILD]}?`);f("LOOSE",`^${g[d.LOOSEPLAIN]}$`);f("GTLT","((?:<|>)?=?)");f("XRANGEIDENTIFIERLOOSE",`${g[d.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);f("XRANGEIDENTIFIER",`${g[d.NUMERICIDENTIFIER]}|x|X|\\*`);f("XRANGEPLAIN",`[v=\\s]*(${g[d.XRANGEIDENTIFIER]})(?:\\.(${g[d.XRANGEIDENTIFIER]})(?:\\.(${g[d.XRANGEIDENTIFIER]})(?:${g[d.PRERELEASE]})?${g[d.BUILD]}?)?)?`);f("XRANGEPLAINLOOSE",`[v=\\s]*(${g[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${g[d.XRANGEIDENTIFIERLOOSE]})(?:\\.(${g[d.XRANGEIDENTIFIERLOOSE]})(?:${g[d.PRERELEASELOOSE]})?${g[d.BUILD]}?)?)?`);f("XRANGE",`^${g[d.GTLT]}\\s*${g[d.XRANGEPLAIN]}$`);f("XRANGELOOSE",`^${g[d.GTLT]}\\s*${g[d.XRANGEPLAINLOOSE]}$`);f("COERCEPLAIN",`(^|[^\\d])(\\d{1,${ke}})(?:\\.(\\d{1,${ke}}))?(?:\\.(\\d{1,${ke}}))?`);f("COERCE",`${g[d.COERCEPLAIN]}(?:$|[^\\d])`);f("COERCEFULL",g[d.COERCEPLAIN]+`(?:${g[d.PRERELEASE]})?(?:${g[d.BUILD]})?(?:$|[^\\d])`);f("COERCERTL",g[d.COERCE],!0);f("COERCERTLFULL",g[d.COERCEFULL],!0);f("LONETILDE","(?:~>?)");f("TILDETRIM",`(\\s*)${g[d.LONETILDE]}\\s+`,!0);x.tildeTrimReplace="$1~";f("TILDE",`^${g[d.LONETILDE]}${g[d.XRANGEPLAIN]}$`);f("TILDELOOSE",`^${g[d.LONETILDE]}${g[d.XRANGEPLAINLOOSE]}$`);f("LONECARET","(?:\\^)");f("CARETTRIM",`(\\s*)${g[d.LONECARET]}\\s+`,!0);x.caretTrimReplace="$1^";f("CARET",`^${g[d.LONECARET]}${g[d.XRANGEPLAIN]}$`);f("CARETLOOSE",`^${g[d.LONECARET]}${g[d.XRANGEPLAINLOOSE]}$`);f("COMPARATORLOOSE",`^${g[d.G
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:",o),r}};var Me={pluginList:[],pluginSubListFrozenVersion:[],themesList:[],updateAtStartup:!0,updateThemesAtStartup:!0,enableAfterInstall:!0,loggingEnabled:!1,loggingPath:"BRAT-log",loggingVerboseEnabled:!1,debuggingMode:!1,notificationsEnabled:!0,personalAccessToken:"",selectLatestPluginVersionByDefault:!1};function Et(n,e,t="latest",s=""){let i=!1;n.settings.pluginList.contains(e)||(n.settings.pluginList.unshift(e),i=!0),n.settings.pluginSubListFrozenVersion.filter(o=>o.repo===e).length===0&&(n.settings.pluginSubListFrozenVersion.unshift({repo:e,version:t,token:s||void 0}),i=!0),i&&n.saveSettings()}function yt(n,e){return n.settings.pluginList.contains(e)}function vt(n,e,t){let s={repo:e,lastUpdate:K(t)};n.settings.themesList.unshift(s),n.saveSettings()}function Pt(n,e){return!!n.settings.themesList.find(s=>s.repo===e)}function Rt(n,e,t){for(let s of n.settings.themesList)s.repo===e&&(s.lastUpdate=t,n.saveSettings())}var N=require("obsidian");var G=class{constructor(e,t){this.tokenEl=e,this.statusEl=t}async validateToken(e,t){var s,i,o,r,a,u,l,c,p,h,m,y,v;if((s=this.tokenEl)==null||s.inputEl.removeClass("valid-input","invalid-input"),!e)return(i=this.statusEl)==null||i.setText("No token provided"),(o=this.statusEl)==null||o.addClass("invalid"),(r=this.statusEl)==null||r.removeClass("valid"),!1;try{let T=await mt(e,t);return(a=this.statusEl)==null||a.removeClass("invalid","valid"),(u=this.statusEl)==null||u.empty(),T.validToken?((l=this.tokenEl)==null||l.inputEl.addClass("valid-input"),(c=this.statusEl)==null||c.addClass("valid"),this.showValidTokenInfo(T),!0):((p=this.tokenEl)==null||p.inputEl.addClass("invalid-input"),(h=this.statusEl)==null||h.addClass("invalid"),this.showErrorMessage(T.error),!1)}catch(T){return console.error("Token validation error:",T),(m=this.tokenEl)==null||m.inputEl.addClass("invalid-input"),(y=this.statusEl)==null||y.setText("Failed to validate token"),(v=this.statusEl)==null||v.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 o=new Date(e.expirationDate),r=Math.ceil((o.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,o;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: ${(o=e.details.requiredScopes)==null?void 0:o.join(", ")}`});break}}};function Q(n,e){let t=new DocumentFragment,s=document.createElement("a");if(s.textContent=n,s.href=`https://github.com/${n}`,s.target="_blank",t.appendChild(s),e){let i=document.createTextNode(e);t.appendChild(i)}return t}function It({prependText:n,url:e,text:t,appendText:s}){let i=new DocumentFragment,o=document.createElement("a");if(o.textContent=t,o.href=e,n){let r=document.createTextNode(n);i.appendChild(r)}if(i.appendChild(o),s){let r=document.createTextNode(s);i.appendChild(r)}return i}var Ee=require("obsidian");function b(n,e,t=10,s){if(!n.settings.notificationsEnabled)return;let i=s?Ee.Platform.isDesktop?"(click=dismiss, right-click=Info)":"(click=dismiss)":"",o=new Ee.Notice(`BRAT
${e}
${i}`,t*1e3);s&&(o.noticeEl.oncontextmenu=()=>{s()})}var j=(n,e=!0)=>{let t=n.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 o=s.createEl("a",{href:"https://tfthacker.com"});return o.innerText="https://tfthacker.com",t};var At=require("obsidian"),ye=class extends At.SuggestModal{constructor(e,t,s,i,o){super(e),this.versions=s,this.selected=i,this.onChoose=o,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,o=!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=o,this.enableAfterInstall=t.settings.enableAfterInstall}async submitForm(){var o,r,a,u,l,c,p,h;if(this.address==="")return;let t=we(this.address),s=this.plugin.settings.pluginSubListFrozenVersion.find(m=>m.repo===t);if(s){await this.betaPlugins.addPlugin(t,!1,!1,!1,this.version,!0,this.enableAfterInstall,this.usePrivateApiKey?this.privateApiKey:void 0)&&(s.version=this.version,s.token=this.usePrivateApiKey?this.privateApiKey||"":void 0,await this.plugin.saveSettings(),this.close()),(o=this.cancelButton)==null||o.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&&yt(this.plugin,t)){b(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"),(h=this.versionSetting)==null||h.setDisabled(!1)}updateVersionDropdown(t,s,i=""){let o;t.clear(),s.length>0&&!i&&this.plugin.settings.selectLatestPluginVersionByDefault?o="latest":o=i,s.length<20||N.Platform.isMobile?t.addDropdown(a=>{a.addOption("","Select a version"),a.addOption("latest","Latest version");for(let l of s)a.addOption(l.version,`${l.version} ${l.prerelease?"(Prerelease)":""}`);let u=l=>{this.version=l,this.updateAddButtonState()};a.onChange(u),a.setValue(o),u(o),a.selectEl.addClass("brat-version-selector"),a.selectEl.style.width="100%"}):t.addButton(a=>{a.setButtonText(o==="latest"?"Latest version":o||"Select a version...").setClass("brat-version-selector").setClass("button").onClick(u=>{u.preventDefault();let c=[{version:"latest",prerelease:!1},...s];new ye(this.app,this.address,c,o,h=>{this.version=h,a.setButtonText(h==="latest"?"Latest version":h||"Select a version..."),this.updateAddButtonState()}).open()})})}updateAddButtonState(){this.addPluginButton&&this.addPluginButton.setDisabled(this.version==="")}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(
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,o||this.plugin.settings.personalAccessToken);if(!l)return s&&(b(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&&b(this.plugin,`${e}
The plugin id attribute for the release is missing from the manifest file`,15),null;if(!("version"in c))return s&&b(this.plugin,`${e}
The version attribute for the release is missing from the manifest file`,15),null;let p=Pe(u.tag_name,{includePrerelease:!0,loose:!0}),h=Pe(c.version,{includePrerelease:!0,loose:!0});return Lt(p,h)!==0&&(s&&b(this.plugin,`${e}
Version mismatch detected:
Release tag version: ${u.tag_name}
Manifest version: ${c.version}
2025-08-19 18:39:03 +08:00
2025-08-20 15:34:47 +08:00
The release tag version will be used to ensure consistency.`,15),c.version=p.version),c}catch(a){if(a instanceof C){let u=`GitHub API rate limit exceeded. Reset in ${a.getMinutesToReset()} minutes.`;throw s&&b(this.plugin,u,15),console.error(`BRAT: validateRepository ${a}`),b(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?b(this.plugin,`${e}
GitHub API Authentication error. Please verify that your personal access token is valid and set correctly.`,15):b(this.plugin,`${e}
GitHub API error ${a.status}: ${a.message}`,15)),console.error(`BRAT: validateRepository ${a}`),a;return s&&b(this.plugin,`${e}
Unspecified error encountered: ${a}, verify debug for more information.`,15),null}}async getAllReleaseFiles(e,t,s,i="",o=""){let r=await Oe(e,this.plugin.settings.debuggingMode,o),a=await Be(e,i,s,this.plugin.settings.debuggingMode,r,o||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,o||this.plugin.settings.personalAccessToken),manifest:u?await Y(a,"manifest.json",this.plugin.settings.debuggingMode,r,o||this.plugin.settings.personalAccessToken):"",styles:await Y(a,"styles.css",this.plugin.settings.debuggingMode,r,o||this.plugin.settings.personalAccessToken)}}async writeReleaseFilesToPluginFolder(e,t){var o,r;let s=`${(0,F.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`,(o=t.mainJs)!=null?o:""),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,o="",r=!1,a=this.plugin.settings.enableAfterInstall,u=""){try{this.plugin.settings.debuggingMode&&console.log("BRAT: addPlugin",e,t,s,i,o,r,a,u?"private":"public");let l=10,c=await this.validateRepository(e,!0,!0,o,u),p=!!c;if(p||(c=await this.validateRepository(e,!1,!0,o,u)),c===null){let m=`${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(m,!0),b(this.plugin,m,l),!1}if(!Object.hasOwn(c,"version")){let m=`${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(m,!0),b(this.plugin,m,l),!1}if(Object.hasOwn(c,"minAppVersion")&&!(0,F.requireApiVersion)(c.minAppVersion)){let m=`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 ${F.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(m,!0),b(this.plugin,m,30),!1}let h=async()=>{let m=await this.getAllReleaseFiles(e,c,p,o,u);if(console.log("rFiles",m),(p||m.manifest==="")&&(m.manifest=JSON.stringify(c)),this.plugin.settings.debuggingMode&&console.log("BRAT: rFiles.manifest",p,m),m.mainJs===null){let y=`${e}
The release is not complete and cannot be download. main.js is missing from the Release`;return await this.plugin.log(y,!0),b(this.plugin,y,l),null}return m};if(!t||r){let m=await h();if(m===null)return!1;if(await this.writeReleaseFilesToPluginFolder(c.id,m),r||Et(this.plugin,e,o,u),a){let{plugins:y}=this.plugin.app,v=(0,F.normalizePath)(`${y.getPluginFolder()}/${c.id}`);await y.loadManifest(v),await y.enablePluginAndSave(c.id)}if(await this.plugin.app.plugins.loadManifests(),r)await this.reloadPlugin(c.id),await this.plugin.log(`${e} reinstalled`,!0),b(this.plugin,`${e}
Plugin has been reinstalled and reloaded with version ${c.version}`,l);else{let y=o===""?"":` (version: ${o})`,v=`${e}${y}
The plugin has been registered with BRAT.`;a||(v+=" You may still need to enable it the Community Plugin List."),await this.plugin.log(v,!0),b(this.plugin,v,l)}}else{let m=`${this.plugin.app.vault.configDir}/plugins/${c.id}/`,y="";try{y=await this.plugin.app.vault.adapter.read(`${m}manifest.json`)}catch(I){if(I.errno===-4058||I.errno===-2)return await this.addPlugin(e,!1,p,!1,o,!1,a,u),!0;console.log("BRAT - Local Manifest Load",c.id,JSON.stringify(I,null,2))}if(o!==""&&o!=="latest")return b(this.plugin,`The version of ${e} is frozen, not updating.`,3),!1;let v=await JSON.parse(y),T=Pe(v.version,{includePrerelease:!0,loose:!0}),E=Pe(c.version,{includePrerelease:!0,loose:!0});if(Lt(T,E)===-1){let I=await h();if(I===null)return!1;if(s){let ce=`There is an update available for ${c.id} from version ${v.version} to ${c.version}. `;return await this.plugin.log(`${ce}[Release Info](https://github.com/${e}/releases/tag/${c.version})`,!0),b(this.plugin,ce,30,()=>{c&&window.open(`https://github.com/${e}/releases/tag/${c.version}`)}),!1}await this.writeReleaseFilesToPluginFolder(c.id,I),await this.plugin.app.plugins.loadManifests(),await this.reloadPlugin(c.id);let $=`${c.id}
Plugin has been updated from version ${v.version} to ${c.version}. `;return await this.plugin.log(`${$}[Release Info](https://github.com/${e}/releases/tag/${c.version})`,!0),b(this.plugin,$,30,()=>{c&&window.open(`https://github.com/${e}/releases/tag/${c.version}`)}),!0}return i&&b(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:o,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,o=""){let r=await this.addPlugin(e,!0,t,s,"",i,!1,o);return!r&&!t&&b(this.plugin,`${e}
Update of plugin failed.`),r}async checkForPluginUpdatesAndInstallUpdates(e=!1,t=!1){var a,u;if(!await ve()){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 F.Notice(`BRAT
${i}`,3e4));let o=new Map(this.plugin.settings.pluginSubListFrozenVersion.map(l=>[l.repo,{version:l.version,token:l.token}]));for(let l of this.plugin.settings.pluginList)o.has(l)&&((a=o.get(l))==null?void 0:a.version)!=="latest"||await this.updatePlugin(l,t,!1,!1,(u=o.get(l))==null?void 0:u.token);let r="Checking for plugin updates COMPLETED";await this.plugin.log(r,!0),e&&(s&&s.hide(),b(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(o=>o.manifest);return e?s.filter(o=>i.find(r=>o.id===r.id)):s.filter(o=>!i.find(r=>o.id===r.id))}};var V=require("obsidian");var J=async(n,e,t)=>{let s=await _(e,!0,n.settings.debuggingMode);if(s||(s=await _(e,!1,n.settings.debuggingMode)),!s)return b(n,"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 wt(e,n.settings.debuggingMode);if(!i)return b(n,"There is no manifest.json file in the root path of this repository, so theme cannot be installed."),!1;let o=await JSON.parse(i),r=(0,V.normalizePath)(Ds(n)+o.name),{adapter:a}=n.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),Rt(n,e,K(s));let u="";return t?(vt(n,e,s),u=`${o.name} theme installed from ${e}. `,setTimeout(()=>{n.app.customCss.setTheme(o.name)},500)):u=`${o.name} theme updated from ${e}.`,n.log(`${u}[Theme Info](https://github.com/${e})`,!1),b(n,u,20,()=>{window.open(`https://github.com/${e}`)}),!0},q=async(n,e)=>{if(!await ve()){console.log("BRAT: No internet detected.");return}let t,s="Checking for beta theme updates STARTED";await n.log(s,!0),e&&n.settings.notificationsEnabled&&(t=new V.Notice(`BRAT
${s}`,3e4));for(let o of n.settings.themesList){let r=await W(o.repo,!0,n.settings.debuggingMode);r==="0"&&(r=await W(o.repo,!1,n.settings.debuggingMode)),console.log("BRAT: lastUpdateOnline",r),r!==o.lastUpdate&&await J(n,o.repo,!1)}let i="Checking for beta theme updates COMPLETED";(async()=>await n.log(i,!0))(),e&&(n.settings.notificationsEnabled&&t&&t.hide(),b(n,i))},Re=(n,e)=>{n.settings.themesList=n.settings.themesList.filter(s=>s.repo!==e),n.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.`;n.log(t,!0),b(n,t)},Ds=n=>`${(0,V.normalizePath)(`${n.app.vault.configDir}/themes`)}/`;var U=require("obsidian");var O=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(Pt(this.plugin,e)){b(this.plugin,"This theme is already in the list for beta testing",10);return}await J(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(o=>{this.address=o.trim()}),i.inputEl.addEventListener("keydown",o=>{o.key==="Enter"&&this.address!==" "&&(o.preventDefault(),this.submitForm())}),i.inputEl.style.width="100%",window.setTimeout(()=>{let o=document.querySelector(".setting-item-info");o&&o.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(o=>{o.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 o of Array.from(i))o.remove()},50)})}onClose(){this.openSettingsTabAfterwards&&(this.plugin.app.setting.openTab(),this.plugin.app.setting.openTabById(this.plugin.APP_ID))}};var Ct=require("obsidian"),L=class extends Ct.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 o;let s=(o=document.querySelector(".suggestion-item.is-selected div"))==null?void 0:o.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 ee=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 to
${o}`,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 L(this.plugin);s.setSuggesterData(t),s.display(i=>{let o=`Reinstalling ${i.info}`;b(this.plugin,`
${o}`,3),this.plugin.log(o,!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 L(this.plugin);t.setSuggesterData(e),t.display(s=>{b(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 L(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 L(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 ft(this.plugin.settings.debuggingMode);if(e){let t=Object.values(e).map(o=>({display:`Plugin: ${o.name} (${o.repo})`,info:o.repo})),s=Object.values(this.plugin.settings.pluginList).map(o=>({display:`BRAT: ${o}`,info:o}));for(let o of t)s.push(o);let i=new L(this.plugin);i.setSuggesterData(s),i.display(o=>{o.info&&window.open(`https://github.com/${o.info}`)})}}},{id:"openGitHubRepoTheme",icon:"BratIcon",name:"Themes: Open the GitHub repository for a theme (appearance)",showInRibbon:!0,callback:async()=>{let e=await bt(this.plugin.settings.debuggingMode);if(e){let t=Object.values(e).map(i=>({display:`Theme: ${i.name} (${i.repo})`,info:i.repo})),s=new L(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(o=>({display:`Plugin: ${o.name}`,info:o.id})),s=new L(this.plugin),i=Object.values(e.settingTabs).map(o=>({display:`Core: ${o.name}`,info:o.id}));for(let o of t)i.push(o);s.setSuggesterData(i),s.display(o=>{e.open(),e.openTabById(o.info)})}},{id:"GrabBetaTheme",icon:"BratIcon",name:"Themes: Grab a beta theme for testing from a Github repository",showInRibbon:!0,callback:()=>{new O(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 L(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)}})),o=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 o)e.push(r);t.setSuggesterData(e),t.display(r=>{typeof r.info=="function"&&r.info()})}};var R=require("obsidian");var Ie=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 o=>{this
`," ")}
`,u=n.app.vault.getAbstractFileByPath(s);u?await n.app.vault.append(u,a):u=await n.app.vault.create(s,a)}}var Ae=class extends Yt.Plugin{constructor(){super(...arguments);this.APP_NAME="BRAT";this.APP_ID="obsidian42-brat";this.settings=Me;this.betaPlugins=new Z(this);this.commands=new ee(this);this.bratApi=new te(this);this.obsidianProtocolHandler=t=>{if(!t.plugin&&!t.theme){b(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 O(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 Ie(this.app,this)),this.registerObsidianProtocolHandler("brat",this.obsidianProtocolHandler),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 Xt(this,t,s)}onunload(){console.log(`unloading ${this.APP_NAME}`)}async loadSettings(){this.settings=Object.assign({},Me,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}};
/* nosourcemap */