From 0623c3ad0b2f63fcf026a3e51be0d6befe960ffb Mon Sep 17 00:00:00 2001 From: svemagie <869694+svemagie@users.noreply.github.com> Date: Mon, 23 Mar 2026 18:13:47 +0100 Subject: [PATCH] feat: resolve [[WikiLinks]] to blog URLs on publish - Converts [[Note Name]] and [[Note Name|Alias]] in the body to Markdown links using the linked note's mp-url frontmatter field. Falls back to plain display text if the note is not published yet. - Resolves the `related:` frontmatter field (Obsidian wikilinks) to blog URLs and sends them as a `related` Micropub property, enabling "See Also" display on the blog. - Image embeds (![[...]]) are excluded via negative lookbehind. Co-Authored-By: Claude Sonnet 4.6 --- main.js | 16 ++++++------ src/Publisher.ts | 65 +++++++++++++++++++++++++++++++++++++++++++++++- 2 files changed, 72 insertions(+), 9 deletions(-) diff --git a/main.js b/main.js index f0dc8d4..62bd463 100644 --- a/main.js +++ b/main.js @@ -3,16 +3,16 @@ THIS IS A GENERATED/BUNDLED FILE BY ESBUILD if you want to view the source, please visit the github repository of this plugin */ -"use strict";var vt=Object.create;var D=Object.defineProperty;var St=Object.getOwnPropertyDescriptor;var kt=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var xt=(a,t)=>{for(var i in t)D(a,i,{get:t[i],enumerable:!0})},ut=(a,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of kt(t))!Et.call(a,e)&&e!==i&&D(a,e,{get:()=>t[e],enumerable:!(n=St(t,e))||n.enumerable});return a};var Pt=(a,t,i)=>(i=a!=null?vt(Tt(a)):{},ut(t||!a||!a.__esModule?D(i,"default",{value:a,enumerable:!0}):i,a)),Rt=a=>ut(D({},"__esModule",{value:!0}),a);var $t={};xt($t,{default:()=>O});module.exports=Rt($t);var f=require("obsidian");var ht={micropubEndpoint:"",mediaEndpoint:"",accessToken:"",defaultSyndicateTo:[],autoDiscover:!1,siteUrl:"",authorizationEndpoint:"",tokenEndpoint:"",me:"",writeUrlToFrontmatter:!0,mapGardenTags:!0,defaultVisibility:"public"};var u=require("obsidian");var S=require("obsidian"),k=class{constructor(t,i,n){this.getEndpoint=t;this.getMediaEndpoint=i;this.getToken=n}async fetchConfig(){let t=`${this.getEndpoint()}?q=config`;return(await(0,S.requestUrl)({url:t,method:"GET",headers:this.authHeaders()})).json}async discoverEndpoints(t){let n=(await(0,S.requestUrl)({url:t,method:"GET"})).text,e=this.extractLinkRel(n,"micropub"),s=this.extractLinkRel(n,"token_endpoint"),r;if(e)try{r=(await this.fetchConfigFrom(e))["media-endpoint"]}catch(c){}return{micropubEndpoint:e,tokenEndpoint:s,mediaEndpoint:r}}async createPost(t){var n,e,s;let i={type:["h-entry"],properties:t};try{let r=await(0,S.requestUrl)({url:this.getEndpoint(),method:"POST",headers:{...this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(i),throw:!1});if(r.status===201||r.status===202)return{success:!0,url:((n=r.headers)==null?void 0:n.location)||((e=r.headers)==null?void 0:e.Location)||((s=r.json)==null?void 0:s.url)};let c=this.extractError(r.text);return{success:!1,error:`HTTP ${r.status}: ${c}`}}catch(r){return{success:!1,error:String(r)}}}async updatePost(t,i){let n={action:"update",url:t,replace:i};try{let e=await(0,S.requestUrl)({url:this.getEndpoint(),method:"POST",headers:{...this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(n),throw:!1});return e.status>=200&&e.status<300?{success:!0,url:t}:{success:!1,error:`HTTP ${e.status}: ${this.extractError(e.text)}`}}catch(e){return{success:!1,error:String(e)}}}async uploadMedia(t,i,n){var m,b,y;let e=this.getMediaEndpoint()||`${this.getEndpoint()}/media`,s=`----MicropubBoundary${Date.now()}`,r=`--${s}\r +"use strict";var St=Object.create;var U=Object.defineProperty;var Tt=Object.getOwnPropertyDescriptor;var Et=Object.getOwnPropertyNames;var xt=Object.getPrototypeOf,Pt=Object.prototype.hasOwnProperty;var Rt=(g,t)=>{for(var i in t)U(g,i,{get:t[i],enumerable:!0})},mt=(g,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let e of Et(t))!Pt.call(g,e)&&e!==i&&U(g,e,{get:()=>t[e],enumerable:!(n=Tt(t,e))||n.enumerable});return g};var At=(g,t,i)=>(i=g!=null?St(xt(g)):{},mt(t||!g||!g.__esModule?U(i,"default",{value:g,enumerable:!0}):i,g)),$t=g=>mt(U({},"__esModule",{value:!0}),g);var Mt={};Rt(Mt,{default:()=>O});module.exports=$t(Mt);var f=require("obsidian");var ft={micropubEndpoint:"",mediaEndpoint:"",accessToken:"",defaultSyndicateTo:[],autoDiscover:!1,siteUrl:"",authorizationEndpoint:"",tokenEndpoint:"",me:"",writeUrlToFrontmatter:!0,mapGardenTags:!0,defaultVisibility:"public"};var m=require("obsidian");var k=require("obsidian"),S=class{constructor(t,i,n){this.getEndpoint=t;this.getMediaEndpoint=i;this.getToken=n}async fetchConfig(){let t=`${this.getEndpoint()}?q=config`;return(await(0,k.requestUrl)({url:t,method:"GET",headers:this.authHeaders()})).json}async discoverEndpoints(t){let n=(await(0,k.requestUrl)({url:t,method:"GET"})).text,e=this.extractLinkRel(n,"micropub"),r=this.extractLinkRel(n,"token_endpoint"),s;if(e)try{s=(await this.fetchConfigFrom(e))["media-endpoint"]}catch(o){}return{micropubEndpoint:e,tokenEndpoint:r,mediaEndpoint:s}}async createPost(t){var n,e,r;let i={type:["h-entry"],properties:t};try{let s=await(0,k.requestUrl)({url:this.getEndpoint(),method:"POST",headers:{...this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(i),throw:!1});if(s.status===201||s.status===202)return{success:!0,url:((n=s.headers)==null?void 0:n.location)||((e=s.headers)==null?void 0:e.Location)||((r=s.json)==null?void 0:r.url)};let o=this.extractError(s.text);return{success:!1,error:`HTTP ${s.status}: ${o}`}}catch(s){return{success:!1,error:String(s)}}}async updatePost(t,i){let n={action:"update",url:t,replace:i};try{let e=await(0,k.requestUrl)({url:this.getEndpoint(),method:"POST",headers:{...this.authHeaders(),"Content-Type":"application/json"},body:JSON.stringify(n),throw:!1});return e.status>=200&&e.status<300?{success:!0,url:t}:{success:!1,error:`HTTP ${e.status}: ${this.extractError(e.text)}`}}catch(e){return{success:!1,error:String(e)}}}async uploadMedia(t,i,n){var u,T,b;let e=this.getMediaEndpoint()||`${this.getEndpoint()}/media`,r=`----MicropubBoundary${Date.now()}`,s=`--${r}\r Content-Disposition: form-data; name="file"; filename="${i}"\r Content-Type: ${n}\r \r -`,c=`\r ---${s}--\r -`,l=new TextEncoder().encode(r),o=new TextEncoder().encode(c),p=new Uint8Array(t),g=new Uint8Array(l.length+p.length+o.length);g.set(l,0),g.set(p,l.length),g.set(o,l.length+p.length);let d=await(0,S.requestUrl)({url:e,method:"POST",headers:{...this.authHeaders(),"Content-Type":`multipart/form-data; boundary=${s}`},body:g.buffer,throw:!1});if(d.status===201||d.status===202){let v=((m=d.headers)==null?void 0:m.location)||((b=d.headers)==null?void 0:b.Location)||((y=d.json)==null?void 0:y.url);if(v)return v}throw new Error(`Media upload failed (HTTP ${d.status}): ${this.extractError(d.text)}`)}authHeaders(){return{Authorization:`Bearer ${this.getToken()}`}}extractLinkRel(t,i){var s;let n=new RegExp(`]+rel=["']${i}["'][^>]+href=["']([^"']+)["']|]+href=["']([^"']+)["'][^>]+rel=["']${i}["']`,"i"),e=t.match(n);return(s=e==null?void 0:e[1])!=null?s:e==null?void 0:e[2]}async fetchConfigFrom(t){return(await(0,S.requestUrl)({url:`${t}?q=config`,method:"GET",headers:this.authHeaders()})).json}extractError(t){var i,n;try{let e=JSON.parse(t);return(n=(i=e.error_description)!=null?i:e.error)!=null?n:t.slice(0,200)}catch(e){return t.slice(0,200)}}};var R=Pt(require("crypto")),_=require("obsidian"),mt="https://svemagie.github.io/obsidian-micropub/",ft="https://svemagie.github.io/obsidian-micropub/callback",bt="create update media",At=300*1e3,P=null;function yt(a){if(!P)return;let{resolve:t,state:i}=P;P=null,t(a)}var U=class a{static async discoverEndpoints(t){let n=(await(0,_.requestUrl)({url:t,method:"GET"})).text,e=a.extractLinkRel(n,"authorization_endpoint"),s=a.extractLinkRel(n,"token_endpoint"),r=a.extractLinkRel(n,"micropub");if(!e)throw new Error(`No found at ${t}. Make sure Indiekit is running and SITE_URL is set correctly.`);if(!s)throw new Error(`No found at ${t}.`);return{authorizationEndpoint:e,tokenEndpoint:s,micropubEndpoint:r}}static async signIn(t){var b,y,v,T,A,E;let{authorizationEndpoint:i,tokenEndpoint:n,micropubEndpoint:e}=await a.discoverEndpoints(t),s=a.base64url(R.randomBytes(16)),r=a.base64url(R.randomBytes(64)),c=a.base64url(R.createHash("sha256").update(r).digest()),l=new Promise((x,w)=>{let $=setTimeout(()=>{P=null,w(new Error("Sign-in timed out (5 min). Please try again."))},At);P={state:s,resolve:M=>{clearTimeout($),x(M)}}}),o=new URL(i);o.searchParams.set("response_type","code"),o.searchParams.set("client_id",mt),o.searchParams.set("redirect_uri",ft),o.searchParams.set("state",s),o.searchParams.set("code_challenge",c),o.searchParams.set("code_challenge_method","S256"),o.searchParams.set("scope",bt),o.searchParams.set("me",t),window.open(o.toString());let p=await l;if(p.state!==s)throw new Error("State mismatch \u2014 possible CSRF attack. Please try again.");let g=p.code;if(!g)throw new Error((y=(b=p.error_description)!=null?b:p.error)!=null?y:"No authorization code received.");let d=await(0,_.requestUrl)({url:n,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",code:g,client_id:mt,redirect_uri:ft,code_verifier:r}).toString(),throw:!1}),m=d.json;if(!m.access_token)throw new Error((T=(v=m.error_description)!=null?v:m.error)!=null?T:`Token exchange failed (HTTP ${d.status})`);return{accessToken:m.access_token,scope:(A=m.scope)!=null?A:bt,me:(E=m.me)!=null?E:t,authorizationEndpoint:i,tokenEndpoint:n,micropubEndpoint:e}}static base64url(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static extractLinkRel(t,i){var s;let n=new RegExp(`]+rel=["'][^"']*\\b${i}\\b[^"']*["'][^>]+href=["']([^"']+)["']|]+href=["']([^"']+)["'][^>]+rel=["'][^"']*\\b${i}\\b[^"']*["']`,"i"),e=t.match(n);return(s=e==null?void 0:e[1])!=null?s:e==null?void 0:e[2]}};var F=class extends u.PluginSettingTab{constructor(i,n){super(i,n);this.plugin=n}display(){let{containerEl:i}=this;i.empty(),i.createEl("h2",{text:"Micropub Publisher"}),i.createEl("h3",{text:"Account"}),this.plugin.settings.me&&this.plugin.settings.accessToken?this.renderSignedIn(i):this.renderSignedOut(i),i.createEl("h3",{text:"Endpoints"}),i.createEl("p",{text:"These are filled automatically when you sign in. Only edit them manually if your server uses non-standard paths.",cls:"setting-item-description"}),new u.Setting(i).setName("Micropub endpoint").setDesc("e.g. https://blog.giersig.eu/micropub").addText(n=>n.setPlaceholder("https://example.com/micropub").setValue(this.plugin.settings.micropubEndpoint).onChange(async e=>{this.plugin.settings.micropubEndpoint=e.trim(),await this.plugin.saveSettings()})),new u.Setting(i).setName("Media endpoint").setDesc("For image uploads. Auto-discovered if blank.").addText(n=>n.setPlaceholder("https://example.com/micropub/media").setValue(this.plugin.settings.mediaEndpoint).onChange(async e=>{this.plugin.settings.mediaEndpoint=e.trim(),await this.plugin.saveSettings()})),i.createEl("h3",{text:"Publish Behaviour"}),new u.Setting(i).setName("Default visibility").setDesc("Applies when the note has no explicit visibility property.").addDropdown(n=>n.addOption("public","Public").addOption("unlisted","Unlisted").addOption("private","Private").setValue(this.plugin.settings.defaultVisibility).onChange(async e=>{this.plugin.settings.defaultVisibility=e,await this.plugin.saveSettings()})),new u.Setting(i).setName("Write URL back to note").setDesc("After publishing, store the post URL as `mp-url` in frontmatter. Subsequent publishes will update the existing post instead of creating a new one.").addToggle(n=>n.setValue(this.plugin.settings.writeUrlToFrontmatter).onChange(async e=>{this.plugin.settings.writeUrlToFrontmatter=e,await this.plugin.saveSettings()})),i.createEl("h3",{text:"Digital Garden"}),new u.Setting(i).setName("Map #garden/* tags to gardenStage").setDesc("Obsidian tags like #garden/plant become a `garden-stage: plant` Micropub property. The blog renders these as growth stage badges at /garden/.").addToggle(n=>n.setValue(this.plugin.settings.mapGardenTags).onChange(async e=>{this.plugin.settings.mapGardenTags=e,await this.plugin.saveSettings()})),i.createEl("p",{text:"Stages: plant \u{1F331} \xB7 cultivate \u{1F33F} \xB7 question \u2753 \xB7 repot \u{1FAB4} \xB7 revitalize \u2728 \xB7 revisit \u{1F504}",cls:"setting-item-description"})}renderSignedOut(i){new u.Setting(i).setName("Site URL").setDesc("Your site's home page. Clicking Sign in opens your blog's login page in the browser \u2014 the same flow iA Writer uses.").addText(e=>e.setPlaceholder("https://blog.giersig.eu").setValue(this.plugin.settings.siteUrl).onChange(async s=>{this.plugin.settings.siteUrl=s.trim(),await this.plugin.saveSettings()})).addButton(e=>{e.setButtonText("Sign in").setCta().onClick(async()=>{let s=this.plugin.settings.siteUrl.trim();if(!s){new u.Notice("Enter your site URL first.");return}e.setDisabled(!0),e.setButtonText("Opening browser\u2026");try{let r=await U.signIn(s);if(this.plugin.settings.accessToken=r.accessToken,this.plugin.settings.me=r.me,this.plugin.settings.authorizationEndpoint=r.authorizationEndpoint,this.plugin.settings.tokenEndpoint=r.tokenEndpoint,r.micropubEndpoint&&(this.plugin.settings.micropubEndpoint=r.micropubEndpoint),r.mediaEndpoint&&(this.plugin.settings.mediaEndpoint=r.mediaEndpoint),await this.plugin.saveSettings(),!this.plugin.settings.mediaEndpoint)try{let l=await new k(()=>this.plugin.settings.micropubEndpoint,()=>this.plugin.settings.mediaEndpoint,()=>this.plugin.settings.accessToken).fetchConfig();l["media-endpoint"]&&(this.plugin.settings.mediaEndpoint=l["media-endpoint"],await this.plugin.saveSettings())}catch(c){}new u.Notice(`\u2705 Signed in as ${r.me}`),this.display()}catch(r){new u.Notice(`Sign-in failed: ${String(r)}`,8e3),e.setDisabled(!1),e.setButtonText("Sign in")}})});let n=i.createEl("details");n.createEl("summary",{text:"Or paste a token manually",cls:"setting-item-description"}),n.style.marginTop="8px",n.style.marginBottom="8px",new u.Setting(n).setName("Access token").setDesc("Bearer token from your Indiekit admin panel.").addText(e=>{e.setPlaceholder("your-bearer-token").setValue(this.plugin.settings.accessToken).onChange(async s=>{this.plugin.settings.accessToken=s.trim(),await this.plugin.saveSettings()}),e.inputEl.type="password"}).addButton(e=>e.setButtonText("Verify").onClick(async()=>{if(!this.plugin.settings.micropubEndpoint||!this.plugin.settings.accessToken){new u.Notice("Set the Micropub endpoint and token first.");return}e.setDisabled(!0);try{await new k(()=>this.plugin.settings.micropubEndpoint,()=>this.plugin.settings.mediaEndpoint,()=>this.plugin.settings.accessToken).fetchConfig(),new u.Notice("\u2705 Token is valid!")}catch(s){new u.Notice(`Token check failed: ${String(s)}`)}finally{e.setDisabled(!1)}}))}renderSignedIn(i){let n=this.plugin.settings.me,e=i.createDiv({cls:"micropub-auth-banner"});e.style.cssText="display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid var(--background-modifier-border);border-radius:8px;margin-bottom:16px;background:var(--background-secondary);";let s=e.createDiv();s.style.cssText="width:40px;height:40px;border-radius:50%;background:var(--interactive-accent);display:flex;align-items:center;justify-content:center;font-size:1.2rem;flex-shrink:0;",s.textContent="\u{1F310}";let r=e.createDiv();r.createEl("div",{text:"Signed in",attr:{style:"font-size:.75rem;color:var(--text-muted);margin-bottom:2px"}}),r.createEl("div",{text:n,attr:{style:"font-weight:500;word-break:break-all"}}),new u.Setting(i).setName("Site URL").addText(c=>c.setValue(this.plugin.settings.siteUrl).setDisabled(!0)).addButton(c=>c.setButtonText("Sign out").setWarning().onClick(async()=>{this.plugin.settings.accessToken="",this.plugin.settings.me="",this.plugin.settings.authorizationEndpoint="",this.plugin.settings.tokenEndpoint="",await this.plugin.saveSettings(),this.display()}))}};var wt=require("obsidian");var j="garden/",L=class{constructor(t,i){this.app=t;this.settings=i;this.client=new k(()=>i.micropubEndpoint,()=>i.mediaEndpoint,()=>i.accessToken)}async publish(t){let i=await this.app.vault.read(t),{frontmatter:n,body:e}=this.parseFrontmatter(i),s=n["mp-url"]!=null?String(n["mp-url"]):n.url!=null?String(n.url):void 0,{content:r,uploadedUrls:c}=await this.processImages(e),l=this.buildProperties(n,r,c,t.basename),o;if(s){let p={};for(let[g,d]of Object.entries(l))p[g]=Array.isArray(d)?d:[d];o=await this.client.updatePost(s,p)}else o=await this.client.createPost(l);return o.success&&o.url&&this.settings.writeUrlToFrontmatter&&await this.writeUrlToNote(t,i,o.url),o}buildProperties(t,i,n,e){var I,z,V,H,q,W,Y,J,Q,X,K,Z,tt,et,it,nt,st,rt,ot,at,ct,lt,pt,gt,dt;let s={},r=i.trim(),c=(I=t.bookmarkOf)!=null?I:t["bookmark-of"],l=(z=t.likeOf)!=null?z:t["like-of"],o=(V=t.inReplyTo)!=null?V:t["in-reply-to"],p=(H=t.repostOf)!=null?H:t["repost-of"];c&&(s["bookmark-of"]=[String(c)]),l&&(s["like-of"]=[String(l)]),o&&(s["in-reply-to"]=[String(o)]),p&&(s["repost-of"]=[String(p)]),(l||p)&&!r||(s.content=r?[{html:r}]:[{html:""}]);let d=(W=(q=t.postType)!=null?q:t["post-type"])!=null?W:t.type;if(d==="article"||!d&&!!((Y=t.title)!=null?Y:t.name)){let h=(Q=(J=t.title)!=null?J:t.name)!=null?Q:e;s.name=[String(h)]}((X=t.summary)!=null?X:t.excerpt)&&(s.summary=[String((K=t.summary)!=null?K:t.excerpt)]);let b=(Z=t.created)!=null?Z:t.date;b&&(s.published=[new Date(String(b)).toISOString()]);let y=[...this.resolveArray(t.tags),...this.resolveArray(t.category)],v=this.extractGardenStage(y),T=y.filter(h=>!h.startsWith(j)&&h!=="garden");if(T.length>0&&(s.category=[...new Set(T)]),this.settings.mapGardenTags){let h=(tt=t.gardenStage)!=null?tt:v;if(h&&(s.gardenStage=[h],h==="evergreen")){let C=t["evergreen-since"];C&&(s.evergreeSince=[String(C)])}}let A=this.resolveArray((et=t["mp-syndicate-to"])!=null?et:t.mpSyndicateTo),E=[...new Set([...this.settings.defaultSyndicateTo,...A])];E.length>0&&(s["mp-syndicate-to"]=E);let x=(it=t.visibility)!=null?it:this.settings.defaultVisibility;x&&x!=="public"&&(s.visibility=[x]);let w=t.ai&&typeof t.ai=="object"?t.ai:{},$=(st=(nt=t["ai-text-level"])!=null?nt:t.aiTextLevel)!=null?st:w.textLevel,M=(ot=(rt=t["ai-code-level"])!=null?rt:t.aiCodeLevel)!=null?ot:w.codeLevel,N=(lt=(ct=(at=t["ai-tools"])!=null?at:t.aiTools)!=null?ct:w.aiTools)!=null?lt:w.tools,B=(dt=(gt=(pt=t["ai-description"])!=null?pt:t.aiDescription)!=null?gt:w.aiDescription)!=null?dt:w.description;$!=null&&(s["ai-text-level"]=[String($)]),M!=null&&(s["ai-code-level"]=[String(M)]),N!=null&&(s["ai-tools"]=[String(N)]),B!=null&&(s["ai-description"]=[String(B)]);let G=this.resolvePhotoArray(t.photo);G.length>0?s.photo=G:n.length>0&&(s.photo=n.map(h=>({value:h})));for(let[h,C]of Object.entries(t))h.startsWith("mp-")&&h!=="mp-url"&&h!=="mp-syndicate-to"&&(s[h]=this.resolveArray(C));return s}resolvePhotoArray(t){return t?(Array.isArray(t)?t:[t]).map(n=>{var e,s;if(typeof n=="string")return{value:n};if(typeof n=="object"&&n!==null){let r=n,c=String((s=(e=r.url)!=null?e:r.value)!=null?s:"");return c?r.alt?{value:c,alt:String(r.alt)}:{value:c}:null}return null}).filter(n=>n!==null):[]}extractGardenStage(t){for(let i of t){let n=i.replace(/^#/,"");if(n.startsWith(j)){let e=n.slice(j.length);if(["plant","cultivate","evergreen","question","repot","revitalize","revisit"].includes(e))return e}}}async processImages(t){let i=[],n=/!\[\[([^\]]+\.(png|jpg|jpeg|gif|webp|svg))\]\]/gi,e=/!\[([^\]]*)\]\(([^)]+\.(png|jpg|jpeg|gif|webp|svg))\)/gi,s=t,r=[...t.matchAll(n)];for(let l of r){let o=l[1];try{let p=await this.uploadLocalFile(o);p&&(i.push(p),s=s.replace(l[0],`![${o}](${p})`))}catch(p){console.warn(`[micropub] Failed to upload ${o}:`,p)}}let c=[...s.matchAll(e)];for(let l of c){let o=l[1],p=l[2];if(!p.startsWith("http"))try{let g=await this.uploadLocalFile(p);g&&(i.push(g),s=s.replace(l[0],`![${o}](${g})`))}catch(g){console.warn(`[micropub] Failed to upload ${p}:`,g)}}return{content:s,uploadedUrls:i}}async uploadLocalFile(t){let i=this.app.vault.getFiles().find(s=>s.name===t||s.path===t);if(!i)return;let n=await this.app.vault.readBinary(i),e=this.guessMimeType(i.extension);return this.client.uploadMedia(n,i.name,e)}parseFrontmatter(t){var e;let i=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!i)return{frontmatter:{},body:t};let n={};try{n=(e=(0,wt.parseYaml)(i[1]))!=null?e:{}}catch(s){}return{frontmatter:n,body:i[2]}}async writeUrlToNote(t,i,n){var p;let e=new Date,s=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),r=[["mp-url",`"${n}"`],["post-status","published"],["published",s]];if(this.settings.siteUrl)try{let g=new URL(this.settings.siteUrl).hostname.replace(/^www\./,"");r.push(["medium",`"[[${g}]]"`])}catch(g){}{let{frontmatter:g}=this.parseFrontmatter(i);if(!g["evergreen-since"]){let d=[...this.resolveArray(g.tags),...this.resolveArray(g.category)];((p=g.gardenStage)!=null?p:this.extractGardenStage(d))==="evergreen"&&r.push(["evergreen-since",s])}}let c=i.match(/^(---\r?\n[\s\S]*?\r?\n---\r?\n)([\s\S]*)$/);if(!c){let g=r.map(([d,m])=>`${d}: ${m}`).join(` +`,o=`\r +--${r}--\r +`,p=new TextEncoder().encode(s),l=new TextEncoder().encode(o),a=new Uint8Array(t),c=new Uint8Array(p.length+a.length+l.length);c.set(p,0),c.set(a,p.length),c.set(l,p.length+a.length);let d=await(0,k.requestUrl)({url:e,method:"POST",headers:{...this.authHeaders(),"Content-Type":`multipart/form-data; boundary=${r}`},body:c.buffer,throw:!1});if(d.status===201||d.status===202){let y=((u=d.headers)==null?void 0:u.location)||((T=d.headers)==null?void 0:T.Location)||((b=d.json)==null?void 0:b.url);if(y)return y}throw new Error(`Media upload failed (HTTP ${d.status}): ${this.extractError(d.text)}`)}authHeaders(){return{Authorization:`Bearer ${this.getToken()}`}}extractLinkRel(t,i){var r;let n=new RegExp(`]+rel=["']${i}["'][^>]+href=["']([^"']+)["']|]+href=["']([^"']+)["'][^>]+rel=["']${i}["']`,"i"),e=t.match(n);return(r=e==null?void 0:e[1])!=null?r:e==null?void 0:e[2]}async fetchConfigFrom(t){return(await(0,k.requestUrl)({url:`${t}?q=config`,method:"GET",headers:this.authHeaders()})).json}extractError(t){var i,n;try{let e=JSON.parse(t);return(n=(i=e.error_description)!=null?i:e.error)!=null?n:t.slice(0,200)}catch(e){return t.slice(0,200)}}};var R=At(require("crypto")),_=require("obsidian"),bt="https://svemagie.github.io/obsidian-micropub/",yt="https://svemagie.github.io/obsidian-micropub/callback",wt="create update media",Ct=300*1e3,P=null;function vt(g){if(!P)return;let{resolve:t,state:i}=P;P=null,t(g)}var D=class g{static async discoverEndpoints(t){let n=(await(0,_.requestUrl)({url:t,method:"GET"})).text,e=g.extractLinkRel(n,"authorization_endpoint"),r=g.extractLinkRel(n,"token_endpoint"),s=g.extractLinkRel(n,"micropub");if(!e)throw new Error(`No found at ${t}. Make sure Indiekit is running and SITE_URL is set correctly.`);if(!r)throw new Error(`No found at ${t}.`);return{authorizationEndpoint:e,tokenEndpoint:r,micropubEndpoint:s}}static async signIn(t){var T,b,y,A,E,$;let{authorizationEndpoint:i,tokenEndpoint:n,micropubEndpoint:e}=await g.discoverEndpoints(t),r=g.base64url(R.randomBytes(16)),s=g.base64url(R.randomBytes(64)),o=g.base64url(R.createHash("sha256").update(s).digest()),p=new Promise((C,x)=>{let w=setTimeout(()=>{P=null,x(new Error("Sign-in timed out (5 min). Please try again."))},Ct);P={state:r,resolve:M=>{clearTimeout(w),C(M)}}}),l=new URL(i);l.searchParams.set("response_type","code"),l.searchParams.set("client_id",bt),l.searchParams.set("redirect_uri",yt),l.searchParams.set("state",r),l.searchParams.set("code_challenge",o),l.searchParams.set("code_challenge_method","S256"),l.searchParams.set("scope",wt),l.searchParams.set("me",t),window.open(l.toString());let a=await p;if(a.state!==r)throw new Error("State mismatch \u2014 possible CSRF attack. Please try again.");let c=a.code;if(!c)throw new Error((b=(T=a.error_description)!=null?T:a.error)!=null?b:"No authorization code received.");let d=await(0,_.requestUrl)({url:n,method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams({grant_type:"authorization_code",code:c,client_id:bt,redirect_uri:yt,code_verifier:s}).toString(),throw:!1}),u=d.json;if(!u.access_token)throw new Error((A=(y=u.error_description)!=null?y:u.error)!=null?A:`Token exchange failed (HTTP ${d.status})`);return{accessToken:u.access_token,scope:(E=u.scope)!=null?E:wt,me:($=u.me)!=null?$:t,authorizationEndpoint:i,tokenEndpoint:n,micropubEndpoint:e}}static base64url(t){return t.toString("base64").replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}static extractLinkRel(t,i){var r;let n=new RegExp(`]+rel=["'][^"']*\\b${i}\\b[^"']*["'][^>]+href=["']([^"']+)["']|]+href=["']([^"']+)["'][^>]+rel=["'][^"']*\\b${i}\\b[^"']*["']`,"i"),e=t.match(n);return(r=e==null?void 0:e[1])!=null?r:e==null?void 0:e[2]}};var F=class extends m.PluginSettingTab{constructor(i,n){super(i,n);this.plugin=n}display(){let{containerEl:i}=this;i.empty(),i.createEl("h2",{text:"Micropub Publisher"}),i.createEl("h3",{text:"Account"}),this.plugin.settings.me&&this.plugin.settings.accessToken?this.renderSignedIn(i):this.renderSignedOut(i),i.createEl("h3",{text:"Endpoints"}),i.createEl("p",{text:"These are filled automatically when you sign in. Only edit them manually if your server uses non-standard paths.",cls:"setting-item-description"}),new m.Setting(i).setName("Micropub endpoint").setDesc("e.g. https://blog.giersig.eu/micropub").addText(n=>n.setPlaceholder("https://example.com/micropub").setValue(this.plugin.settings.micropubEndpoint).onChange(async e=>{this.plugin.settings.micropubEndpoint=e.trim(),await this.plugin.saveSettings()})),new m.Setting(i).setName("Media endpoint").setDesc("For image uploads. Auto-discovered if blank.").addText(n=>n.setPlaceholder("https://example.com/micropub/media").setValue(this.plugin.settings.mediaEndpoint).onChange(async e=>{this.plugin.settings.mediaEndpoint=e.trim(),await this.plugin.saveSettings()})),i.createEl("h3",{text:"Publish Behaviour"}),new m.Setting(i).setName("Default visibility").setDesc("Applies when the note has no explicit visibility property.").addDropdown(n=>n.addOption("public","Public").addOption("unlisted","Unlisted").addOption("private","Private").setValue(this.plugin.settings.defaultVisibility).onChange(async e=>{this.plugin.settings.defaultVisibility=e,await this.plugin.saveSettings()})),new m.Setting(i).setName("Write URL back to note").setDesc("After publishing, store the post URL as `mp-url` in frontmatter. Subsequent publishes will update the existing post instead of creating a new one.").addToggle(n=>n.setValue(this.plugin.settings.writeUrlToFrontmatter).onChange(async e=>{this.plugin.settings.writeUrlToFrontmatter=e,await this.plugin.saveSettings()})),i.createEl("h3",{text:"Digital Garden"}),new m.Setting(i).setName("Map #garden/* tags to gardenStage").setDesc("Obsidian tags like #garden/plant become a `garden-stage: plant` Micropub property. The blog renders these as growth stage badges at /garden/.").addToggle(n=>n.setValue(this.plugin.settings.mapGardenTags).onChange(async e=>{this.plugin.settings.mapGardenTags=e,await this.plugin.saveSettings()})),i.createEl("p",{text:"Stages: plant \u{1F331} \xB7 cultivate \u{1F33F} \xB7 question \u2753 \xB7 repot \u{1FAB4} \xB7 revitalize \u2728 \xB7 revisit \u{1F504}",cls:"setting-item-description"})}renderSignedOut(i){new m.Setting(i).setName("Site URL").setDesc("Your site's home page. Clicking Sign in opens your blog's login page in the browser \u2014 the same flow iA Writer uses.").addText(e=>e.setPlaceholder("https://blog.giersig.eu").setValue(this.plugin.settings.siteUrl).onChange(async r=>{this.plugin.settings.siteUrl=r.trim(),await this.plugin.saveSettings()})).addButton(e=>{e.setButtonText("Sign in").setCta().onClick(async()=>{let r=this.plugin.settings.siteUrl.trim();if(!r){new m.Notice("Enter your site URL first.");return}e.setDisabled(!0),e.setButtonText("Opening browser\u2026");try{let s=await D.signIn(r);if(this.plugin.settings.accessToken=s.accessToken,this.plugin.settings.me=s.me,this.plugin.settings.authorizationEndpoint=s.authorizationEndpoint,this.plugin.settings.tokenEndpoint=s.tokenEndpoint,s.micropubEndpoint&&(this.plugin.settings.micropubEndpoint=s.micropubEndpoint),s.mediaEndpoint&&(this.plugin.settings.mediaEndpoint=s.mediaEndpoint),await this.plugin.saveSettings(),!this.plugin.settings.mediaEndpoint)try{let p=await new S(()=>this.plugin.settings.micropubEndpoint,()=>this.plugin.settings.mediaEndpoint,()=>this.plugin.settings.accessToken).fetchConfig();p["media-endpoint"]&&(this.plugin.settings.mediaEndpoint=p["media-endpoint"],await this.plugin.saveSettings())}catch(o){}new m.Notice(`\u2705 Signed in as ${s.me}`),this.display()}catch(s){new m.Notice(`Sign-in failed: ${String(s)}`,8e3),e.setDisabled(!1),e.setButtonText("Sign in")}})});let n=i.createEl("details");n.createEl("summary",{text:"Or paste a token manually",cls:"setting-item-description"}),n.style.marginTop="8px",n.style.marginBottom="8px",new m.Setting(n).setName("Access token").setDesc("Bearer token from your Indiekit admin panel.").addText(e=>{e.setPlaceholder("your-bearer-token").setValue(this.plugin.settings.accessToken).onChange(async r=>{this.plugin.settings.accessToken=r.trim(),await this.plugin.saveSettings()}),e.inputEl.type="password"}).addButton(e=>e.setButtonText("Verify").onClick(async()=>{if(!this.plugin.settings.micropubEndpoint||!this.plugin.settings.accessToken){new m.Notice("Set the Micropub endpoint and token first.");return}e.setDisabled(!0);try{await new S(()=>this.plugin.settings.micropubEndpoint,()=>this.plugin.settings.mediaEndpoint,()=>this.plugin.settings.accessToken).fetchConfig(),new m.Notice("\u2705 Token is valid!")}catch(r){new m.Notice(`Token check failed: ${String(r)}`)}finally{e.setDisabled(!1)}}))}renderSignedIn(i){let n=this.plugin.settings.me,e=i.createDiv({cls:"micropub-auth-banner"});e.style.cssText="display:flex;align-items:center;gap:12px;padding:12px 16px;border:1px solid var(--background-modifier-border);border-radius:8px;margin-bottom:16px;background:var(--background-secondary);";let r=e.createDiv();r.style.cssText="width:40px;height:40px;border-radius:50%;background:var(--interactive-accent);display:flex;align-items:center;justify-content:center;font-size:1.2rem;flex-shrink:0;",r.textContent="\u{1F310}";let s=e.createDiv();s.createEl("div",{text:"Signed in",attr:{style:"font-size:.75rem;color:var(--text-muted);margin-bottom:2px"}}),s.createEl("div",{text:n,attr:{style:"font-weight:500;word-break:break-all"}}),new m.Setting(i).setName("Site URL").addText(o=>o.setValue(this.plugin.settings.siteUrl).setDisabled(!0)).addButton(o=>o.setButtonText("Sign out").setWarning().onClick(async()=>{this.plugin.settings.accessToken="",this.plugin.settings.me="",this.plugin.settings.authorizationEndpoint="",this.plugin.settings.tokenEndpoint="",await this.plugin.saveSettings(),this.display()}))}};var kt=require("obsidian");var N="garden/",L=class{constructor(t,i){this.app=t;this.settings=i;this.client=new S(()=>i.micropubEndpoint,()=>i.mediaEndpoint,()=>i.accessToken)}async publish(t){let i=await this.app.vault.read(t),{frontmatter:n,body:e}=this.parseFrontmatter(i),r=n["mp-url"]!=null?String(n["mp-url"]):n.url!=null?String(n.url):void 0,{content:s,uploadedUrls:o}=await this.processImages(e),p=this.resolveWikilinks(s,t.path),l=this.buildProperties(n,p,o,t.basename,t.path),a;if(r){let c={};for(let[d,u]of Object.entries(l))c[d]=Array.isArray(u)?u:[u];a=await this.client.updatePost(r,c)}else a=await this.client.createPost(l);return a.success&&a.url&&this.settings.writeUrlToFrontmatter&&await this.writeUrlToNote(t,i,a.url),a}buildProperties(t,i,n,e,r){var V,H,W,q,Y,J,Q,X,K,Z,tt,et,it,nt,st,rt,ot,at,ct,lt,pt,gt,dt,ut,ht;let s={},o=i.trim(),p=(V=t.bookmarkOf)!=null?V:t["bookmark-of"],l=(H=t.likeOf)!=null?H:t["like-of"],a=(W=t.inReplyTo)!=null?W:t["in-reply-to"],c=(q=t.repostOf)!=null?q:t["repost-of"];p&&(s["bookmark-of"]=[String(p)]),l&&(s["like-of"]=[String(l)]),a&&(s["in-reply-to"]=[String(a)]),c&&(s["repost-of"]=[String(c)]),(l||c)&&!o||(s.content=o?[{html:o}]:[{html:""}]);let u=(J=(Y=t.postType)!=null?Y:t["post-type"])!=null?J:t.type;if(u==="article"||!u&&!!((Q=t.title)!=null?Q:t.name)){let h=(K=(X=t.title)!=null?X:t.name)!=null?K:e;s.name=[String(h)]}((Z=t.summary)!=null?Z:t.excerpt)&&(s.summary=[String((tt=t.summary)!=null?tt:t.excerpt)]);let b=(et=t.created)!=null?et:t.date;b&&(s.published=[new Date(String(b)).toISOString()]);let y=[...this.resolveArray(t.tags),...this.resolveArray(t.category)],A=this.extractGardenStage(y),E=y.filter(h=>!h.startsWith(N)&&h!=="garden");if(E.length>0&&(s.category=[...new Set(E)]),this.settings.mapGardenTags){let h=(it=t.gardenStage)!=null?it:A;if(h&&(s.gardenStage=[h],h==="evergreen")){let v=t["evergreen-since"];v&&(s.evergreeSince=[String(v)])}}let $=this.resolveArray((nt=t["mp-syndicate-to"])!=null?nt:t.mpSyndicateTo),C=[...new Set([...this.settings.defaultSyndicateTo,...$])];C.length>0&&(s["mp-syndicate-to"]=C);let x=(st=t.visibility)!=null?st:this.settings.defaultVisibility;x&&x!=="public"&&(s.visibility=[x]);let w=t.ai&&typeof t.ai=="object"?t.ai:{},M=(ot=(rt=t["ai-text-level"])!=null?rt:t.aiTextLevel)!=null?ot:w.textLevel,j=(ct=(at=t["ai-code-level"])!=null?at:t.aiCodeLevel)!=null?ct:w.codeLevel,B=(gt=(pt=(lt=t["ai-tools"])!=null?lt:t.aiTools)!=null?pt:w.aiTools)!=null?gt:w.tools,G=(ht=(ut=(dt=t["ai-description"])!=null?dt:t.aiDescription)!=null?ut:w.aiDescription)!=null?ht:w.description;M!=null&&(s["ai-text-level"]=[String(M)]),j!=null&&(s["ai-code-level"]=[String(j)]),B!=null&&(s["ai-tools"]=[String(B)]),G!=null&&(s["ai-description"]=[String(G)]);let I=this.resolvePhotoArray(t.photo);I.length>0?s.photo=I:n.length>0&&(s.photo=n.map(h=>({value:h})));let z=this.resolveArray(t.related);if(z.length>0){let h=z.map(v=>this.resolveWikilinkToUrl(v,r)).filter(v=>v!==null);h.length>0&&(s.related=h)}for(let[h,v]of Object.entries(t))h.startsWith("mp-")&&h!=="mp-url"&&h!=="mp-syndicate-to"&&(s[h]=this.resolveArray(v));return s}resolvePhotoArray(t){return t?(Array.isArray(t)?t:[t]).map(n=>{var e,r;if(typeof n=="string")return{value:n};if(typeof n=="object"&&n!==null){let s=n,o=String((r=(e=s.url)!=null?e:s.value)!=null?r:"");return o?s.alt?{value:o,alt:String(s.alt)}:{value:o}:null}return null}).filter(n=>n!==null):[]}extractGardenStage(t){for(let i of t){let n=i.replace(/^#/,"");if(n.startsWith(N)){let e=n.slice(N.length);if(["plant","cultivate","evergreen","question","repot","revitalize","revisit"].includes(e))return e}}}async processImages(t){let i=[],n=/!\[\[([^\]]+\.(png|jpg|jpeg|gif|webp|svg))\]\]/gi,e=/!\[([^\]]*)\]\(([^)]+\.(png|jpg|jpeg|gif|webp|svg))\)/gi,r=t,s=[...t.matchAll(n)];for(let p of s){let l=p[1];try{let a=await this.uploadLocalFile(l);a&&(i.push(a),r=r.replace(p[0],`![${l}](${a})`))}catch(a){console.warn(`[micropub] Failed to upload ${l}:`,a)}}let o=[...r.matchAll(e)];for(let p of o){let l=p[1],a=p[2];if(!a.startsWith("http"))try{let c=await this.uploadLocalFile(a);c&&(i.push(c),r=r.replace(p[0],`![${l}](${c})`))}catch(c){console.warn(`[micropub] Failed to upload ${a}:`,c)}}return{content:r,uploadedUrls:i}}async uploadLocalFile(t){let i=this.app.vault.getFiles().find(r=>r.name===t||r.path===t);if(!i)return;let n=await this.app.vault.readBinary(i),e=this.guessMimeType(i.extension);return this.client.uploadMedia(n,i.name,e)}parseFrontmatter(t){var e;let i=t.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n([\s\S]*)$/);if(!i)return{frontmatter:{},body:t};let n={};try{n=(e=(0,kt.parseYaml)(i[1]))!=null?e:{}}catch(r){}return{frontmatter:n,body:i[2]}}async writeUrlToNote(t,i,n){var a;let e=new Date,r=[e.getFullYear(),String(e.getMonth()+1).padStart(2,"0"),String(e.getDate()).padStart(2,"0")].join("-"),s=[["mp-url",`"${n}"`],["post-status","published"],["published",r]];if(this.settings.siteUrl)try{let c=new URL(this.settings.siteUrl).hostname.replace(/^www\./,"");s.push(["medium",`"[[${c}]]"`])}catch(c){}{let{frontmatter:c}=this.parseFrontmatter(i);if(!c["evergreen-since"]){let d=[...this.resolveArray(c.tags),...this.resolveArray(c.category)];((a=c.gardenStage)!=null?a:this.extractGardenStage(d))==="evergreen"&&s.push(["evergreen-since",r])}}let o=i.match(/^(---\r?\n[\s\S]*?\r?\n---\r?\n)([\s\S]*)$/);if(!o){let c=s.map(([d,u])=>`${d}: ${u}`).join(` `);await this.app.vault.modify(t,`--- -${g} +${c} --- -`+i);return}let l=c[1],o=c[2];for(let[g,d]of r)l=this.setFrontmatterField(l,g,d);await this.app.vault.modify(t,l+o)}setFrontmatterField(t,i,n){let e=new RegExp(`^${i}:.*$`,"m");return e.test(t)?t.replace(e,`${i}: ${n}`):t.replace(/(\r?\n---\r?\n)$/,` -${i}: ${n}$1`)}resolveArray(t){return t?Array.isArray(t)?t.map(String):[String(t)]:[]}guessMimeType(t){var n;return(n={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"}[t.toLowerCase()])!=null?n:"application/octet-stream"}};var O=class extends f.Plugin{async onload(){await this.loadSettings(),this.addCommand({id:"publish-to-micropub",name:"Publish to Micropub",checkCallback:t=>{let i=this.app.workspace.getActiveFile();return!i||i.extension!=="md"?!1:(t||this.publishActiveNote(i),!0)}}),this.addCommand({id:"publish-to-micropub-update",name:"Update existing Micropub post",checkCallback:t=>{let i=this.app.workspace.getActiveFile();return!i||i.extension!=="md"?!1:(t||this.publishActiveNote(i),!0)}}),this.registerObsidianProtocolHandler("micropub-auth",t=>{yt(t)}),this.addSettingTab(new F(this.app,this)),this.addRibbonIcon("send","Publish to Micropub",()=>{let t=this.app.workspace.getActiveFile();if(!t||t.extension!=="md"){new f.Notice("Open a Markdown note to publish.");return}this.publishActiveNote(t)})}onunload(){}async publishActiveNote(t){if(!this.settings.micropubEndpoint){new f.Notice("\u26A0\uFE0F Micropub endpoint not configured. Open plugin settings to add it.");return}if(!this.settings.accessToken){new f.Notice("\u26A0\uFE0F Access token not configured. Open plugin settings to add it.");return}let i=new f.Notice("Publishing\u2026",0);try{let e=await new L(this.app,this.settings).publish(t);if(i.hide(),e.success){let s=e.url?` -${e.url}`:"";new f.Notice(`\u2705 Published!${s}`,8e3)}else new f.Notice(`\u274C Publish failed: ${e.error}`,1e4),console.error("[micropub] Publish failed:",e.error)}catch(n){i.hide();let e=n instanceof Error?n.message:String(n);new f.Notice(`\u274C Error: ${e}`,1e4),console.error("[micropub] Unexpected error:",n)}}async loadSettings(){this.settings=Object.assign({},ht,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}}; +`+i);return}let p=o[1],l=o[2];for(let[c,d]of s)p=this.setFrontmatterField(p,c,d);await this.app.vault.modify(t,p+l)}setFrontmatterField(t,i,n){let e=new RegExp(`^${i}:.*$`,"m");return e.test(t)?t.replace(e,`${i}: ${n}`):t.replace(/(\r?\n---\r?\n)$/,` +${i}: ${n}$1`)}resolveWikilinks(t,i){return t.replace(/(?{let o=e.trim(),p=(s==null?void 0:s.trim())||o.split("/").pop()||o,l=this.resolveWikilinkToUrl(`[[${o}]]`,i);if(!l)return p;let a=r?r.toLowerCase().replace(/\s+/g,"-"):"";return`[${p}](${l}${a})`})}resolveWikilinkToUrl(t,i){var r,s,o;if(t.startsWith("http"))return t;let n=t.match(/^\[\[([^\]|#]+)(?:#[^\]|]*)?\|?[^\]]*\]\]$/);if(!n)return null;let e=this.app.metadataCache.getFirstLinkpathDest(n[1].trim(),i);return e&&(o=(s=(r=this.app.metadataCache.getFileCache(e))==null?void 0:r.frontmatter)==null?void 0:s["mp-url"])!=null?o:null}resolveArray(t){return t?Array.isArray(t)?t.map(String):[String(t)]:[]}guessMimeType(t){var n;return(n={png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml"}[t.toLowerCase()])!=null?n:"application/octet-stream"}};var O=class extends f.Plugin{async onload(){await this.loadSettings(),this.addCommand({id:"publish-to-micropub",name:"Publish to Micropub",checkCallback:t=>{let i=this.app.workspace.getActiveFile();return!i||i.extension!=="md"?!1:(t||this.publishActiveNote(i),!0)}}),this.addCommand({id:"publish-to-micropub-update",name:"Update existing Micropub post",checkCallback:t=>{let i=this.app.workspace.getActiveFile();return!i||i.extension!=="md"?!1:(t||this.publishActiveNote(i),!0)}}),this.registerObsidianProtocolHandler("micropub-auth",t=>{vt(t)}),this.addSettingTab(new F(this.app,this)),this.addRibbonIcon("send","Publish to Micropub",()=>{let t=this.app.workspace.getActiveFile();if(!t||t.extension!=="md"){new f.Notice("Open a Markdown note to publish.");return}this.publishActiveNote(t)})}onunload(){}async publishActiveNote(t){if(!this.settings.micropubEndpoint){new f.Notice("\u26A0\uFE0F Micropub endpoint not configured. Open plugin settings to add it.");return}if(!this.settings.accessToken){new f.Notice("\u26A0\uFE0F Access token not configured. Open plugin settings to add it.");return}let i=new f.Notice("Publishing\u2026",0);try{let e=await new L(this.app,this.settings).publish(t);if(i.hide(),e.success){let r=e.url?` +${e.url}`:"";new f.Notice(`\u2705 Published!${r}`,8e3)}else new f.Notice(`\u274C Publish failed: ${e.error}`,1e4),console.error("[micropub] Publish failed:",e.error)}catch(n){i.hide();let e=n instanceof Error?n.message:String(n);new f.Notice(`\u274C Error: ${e}`,1e4),console.error("[micropub] Unexpected error:",n)}}async loadSettings(){this.settings=Object.assign({},ft,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}}; diff --git a/src/Publisher.ts b/src/Publisher.ts index 5e9a173..291c2ec 100644 --- a/src/Publisher.ts +++ b/src/Publisher.ts @@ -49,8 +49,11 @@ export class Publisher { const { content: processedBody, uploadedUrls } = await this.processImages(body); + // Resolve [[WikiLinks]] in body to blog URLs + const linkedBody = this.resolveWikilinks(processedBody, file.path); + // Build Micropub properties - const properties = this.buildProperties(frontmatter, processedBody, uploadedUrls, file.basename); + const properties = this.buildProperties(frontmatter, linkedBody, uploadedUrls, file.basename, file.path); let result: PublishResult; @@ -81,6 +84,7 @@ export class Publisher { body: string, uploadedUrls: string[], basename: string, + filePath: string, ): Record { const props: Record = {}; @@ -214,6 +218,17 @@ export class Publisher { props["photo"] = uploadedUrls.map((url) => ({ value: url })); } + // Related posts — resolve [[WikiLink]] wikilinks to published blog URLs + const relatedRaw = this.resolveArray(fm["related"]); + if (relatedRaw.length > 0) { + const relatedUrls = relatedRaw + .map((ref) => this.resolveWikilinkToUrl(ref, filePath)) + .filter((url): url is string => url !== null); + if (relatedUrls.length > 0) { + props["related"] = relatedUrls; + } + } + // Pass through any `mp-*` properties from frontmatter verbatim for (const [k, v] of Object.entries(fm)) { if (k.startsWith("mp-") && k !== "mp-url" && k !== "mp-syndicate-to") { @@ -435,6 +450,54 @@ export class Publisher { return fmBlock.replace(/(\r?\n---\r?\n)$/, `\n${key}: ${value}$1`); } + // ── Wikilink resolution ────────────────────────────────────────────────── + + /** + * Replace Obsidian [[WikiLinks]] in body text with Markdown hyperlinks. + * Uses mp-url from the linked note's frontmatter. Falls back to plain + * display text if the note is not found or not yet published. + * Image embeds (![[...]]) are left untouched via negative lookbehind. + */ + private resolveWikilinks(body: string, sourcePath: string): string { + return body.replace( + /(? { + const cleanName = noteName.trim(); + const displayText = + alias?.trim() || cleanName.split("/").pop() || cleanName; + const url = this.resolveWikilinkToUrl(`[[${cleanName}]]`, sourcePath); + if (!url) return displayText; + const anchorSuffix = anchor + ? anchor.toLowerCase().replace(/\s+/g, "-") + : ""; + return `[${displayText}](${url}${anchorSuffix})`; + }, + ); + } + + /** + * Resolve a single [[WikiLink]] or plain URL string to a published mp-url. + * Returns null if the note is not found or has no mp-url. + */ + private resolveWikilinkToUrl( + ref: string, + sourcePath: string, + ): string | null { + if (ref.startsWith("http")) return ref; + const m = ref.match(/^\[\[([^\]|#]+)(?:#[^\]|]*)?\|?[^\]]*\]\]$/); + if (!m) return null; + const file = this.app.metadataCache.getFirstLinkpathDest( + m[1].trim(), + sourcePath, + ); + if (!file) return null; + return ( + (this.app.metadataCache.getFileCache(file)?.frontmatter?.[ + "mp-url" + ] as string | undefined) ?? null + ); + } + private resolveArray(value: unknown): string[] { if (!value) return []; if (Array.isArray(value)) return value.map(String);