diff --git a/main.js b/main.js deleted file mode 100644 index c3da66f..0000000 --- a/main.js +++ /dev/null @@ -1,47 +0,0 @@ -/* Pumler Obsidian Plugin */ -var _e=Object.defineProperty;var fn=Object.getOwnPropertyDescriptor;var hn=Object.getOwnPropertyNames;var mn=Object.prototype.hasOwnProperty;var gn=(e,r)=>{for(var n in r)_e(e,n,{get:r[n],enumerable:!0})},yn=(e,r,n,t)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of hn(r))!mn.call(e,i)&&i!==n&&_e(e,i,{get:()=>r[i],enumerable:!(t=fn(r,i))||t.enumerable});return e};var vn=e=>yn(_e({},"__esModule",{value:!0}),e);var jo={};gn(jo,{default:()=>be});module.exports=vn(jo);var Ee=require("obsidian");var Se="https://api.pumler.com/api/diagram/render",Ke="auto",Ce=["plantuml","structurizr","mermaid"],Le=["auto","dark","light"],qe={plantuml:["sequence","usecase","class","object","activity","component","deployment","state","timing","archimate","mindmap","wbs","json","yaml","er","nwdiag"],structurizr:["systemContext","container","component","deployment"],mermaid:["flowchart","sequence","class","er","journey","gantt","pie","quadrant","requirement","gitgraph","c4","mindmap","timeline","sankey","xychart","block","packet","kanban","architecture","radar","treemap"]};var F={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},se=class{constructor(r,n){this.adapter=r;this.writeQueue=Promise.resolve();this.logPath=xn(n),this.logDir=wn(this.logPath)}debug(r,n={}){this.write("debug",r,n)}info(r,n={}){this.write("info",r,n)}warn(r,n={}){this.write("warn",r,n)}error(r,n={}){this.write("error",r,n)}write(r,n,t){let i={ts:new Date().toISOString(),level:r,event:n,...We(t)},l=`${JSON.stringify(i)} -`;this.writeQueue=this.writeQueue.catch(()=>{}).then(async()=>{await this.ensureLogDir(),await this.ensureLogFile(),await this.adapter.append(this.logPath,l)}).catch(()=>{})}async ensureLogDir(){!this.logDir||await this.adapter.exists(this.logDir)||await this.adapter.mkdir(this.logDir)}async ensureLogFile(){await this.adapter.exists(this.logPath)||await this.adapter.write(this.logPath,"")}};function L(e){let r=2166136261;for(let n=0;n>>0).toString(16).padStart(8,"0")}function P(e){return e instanceof Error?{errorName:e.name,errorMessage:e.message}:{errorMessage:String(e)}}function We(e){let r={};return Object.entries(e).forEach(([n,t])=>{r[n]=Ze(t)}),r}function Ze(e){return e instanceof Error?P(e):Array.isArray(e)?e.map(Ze):e&&typeof e=="object"?We(e):typeof e=="string"&&e.length>500?`${e.slice(0,500)}...[truncated:${e.length}]`:e}function xn(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}function wn(e){let r=e.lastIndexOf("/");return r>0?e.slice(0,r):null}var U=class extends Error{constructor(r,n,t){super(r),this.name="PumlerRenderError",this.line=n,this.column=t}},ue=class{constructor(r=F){this.logger=r}async renderDiagram(r,n={}){var a,c,s,d,u;let t,i=Date.now();this.logger.info("client.render.start",{provider:r.provider,type:r.type,theme:r.theme,sourceLength:r.source.length,signalAborted:(c=(a=n.signal)==null?void 0:a.aborted)!=null?c:!1});try{t=await fetch(Se,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json"},body:JSON.stringify({source:r.source,metadata:{provider:r.provider,diagramType:r.type,theme:{mode:r.theme}}}),signal:n.signal})}catch(p){throw this.logger.warn("client.render.network_error",{provider:r.provider,type:r.type,durationMs:Date.now()-i,signalAborted:(d=(s=n.signal)==null?void 0:s.aborted)!=null?d:!1,...P(p)}),(u=n.signal)!=null&&u.aborted?p:new U("Network error: unable to reach the Pumler rendering API")}let l=await An(t);if(!t.ok)throw this.logger.warn("client.render.api_error",{provider:r.provider,type:r.type,durationMs:Date.now()-i,status:t.status}),bn(l);let o=l&&typeof l=="object"&&"diagram"in l?l.diagram:void 0;if(typeof o!="string"||o.trim()==="")throw this.logger.warn("client.render.unexpected_response",{provider:r.provider,type:r.type,durationMs:Date.now()-i,status:t.status}),new U("Unexpected response from the Pumler rendering API");return this.logger.info("client.render.success",{provider:r.provider,type:r.type,durationMs:Date.now()-i,status:t.status,svgLength:o.length}),o}};function $(e){return JSON.stringify([Se,e.provider,e.type,e.theme,e.source])}async function An(e){try{return await e.json()}catch(r){return null}}function bn(e){let r=e&&typeof e=="object"&&"error"in e?e.error:null,n=typeof(r==null?void 0:r.message)=="string"?r.message:"Pumler rendering API returned an error",t=typeof(r==null?void 0:r.line)=="number"?r.line:void 0,i=typeof(r==null?void 0:r.column)=="number"?r.column:void 0;return new U(n,t,i)}var En=30,de=class{constructor(r,n,t=En,i=F){this.adapter=r;this.cacheDir=n;this.limit=t;this.logger=i;this.operationQueue=Promise.resolve();this.cacheDir=ne(n),this.indexPath=ne(`${this.cacheDir}/index.json`)}async get(r){let n=Date.now(),t=L($(r));this.logger.debug("cache.get.start",B(r,t));try{let i=await this.enqueueOperation(()=>this.readEntry(r,t));return this.logger.debug(i?"cache.get.hit":"cache.get.miss",{...B(r,t),durationMs:Date.now()-n,svgLength:i==null?void 0:i.length}),i}catch(i){return this.logger.warn("cache.get.error",{...B(r,t),durationMs:Date.now()-n,...P(i)}),null}}async set(r,n){let t=Date.now(),i=L($(r));this.logger.debug("cache.set.start",{...B(r,i),svgLength:n.length}),await this.enqueueOperation(()=>this.writeEntry(r,n,i)).then(()=>{this.logger.debug("cache.set.done",{...B(r,i),durationMs:Date.now()-t,svgLength:n.length})}).catch(l=>{this.logger.warn("cache.set.error",{...B(r,i),durationMs:Date.now()-t,...P(l)})})}enqueueOperation(r){let n=this.operationQueue.catch(()=>{}).then(r);return this.operationQueue=n.then(()=>{}).catch(()=>{}),n}async readEntry(r,n){let t=await Xe(r),i=await this.readIndex(),l=i.entries.find(s=>s.key===t);if(!l)return null;let o=ne(`${this.cacheDir}/${l.file}`),a=await this.adapter.read(o),c=Je(i);return l.lastAccessed=c,l.updatedAt=Math.max(l.updatedAt,l.createdAt),await this.writeIndex(i),this.logger.debug("cache.index.touch",{...B(r,n),file:l.file,entryCount:i.entries.length}),a}async writeEntry(r,n,t){await this.ensureCacheDir();let i=await Xe(r),l=`${i}.svg`,o=ne(`${this.cacheDir}/${l}`);await this.adapter.write(o,n);let a=await this.readIndex(),c=Je(a),s=a.entries.find(d=>d.key===i);s?(s.file=l,s.updatedAt=c,s.lastAccessed=c):a.entries.push({key:i,file:l,createdAt:c,updatedAt:c,lastAccessed:c}),await this.prune(a),await this.writeIndex(a),this.logger.debug("cache.index.write",{...B(r,t),file:l,entryCount:a.entries.length})}async readIndex(){try{let r=await this.adapter.read(this.indexPath),n=JSON.parse(r);return n.version!==1||!Array.isArray(n.entries)?Qe():{version:1,entries:n.entries.filter(_n)}}catch(r){return Qe()}}async writeIndex(r){await this.ensureCacheDir(),await this.adapter.write(this.indexPath,JSON.stringify(r,null,2))}async ensureCacheDir(){await this.adapter.exists(this.cacheDir)||await this.adapter.mkdir(this.cacheDir)}async prune(r){let t=[...r.entries].sort((o,a)=>a.lastAccessed-o.lastAccessed).slice(0,this.limit),i=new Set(t.map(o=>o.file)),l=r.entries.filter(o=>!i.has(o.file));r.entries=t,await Promise.all(l.map(o=>this.removeCacheFile(o.file))),l.length>0&&this.logger.info("cache.prune",{removedCount:l.length,retainedCount:t.length,limit:this.limit})}async removeCacheFile(r){try{await this.adapter.remove(ne(`${this.cacheDir}/${r}`))}catch(n){}}};function B(e,r){return{provider:e.provider,type:e.type,theme:e.theme,sourceLength:e.source.length,cacheSeedDigest:r}}function ne(e){return e.replace(/\\/g,"/").replace(/\/+/g,"/").replace(/^\/+/,"").replace(/\/+$/,"")}async function Xe(e){let r=new TextEncoder().encode($(e)),n=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(n)).map(t=>t.toString(16).padStart(2,"0")).join("")}function Qe(){return{version:1,entries:[]}}function Je(e){let r=e.entries.reduce((n,t)=>Math.max(n,t.lastAccessed),0);return Math.max(Date.now(),r+1)}function _n(e){if(!e||typeof e!="object")return!1;let r=e;return typeof r.key=="string"&&typeof r.file=="string"&&typeof r.createdAt=="number"&&typeof r.updatedAt=="number"&&typeof r.lastAccessed=="number"}function mr(e){return typeof e=="undefined"||e===null}function Sn(e){return typeof e=="object"&&e!==null}function Cn(e){return Array.isArray(e)?e:mr(e)?[]:[e]}function Ln(e,r){var n,t,i,l;if(r)for(l=Object.keys(r),n=0,t=l.length;na&&(l=" ... ",r=t-a+l.length),n-t>a&&(o=" ...",n=t+a-o.length),{str:l+e.slice(r,n).replace(/\t/g,"\u2192")+o,pos:t-r+l.length}}function ke(e,r){return w.repeat(" ",r-e.length)+e}function Nn(e,r){if(r=Object.create(r||null),!e.buffer)return null;r.maxLength||(r.maxLength=79),typeof r.indent!="number"&&(r.indent=1),typeof r.linesBefore!="number"&&(r.linesBefore=3),typeof r.linesAfter!="number"&&(r.linesAfter=2);for(var n=/\r?\n|\r|\0/g,t=[0],i=[],l,o=-1;l=n.exec(e.buffer);)i.push(l.index),t.push(l.index+l[0].length),e.position<=l.index&&o<0&&(o=t.length-2);o<0&&(o=t.length-1);var a="",c,s,d=Math.min(e.line+r.linesAfter,i.length).toString().length,u=r.maxLength-(r.indent+d+3);for(c=1;c<=r.linesBefore&&!(o-c<0);c++)s=Te(e.buffer,t[o-c],i[o-c],e.position-(t[o]-t[o-c]),u),a=w.repeat(" ",r.indent)+ke((e.line-c+1).toString(),d)+" | "+s.str+` -`+a;for(s=Te(e.buffer,t[o],i[o],e.position,u),a+=w.repeat(" ",r.indent)+ke((e.line+1).toString(),d)+" | "+s.str+` -`,a+=w.repeat("-",r.indent+d+3+s.pos)+`^ -`,c=1;c<=r.linesAfter&&!(o+c>=i.length);c++)s=Te(e.buffer,t[o+c],i[o+c],e.position-(t[o]-t[o+c]),u),a+=w.repeat(" ",r.indent)+ke((e.line+c+1).toString(),d)+" | "+s.str+` -`;return a.replace(/\n$/,"")}var Fn=Nn,Bn=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],Yn=["scalar","sequence","mapping"];function Hn(e){var r={};return e!==null&&Object.keys(e).forEach(function(n){e[n].forEach(function(t){r[String(t)]=n})}),r}function jn(e,r){if(r=r||{},Object.keys(r).forEach(function(n){if(Bn.indexOf(n)===-1)throw new S('Unknown option "'+n+'" is met in definition of "'+e+'" YAML type.')}),this.options=r,this.tag=e,this.kind=r.kind||null,this.resolve=r.resolve||function(){return!0},this.construct=r.construct||function(n){return n},this.instanceOf=r.instanceOf||null,this.predicate=r.predicate||null,this.represent=r.represent||null,this.representName=r.representName||null,this.defaultStyle=r.defaultStyle||null,this.multi=r.multi||!1,this.styleAliases=Hn(r.styleAliases||null),Yn.indexOf(this.kind)===-1)throw new S('Unknown kind "'+this.kind+'" is specified for "'+e+'" YAML type.')}var E=jn;function er(e,r){var n=[];return e[r].forEach(function(t){var i=n.length;n.forEach(function(l,o){l.tag===t.tag&&l.kind===t.kind&&l.multi===t.multi&&(i=o)}),n[i]=t}),n}function Un(){var e={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},r,n;function t(i){i.multi?(e.multi[i.kind].push(i),e.multi.fallback.push(i)):e[i.kind][i.tag]=e.fallback[i.tag]=i}for(r=0,n=arguments.length;r=0?"0b"+e.toString(2):"-0b"+e.toString(2).slice(1)},octal:function(e){return e>=0?"0o"+e.toString(8):"-0o"+e.toString(8).slice(1)},decimal:function(e){return e.toString(10)},hexadecimal:function(e){return e>=0?"0x"+e.toString(16).toUpperCase():"-0x"+e.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),st=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");function ut(e){return!(e===null||!st.test(e)||e[e.length-1]==="_")}function dt(e){var r,n;return r=e.replace(/_/g,"").toLowerCase(),n=r[0]==="-"?-1:1,"+-".indexOf(r[0])>=0&&(r=r.slice(1)),r===".inf"?n===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:r===".nan"?NaN:n*parseFloat(r,10)}var pt=/^[-+]?[0-9]+e/;function ft(e,r){var n;if(isNaN(e))switch(r){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===e)switch(r){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===e)switch(r){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(w.isNegativeZero(e))return"-0.0";return n=e.toString(10),pt.test(n)?n.replace("e",".e"):n}function ht(e){return Object.prototype.toString.call(e)==="[object Number]"&&(e%1!==0||w.isNegativeZero(e))}var mt=new E("tag:yaml.org,2002:float",{kind:"scalar",resolve:ut,construct:dt,predicate:ht,represent:ft,defaultStyle:"lowercase"}),gt=Kn.extend({implicit:[Xn,rt,ct,mt]}),yt=gt,yr=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),vr=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");function vt(e){return e===null?!1:yr.exec(e)!==null||vr.exec(e)!==null}function xt(e){var r,n,t,i,l,o,a,c=0,s=null,d,u,p;if(r=yr.exec(e),r===null&&(r=vr.exec(e)),r===null)throw new Error("Date resolve error");if(n=+r[1],t=+r[2]-1,i=+r[3],!r[4])return new Date(Date.UTC(n,t,i));if(l=+r[4],o=+r[5],a=+r[6],r[7]){for(c=r[7].slice(0,3);c.length<3;)c+="0";c=+c}return r[9]&&(d=+r[10],u=+(r[11]||0),s=(d*60+u)*6e4,r[9]==="-"&&(s=-s)),p=new Date(Date.UTC(n,t,i,l,o,a,c)),s&&p.setTime(p.getTime()-s),p}function wt(e){return e.toISOString()}var At=new E("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:vt,construct:xt,instanceOf:Date,represent:wt});function bt(e){return e==="<<"||e===null}var Et=new E("tag:yaml.org,2002:merge",{kind:"scalar",resolve:bt}),Ne=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/= -\r`;function _t(e){if(e===null)return!1;var r,n,t=0,i=e.length,l=Ne;for(n=0;n64)){if(r<0)return!1;t+=6}return t%8===0}function St(e){var r,n,t=e.replace(/[\r\n=]/g,""),i=t.length,l=Ne,o=0,a=[];for(r=0;r>16&255),a.push(o>>8&255),a.push(o&255)),o=o<<6|l.indexOf(t.charAt(r));return n=i%4*6,n===0?(a.push(o>>16&255),a.push(o>>8&255),a.push(o&255)):n===18?(a.push(o>>10&255),a.push(o>>2&255)):n===12&&a.push(o>>4&255),new Uint8Array(a)}function Ct(e){var r="",n=0,t,i,l=e.length,o=Ne;for(t=0;t>18&63],r+=o[n>>12&63],r+=o[n>>6&63],r+=o[n&63]),n=(n<<8)+e[t];return i=l%3,i===0?(r+=o[n>>18&63],r+=o[n>>12&63],r+=o[n>>6&63],r+=o[n&63]):i===2?(r+=o[n>>10&63],r+=o[n>>4&63],r+=o[n<<2&63],r+=o[64]):i===1&&(r+=o[n>>2&63],r+=o[n<<4&63],r+=o[64],r+=o[64]),r}function Lt(e){return Object.prototype.toString.call(e)==="[object Uint8Array]"}var Tt=new E("tag:yaml.org,2002:binary",{kind:"scalar",resolve:_t,construct:St,predicate:Lt,represent:Ct}),kt=Object.prototype.hasOwnProperty,Dt=Object.prototype.toString;function Pt(e){if(e===null)return!0;var r=[],n,t,i,l,o,a=e;for(n=0,t=a.length;n>10)+55296,(e-65536&1023)+56320)}function _r(e,r,n){r==="__proto__"?Object.defineProperty(e,r,{configurable:!0,enumerable:!0,writable:!0,value:n}):e[r]=n}var Sr=new Array(256),Cr=new Array(256);for(z=0;z<256;z++)Sr[z]=tr(z)?1:0,Cr[z]=tr(z);var z;function Zt(e,r){this.input=e,this.filename=r.filename||null,this.schema=r.schema||xr,this.onWarning=r.onWarning||null,this.legacy=r.legacy||!1,this.json=r.json||!1,this.listener=r.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=e.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function Lr(e,r){var n={name:e.filename,buffer:e.input.slice(0,-1),position:e.position,line:e.line,column:e.position-e.lineStart};return n.snippet=Fn(n),new S(r,n)}function m(e,r){throw Lr(e,r)}function he(e,r){e.onWarning&&e.onWarning.call(null,Lr(e,r))}var ir={YAML:function(r,n,t){var i,l,o;r.version!==null&&m(r,"duplication of %YAML directive"),t.length!==1&&m(r,"YAML directive accepts exactly one argument"),i=/^([0-9]+)\.([0-9]+)$/.exec(t[0]),i===null&&m(r,"ill-formed argument of the YAML directive"),l=parseInt(i[1],10),o=parseInt(i[2],10),l!==1&&m(r,"unacceptable YAML version of the document"),r.version=t[0],r.checkLineBreaks=o<2,o!==1&&o!==2&&he(r,"unsupported YAML version of the document")},TAG:function(r,n,t){var i,l;t.length!==2&&m(r,"TAG directive accepts exactly two arguments"),i=t[0],l=t[1],br.test(i)||m(r,"ill-formed tag handle (first argument) of the TAG directive"),H.call(r.tagMap,i)&&m(r,'there is a previously declared suffix for "'+i+'" tag handle'),Er.test(l)||m(r,"ill-formed tag prefix (second argument) of the TAG directive");try{l=decodeURIComponent(l)}catch(o){m(r,"tag prefix is malformed: "+l)}r.tagMap[i]=l}};function Y(e,r,n,t){var i,l,o,a;if(r1&&(e.result+=w.repeat(` -`,r-1))}function Xt(e,r,n){var t,i,l,o,a,c,s,d,u=e.kind,p=e.result,f;if(f=e.input.charCodeAt(e.position),C(f)||K(f)||f===35||f===38||f===42||f===33||f===124||f===62||f===39||f===34||f===37||f===64||f===96||(f===63||f===45)&&(i=e.input.charCodeAt(e.position+1),C(i)||n&&K(i)))return!1;for(e.kind="scalar",e.result="",l=o=e.position,a=!1;f!==0;){if(f===58){if(i=e.input.charCodeAt(e.position+1),C(i)||n&&K(i))break}else if(f===35){if(t=e.input.charCodeAt(e.position-1),C(t))break}else{if(e.position===e.lineStart&&ye(e)||n&&K(f))break;if(k(f))if(c=e.line,s=e.lineStart,d=e.lineIndent,x(e,!1,-1),e.lineIndent>=r){a=!0,f=e.input.charCodeAt(e.position);continue}else{e.position=o,e.line=c,e.lineStart=s,e.lineIndent=d;break}}a&&(Y(e,l,o,!1),Be(e,e.line-c),l=o=e.position,a=!1),G(f)||(o=e.position+1),f=e.input.charCodeAt(++e.position)}return Y(e,l,o,!1),e.result?!0:(e.kind=u,e.result=p,!1)}function Qt(e,r){var n,t,i;if(n=e.input.charCodeAt(e.position),n!==39)return!1;for(e.kind="scalar",e.result="",e.position++,t=i=e.position;(n=e.input.charCodeAt(e.position))!==0;)if(n===39)if(Y(e,t,e.position,!0),n=e.input.charCodeAt(++e.position),n===39)t=e.position,e.position++,i=e.position;else return!0;else k(n)?(Y(e,t,i,!0),Be(e,x(e,!1,r)),t=i=e.position):e.position===e.lineStart&&ye(e)?m(e,"unexpected end of the document within a single quoted scalar"):(e.position++,i=e.position);m(e,"unexpected end of the stream within a single quoted scalar")}function Jt(e,r){var n,t,i,l,o,a;if(a=e.input.charCodeAt(e.position),a!==34)return!1;for(e.kind="scalar",e.result="",e.position++,n=t=e.position;(a=e.input.charCodeAt(e.position))!==0;){if(a===34)return Y(e,n,e.position,!0),e.position++,!0;if(a===92){if(Y(e,n,e.position,!0),a=e.input.charCodeAt(++e.position),k(a))x(e,!1,r);else if(a<256&&Sr[a])e.result+=Cr[a],e.position++;else if((o=Kt(a))>0){for(i=o,l=0;i>0;i--)a=e.input.charCodeAt(++e.position),(o=Vt(a))>=0?l=(l<<4)+o:m(e,"expected hexadecimal character");e.result+=Wt(l),e.position++}else m(e,"unknown escape sequence");n=t=e.position}else k(a)?(Y(e,n,t,!0),Be(e,x(e,!1,r)),n=t=e.position):e.position===e.lineStart&&ye(e)?m(e,"unexpected end of the document within a double quoted scalar"):(e.position++,t=e.position)}m(e,"unexpected end of the stream within a double quoted scalar")}function ei(e,r){var n=!0,t,i,l,o=e.tag,a,c=e.anchor,s,d,u,p,f,g=Object.create(null),y,v,A,h;if(h=e.input.charCodeAt(e.position),h===91)d=93,f=!1,a=[];else if(h===123)d=125,f=!0,a={};else return!1;for(e.anchor!==null&&(e.anchorMap[e.anchor]=a),h=e.input.charCodeAt(++e.position);h!==0;){if(x(e,!0,r),h=e.input.charCodeAt(e.position),h===d)return e.position++,e.tag=o,e.anchor=c,e.kind=f?"mapping":"sequence",e.result=a,!0;n?h===44&&m(e,"expected the node content, but found ','"):m(e,"missed comma between flow collection entries"),v=y=A=null,u=p=!1,h===63&&(s=e.input.charCodeAt(e.position+1),C(s)&&(u=p=!0,e.position++,x(e,!0,r))),t=e.line,i=e.lineStart,l=e.position,W(e,r,pe,!1,!0),v=e.tag,y=e.result,x(e,!0,r),h=e.input.charCodeAt(e.position),(p||e.line===t)&&h===58&&(u=!0,h=e.input.charCodeAt(++e.position),x(e,!0,r),W(e,r,pe,!1,!0),A=e.result),f?q(e,a,g,v,y,A,t,i,l):u?a.push(q(e,null,g,v,y,A,t,i,l)):a.push(y),x(e,!0,r),h=e.input.charCodeAt(e.position),h===44?(n=!0,h=e.input.charCodeAt(++e.position)):n=!1}m(e,"unexpected end of the stream within a flow collection")}function ri(e,r){var n,t,i=De,l=!1,o=!1,a=r,c=0,s=!1,d,u;if(u=e.input.charCodeAt(e.position),u===124)t=!1;else if(u===62)t=!0;else return!1;for(e.kind="scalar",e.result="";u!==0;)if(u=e.input.charCodeAt(++e.position),u===43||u===45)De===i?i=u===43?rr:Ut:m(e,"repeat of a chomping mode identifier");else if((d=qt(u))>=0)d===0?m(e,"bad explicit indentation width of a block scalar; it cannot be less than one"):o?m(e,"repeat of an indentation width identifier"):(a=r+d-1,o=!0);else break;if(G(u)){do u=e.input.charCodeAt(++e.position);while(G(u));if(u===35)do u=e.input.charCodeAt(++e.position);while(!k(u)&&u!==0)}for(;u!==0;){for(Fe(e),e.lineIndent=0,u=e.input.charCodeAt(e.position);(!o||e.lineIndenta&&(a=e.lineIndent),k(u)){c++;continue}if(e.lineIndentr)&&c!==0)m(e,"bad indentation of a sequence entry");else if(e.lineIndentr)&&(v&&(o=e.line,a=e.lineStart,c=e.position),W(e,r,fe,!0,i)&&(v?g=e.result:y=e.result),v||(q(e,u,p,f,g,y,o,a,c),f=g=y=null),x(e,!0,-1),h=e.input.charCodeAt(e.position)),(e.line===l||e.lineIndent>r)&&h!==0)m(e,"bad indentation of a mapping entry");else if(e.lineIndentr?c=1:e.lineIndent===r?c=0:e.lineIndentr?c=1:e.lineIndent===r?c=0:e.lineIndent tag; it should be "scalar", not "'+e.kind+'"'),u=0,p=e.implicitTypes.length;u"),e.result!==null&&g.kind!==e.kind&&m(e,"unacceptable node kind for !<"+e.tag+'> tag; it should be "'+g.kind+'", not "'+e.kind+'"'),g.resolve(e.result,e.tag)?(e.result=g.construct(e.result,e.tag),e.anchor!==null&&(e.anchorMap[e.anchor]=e.result)):m(e,"cannot resolve a node with !<"+e.tag+"> explicit tag")}return e.listener!==null&&e.listener("close",e),e.tag!==null||e.anchor!==null||d}function li(e){var r=e.position,n,t,i,l=!1,o;for(e.version=null,e.checkLineBreaks=e.legacy,e.tagMap=Object.create(null),e.anchorMap=Object.create(null);(o=e.input.charCodeAt(e.position))!==0&&(x(e,!0,-1),o=e.input.charCodeAt(e.position),!(e.lineIndent>0||o!==37));){for(l=!0,o=e.input.charCodeAt(++e.position),n=e.position;o!==0&&!C(o);)o=e.input.charCodeAt(++e.position);for(t=e.input.slice(n,e.position),i=[],t.length<1&&m(e,"directive name must not be less than one character in length");o!==0;){for(;G(o);)o=e.input.charCodeAt(++e.position);if(o===35){do o=e.input.charCodeAt(++e.position);while(o!==0&&!k(o));break}if(k(o))break;for(n=e.position;o!==0&&!C(o);)o=e.input.charCodeAt(++e.position);i.push(e.input.slice(n,e.position))}o!==0&&Fe(e),H.call(ir,t)?ir[t](e,t,i):he(e,'unknown document directive "'+t+'"')}if(x(e,!0,-1),e.lineIndent===0&&e.input.charCodeAt(e.position)===45&&e.input.charCodeAt(e.position+1)===45&&e.input.charCodeAt(e.position+2)===45?(e.position+=3,x(e,!0,-1)):l&&m(e,"directives end mark is expected"),W(e,e.lineIndent-1,fe,!1,!0),x(e,!0,-1),e.checkLineBreaks&&zt.test(e.input.slice(r,e.position))&&he(e,"non-ASCII line breaks are interpreted as content"),e.documents.push(e.result),e.position===e.lineStart&&ye(e)){e.input.charCodeAt(e.position)===46&&(e.position+=3,x(e,!0,-1));return}if(e.position=55296&&n<=56319&&r+1=56320&&t<=57343)?(n-55296)*1024+t-56320+65536:n}function Fr(e){var r=/^\n* /;return r.test(e)}var Br=1,Ie=2,Yr=3,Hr=4,V=5;function Ni(e,r,n,t,i,l,o,a){var c,s=0,d=null,u=!1,p=!1,f=t!==-1,g=-1,y=Ii(te(e,0))&&Mi(te(e,e.length-1));if(r||o)for(c=0;c=65536?c+=2:c++){if(s=te(e,c),!ae(s))return V;y=y&&sr(s,d,a),d=s}else{for(c=0;c=65536?c+=2:c++){if(s=te(e,c),s===oe)u=!0,f&&(p=p||c-g-1>t&&e[g+1]!==" ",g=c);else if(!ae(s))return V;y=y&&sr(s,d,a),d=s}p=p||f&&c-g-1>t&&e[g+1]!==" "}return!u&&!p?y&&!o&&!i(e)?Br:l===le?V:Ie:n>9&&Fr(e)?V:o?l===le?V:Ie:p?Hr:Yr}function Fi(e,r,n,t,i){e.dump=(function(){if(r.length===0)return e.quotingType===le?'""':"''";if(!e.noCompatMode&&(Li.indexOf(r)!==-1||Ti.test(r)))return e.quotingType===le?'"'+r+'"':"'"+r+"'";var l=e.indent*Math.max(1,n),o=e.lineWidth===-1?-1:Math.max(Math.min(e.lineWidth,40),e.lineWidth-l),a=t||e.flowLevel>-1&&n>=e.flowLevel;function c(s){return Oi(e,s)}switch(Ni(r,a,e.indent,o,c,e.quotingType,e.forceQuotes&&!t,i)){case Br:return r;case Ie:return"'"+r.replace(/'/g,"''")+"'";case Yr:return"|"+ur(r,e.indent)+dr(ar(r,l));case Hr:return">"+ur(r,e.indent)+dr(ar(Bi(r,o),l));case V:return'"'+Yi(r)+'"';default:throw new S("impossible error: invalid scalar style")}})()}function ur(e,r){var n=Fr(e)?String(r):"",t=e[e.length-1]===` -`,i=t&&(e[e.length-2]===` -`||e===` -`),l=i?"+":t?"":"-";return n+l+` -`}function dr(e){return e[e.length-1]===` -`?e.slice(0,-1):e}function Bi(e,r){for(var n=/(\n+)([^\n]*)/g,t=(function(){var s=e.indexOf(` -`);return s=s!==-1?s:e.length,n.lastIndex=s,pr(e.slice(0,s),r)})(),i=e[0]===` -`||e[0]===" ",l,o;o=n.exec(e);){var a=o[1],c=o[2];l=c[0]===" ",t+=a+(!i&&!l&&c!==""?` -`:"")+pr(c,r),i=l}return t}function pr(e,r){if(e===""||e[0]===" ")return e;for(var n=/ [^ ]/g,t,i=0,l,o=0,a=0,c="";t=n.exec(e);)a=t.index,a-i>r&&(l=o>i?o:a,c+=` -`+e.slice(i,l),i=l+1),o=a;return c+=` -`,e.length-i>r&&o>i?c+=e.slice(i,o)+` -`+e.slice(o+1):c+=e.slice(i),c.slice(1)}function Yi(e){for(var r="",n=0,t,i=0;i=65536?i+=2:i++)n=te(e,i),t=_[n],!t&&ae(n)?(r+=e[i],n>=65536&&(r+=e[i+1])):r+=t||Di(n);return r}function Hi(e,r,n){var t="",i=e.tag,l,o,a;for(l=0,o=n.length;l1024&&(d+="? "),d+=e.dump+(e.condenseFlow?'"':"")+":"+(e.condenseFlow?"":" "),R(e,r,s,!1,!1)&&(d+=e.dump,t+=d));e.tag=i,e.dump="{"+t+"}"}function Ui(e,r,n,t){var i="",l=e.tag,o=Object.keys(n),a,c,s,d,u,p;if(e.sortKeys===!0)o.sort();else if(typeof e.sortKeys=="function")o.sort(e.sortKeys);else if(e.sortKeys)throw new S("sortKeys must be a boolean or a function");for(a=0,c=o.length;a1024,u&&(e.dump&&oe===e.dump.charCodeAt(0)?p+="?":p+="? "),p+=e.dump,u&&(p+=Oe(e,r)),R(e,r+1,d,!0,u)&&(e.dump&&oe===e.dump.charCodeAt(0)?p+=":":p+=": ",p+=e.dump,i+=p));e.tag=l,e.dump=i||"{}"}function hr(e,r,n){var t,i,l,o,a,c;for(i=n?e.explicitTypes:e.implicitTypes,l=0,o=i.length;l tag resolver accepts not "'+c+'" style');e.dump=t}return!0}return!1}function R(e,r,n,t,i,l,o){e.tag=null,e.dump=n,hr(e,n,!1)||hr(e,n,!0);var a=Dr.call(e.dump),c=t,s;t&&(t=e.flowLevel<0||e.flowLevel>r);var d=a==="[object Object]"||a==="[object Array]",u,p;if(d&&(u=e.duplicates.indexOf(n),p=u!==-1),(e.tag!==null&&e.tag!=="?"||p||e.indent!==2&&r>0)&&(i=!1),p&&e.usedDuplicates[u])e.dump="*ref_"+u;else{if(d&&p&&!e.usedDuplicates[u]&&(e.usedDuplicates[u]=!0),a==="[object Object]")t&&Object.keys(e.dump).length!==0?(Ui(e,r,e.dump,i),p&&(e.dump="&ref_"+u+e.dump)):(ji(e,r,e.dump),p&&(e.dump="&ref_"+u+" "+e.dump));else if(a==="[object Array]")t&&e.dump.length!==0?(e.noArrayIndent&&!o&&r>0?fr(e,r-1,e.dump,i):fr(e,r,e.dump,i),p&&(e.dump="&ref_"+u+e.dump)):(Hi(e,r,e.dump),p&&(e.dump="&ref_"+u+" "+e.dump));else if(a==="[object String]")e.tag!=="?"&&Fi(e,e.dump,r,l,c);else{if(a==="[object Undefined]")return!1;if(e.skipInvalid)return!1;throw new S("unacceptable kind of an object to dump "+a)}e.tag!==null&&e.tag!=="?"&&(s=encodeURI(e.tag[0]==="!"?e.tag.slice(1):e.tag).replace(/!/g,"%21"),e.tag[0]==="!"?s="!"+s:s.slice(0,18)==="tag:yaml.org,2002:"?s="!!"+s.slice(18):s="!<"+s+">",e.dump=s+" "+e.dump)}return!0}function $i(e,r){var n=[],t=[],i,l;for(Me(e,n,t),i=0,l=t.length;is>0&&c.trim()===Ur);if(t<0)throw new b("Pumler YAML header is missing the closing --- delimiter");let i=n.slice(1,t).join(` -`),l=n.slice(t+1).join(` -`);if(l.trim()==="")throw new b("Pumler diagram source is required");return{metadata:qi(i),source:l}}function qi(e){let r;try{r=jr(e)}catch(a){let c=a instanceof Error?a.message:"invalid YAML";throw new b(`Invalid Pumler YAML header: ${c}`)}if(!ro(r))throw new b("Pumler YAML header must be an object");let n=Object.keys(r).filter(a=>!Ki.includes(a));if(n.length>0)throw new b(`Unsupported Pumler setting: ${n.join(", ")}`);let t=Wi(r.provider),i=Zi(t,r.type),l=Xi(r.theme),o=Qi(r.title);return{provider:t,type:i,theme:l,...o?{title:o}:{}}}function Wi(e){if(typeof e!="string"||e.trim()==="")throw new b('Pumler setting "provider" is required');let r=e.trim();if(!Ji(r))throw new b(`Unsupported Pumler provider "${r}". Supported providers: ${Ce.join(", ")}`);return r}function Zi(e,r){if(typeof r!="string"||r.trim()==="")throw new b('Pumler setting "type" is required');let n=r.trim(),t=qe[e];if(!t.includes(n))throw new b(`Unsupported ${e} diagram type "${n}". Supported types: ${t.join(", ")}`);return n}function Xi(e){if(e==null)return Ke;if(typeof e!="string"||e.trim()==="")throw new b('Pumler setting "theme" must be one of: auto, dark, light');let r=e.trim();if(!eo(r))throw new b(`Unsupported Pumler theme "${r}". Supported themes: ${Le.join(", ")}`);return r}function Qi(e){if(e==null)return null;if(typeof e!="string")throw new b('Pumler setting "title" must be a string');let r=e.trim();return r.length>0?r:null}function Ji(e){return Ce.includes(e)}function eo(e){return Le.includes(e)}function ro(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $r(e,r=document){return e==="dark"||e==="light"?e:(r instanceof Document?r.body:document.body).classList.contains("theme-dark")?"dark":"light"}var Vr=["width","height","max-width","max-height","min-width","min-height"],no=new Set(["svg","g","defs","desc","title","path","rect","circle","ellipse","line","polyline","polygon","text","tspan","textpath","use","marker","clippath","mask","pattern","lineargradient","radialgradient","stop","style","filter","feblend","fecolormatrix","fecomponenttransfer","fecomposite","fedropshadow","feflood","fegaussianblur","femerge","femergenode","feoffset"]),to=new Set(["id","class","style","transform","opacity","fill","fill-opacity","fill-rule","stroke","stroke-opacity","stroke-width","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-dasharray","stroke-dashoffset","clip-path","clip-rule","mask","filter","marker-start","marker-mid","marker-end","color","display","visibility"]),io=new Map([["svg",["viewbox","width","height","x","y","preserveaspectratio","version","xmlns"]],["path",["d","pathlength"]],["rect",["x","y","width","height","rx","ry"]],["circle",["cx","cy","r"]],["ellipse",["cx","cy","rx","ry"]],["line",["x1","y1","x2","y2"]],["polyline",["points"]],["polygon",["points"]],["text",["x","y","dx","dy","rotate","textlength","lengthadjust","text-anchor","dominant-baseline","alignment-baseline","font-family","font-size","font-weight","font-style","font-stretch","letter-spacing","word-spacing"]],["tspan",["x","y","dx","dy","rotate","textlength","lengthadjust","text-anchor","dominant-baseline","alignment-baseline","font-family","font-size","font-weight","font-style","font-stretch","letter-spacing","word-spacing"]],["textpath",["href","xlink:href","startoffset","method","spacing"]],["use",["href","xlink:href","x","y","width","height"]],["marker",["refx","refy","markerwidth","markerheight","markerunits","orient","viewbox","preserveaspectratio"]],["clippath",["clippathunits"]],["mask",["x","y","width","height","maskunits","maskcontentunits"]],["pattern",["x","y","width","height","patternunits","patterncontentunits","patterntransform","viewbox","preserveaspectratio"]],["lineargradient",["x1","y1","x2","y2","gradientunits","gradienttransform","spreadmethod","href","xlink:href"]],["radialgradient",["cx","cy","r","fx","fy","fr","gradientunits","gradienttransform","spreadmethod","href","xlink:href"]],["stop",["offset","stop-color","stop-opacity"]],["filter",["x","y","width","height","filterunits","primitiveunits","color-interpolation-filters"]],["feblend",["in","in2","mode","result"]],["fecolormatrix",["in","type","values","result"]],["fecomponenttransfer",["in","result"]],["fecomposite",["in","in2","operator","k1","k2","k3","k4","result"]],["fedropshadow",["dx","dy","stddeviation","flood-color","flood-opacity","result"]],["feflood",["flood-color","flood-opacity","result"]],["fegaussianblur",["in","stddeviation","edgemode","result"]],["femerge",["result"]],["femergenode",["in"]],["feoffset",["in","dx","dy","result"]]].map(([e,r])=>[e,new Set(r)])),oo=new Set(["href","xlink:href"]),lo=new Set(["alignment-baseline","clip-path","clip-rule","color","display","dominant-baseline","fill","fill-opacity","fill-rule","filter","font","font-family","font-size","font-stretch","font-style","font-weight","letter-spacing","marker-end","marker-mid","marker-start","mask","opacity","stop-color","stop-opacity","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-anchor","visibility","word-spacing",...Vr]);function Kr(e,r){let t=new DOMParser().parseFromString(e,"image/svg+xml"),i=t.querySelector("parsererror"),l=t.querySelector("svg");if(i||!l)throw new Error("Pumler API returned invalid SVG");t.querySelectorAll("*").forEach(a=>{var s;let c=ao(a);if(!no.has(c)){a.remove();return}c==="style"&&(a.textContent=so((s=a.textContent)!=null?s:""));for(let d of Array.from(a.attributes)){let u=d.name.toLowerCase(),p=d.value.trim();if(!co(c,u)){a.removeAttribute(d.name);continue}if(oo.has(u)&&!Wr(p)){a.removeAttribute(d.name);continue}if(u==="style"){let f=Xr(p);f?a.setAttribute(d.name,f):a.removeAttribute(d.name);continue}Zr(p)||a.removeAttribute(d.name)}});let o=document.importNode(l,!0);return r&&Qr(o,r),ho(o),o}function qr(e,r){let n=e.cloneNode(!0);return Qr(n,r),n}function ao(e){return e.localName.toLowerCase()}function co(e,r){var n;return to.has(r)||!!((n=io.get(e))!=null&&n.has(r))}function Wr(e){return/^#[^\s"'<>]+$/.test(e.trim())}function Zr(e){let r=e.trim().toLowerCase();return r.includes("javascript:")||r.includes("vbscript:")||r.includes("data:")||r.includes("expression(")||r.includes("-moz-binding")||r.includes("behavior:")?!1:po(e)}function so(e){var l,o;let r=[],n=e.replace(/@import[^;]+;/gi,""),t=/([^{}]+)\{([^{}]*)\}/g,i;for(;(i=t.exec(n))!==null;){let a=(l=i[1])==null?void 0:l.trim(),c=Xr((o=i[2])!=null?o:"");a&&c&&uo(a)&&r.push(`${a} { ${c} }`)}return r.join(` -`)}function uo(e){return!e.includes("@")&&/^[a-zA-Z0-9\s.#:[\],>+~*="'()_-]+$/.test(e)}function Xr(e){return e.split(";").map(r=>r.trim()).filter(Boolean).map(r=>{let n=r.indexOf(":");if(n<=0)return null;let t=r.slice(0,n).trim().toLowerCase(),i=r.slice(n+1).trim();return!lo.has(t)||!Zr(i)?null:`${t}: ${i}`}).filter(r=>!!r).join("; ")}function po(e){var t;let r=/url\(\s*(['"]?)(.*?)\1\s*\)/gi,n;for(;(n=r.exec(e))!==null;)if(!Wr((t=n[2])!=null?t:""))return!1;return!0}function Qr(e,r){let n=new Map,t=r.replace(/[^a-zA-Z0-9_-]/g,"-");[...e.hasAttribute("id")?[e]:[],...Array.from(e.querySelectorAll("[id]"))].forEach(l=>{let o=l.getAttribute("id");if(!o)return;let a=`${t}-${o}`;n.set(o,a),l.setAttribute("id",a)}),n.size!==0&&(e.querySelectorAll("*").forEach(l=>{for(let o of Array.from(l.attributes)){let a=zr(o.value,n);a!==o.value&&l.setAttribute(o.name,a)}}),e.querySelectorAll("style").forEach(l=>{let o=l.textContent;o&&(l.textContent=zr(o,n))}))}function zr(e,r){let n=e;return r.forEach((t,i)=>{let l=fo(i);n=n.replace(new RegExp(`url\\(\\s*(["']?)#${l}\\1\\s*\\)`,"g"),`url(#${t})`),n===`#${i}`&&(n=`#${t}`)}),n}function fo(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ho(e){mo(e),go(e),e.setAttribute("width","100%"),e.removeAttribute("height"),e.setAttribute("preserveAspectRatio","xMidYMid meet"),e.setAttribute("focusable","false")}function mo(e){if(e.getAttribute("viewBox"))return;let r=Gr(e.getAttribute("width")),n=Gr(e.getAttribute("height"));r===null||n===null||e.setAttribute("viewBox",`0 0 ${r} ${n}`)}function Gr(e){if(!e)return null;let r=e.trim().match(/^(\d+(?:\.\d+)?)(?:px)?$/i);if(!r)return null;let n=Number(r[1]);return Number.isFinite(n)&&n>0?n:null}function go(e){let r=e.getAttribute("style");if(!r)return;let n=r.split(";").map(t=>t.trim()).filter(Boolean).filter(t=>{var l;let i=(l=t.split(":",1)[0])==null?void 0:l.trim().toLowerCase();return i?!Vr.includes(i):!1});if(n.length===0){e.removeAttribute("style");return}e.setAttribute("style",n.join("; "))}var yo=700,vo=20,Jr=.5,en=4,rn=.25,nn=.1,je=1,Ae=class{constructor(r,n,t=F){this.client=r;this.cache=n;this.logger=t;this.pendingRenders=new Map;this.activeRenderTokens=new Map;this.inFlightRemoteRenders=new Map;this.sanitizedSvgTemplates=new Map;this.nextRenderToken=0;this.nextSvgIdScope=0}async render(r,n,t={}){var p,f,g,y,v,A,h,X,Q,O,I;let i=L(r);if((p=t.signal)!=null&&p.aborted){this.logger.debug("renderer.render.skip_pre_aborted",{debounceKey:t.debounceKey,sourceLength:r.length,sourceDigest:i});return}n.classList.add("pumler-render"),n.replaceChildren(Oo("Rendering Pumler diagram..."));let l=t.debounceKey||xo(n),o=++this.nextRenderToken;this.activeRenderTokens.set(l,o),this.logger.info("renderer.render.start",{debounceKey:l,token:o,sourceLength:r.length,sourceDigest:i,elementConnected:n.isConnected,signalAborted:(g=(f=t.signal)==null?void 0:f.aborted)!=null?g:!1});let a=()=>this.activeRenderTokens.get(l)===o,c,s;try{c=ve(r),s={provider:c.metadata.provider,type:c.metadata.type,theme:$r(c.metadata.theme),source:c.source},this.logger.info("renderer.render.parsed",{debounceKey:l,token:o,provider:s.provider,type:s.type,configuredTheme:c.metadata.theme,resolvedTheme:s.theme,diagramSourceLength:c.source.length,diagramSourceDigest:L(c.source)});let T=await((y=this.cache)==null?void 0:y.get(s));if(T){if((v=t.signal)!=null&&v.aborted||!a()){this.logger.debug("renderer.render.cached_skip_stale",{debounceKey:l,token:o,signalAborted:(h=(A=t.signal)==null?void 0:A.aborted)!=null?h:!1,isCurrentRender:a()});return}this.logger.info("renderer.render.cache_hit_replace",{debounceKey:l,token:o,svgLength:T.length}),this.replaceWithDiagram(n,T,c.metadata,s,l,o);return}}catch(T){this.logger.warn("renderer.render.parse_or_cache_error",{debounceKey:l,token:o,signalAborted:(Q=(X=t.signal)==null?void 0:X.aborted)!=null?Q:!1,isCurrentRender:a(),...P(T)}),!((O=t.signal)!=null&&O.aborted)&&a()&&n.replaceChildren(un(T));return}let d=this.pendingRenders.get(l);d&&(this.logger.debug("renderer.debounce.supersede_previous",{debounceKey:l,token:o,hadTimer:d.timer!==null}),d.timer!==null&&clearTimeout(d.timer),d.supersede());let u=(I=t.debounceMs)!=null?I:yo;return await new Promise(T=>{var ze,Ge;let j=null,M=!1,D=null,N=()=>{var ee,re,Ve;M||(M=!0,(ee=t.signal)==null||ee.removeEventListener("abort",N),this.logger.debug("renderer.render.promise_settle",{debounceKey:l,token:o,signalAborted:(Ve=(re=t.signal)==null?void 0:re.aborted)!=null?Ve:!1}),T())},ce=()=>{j!==null&&clearTimeout(j),D&&this.pendingRenders.get(l)===D&&this.pendingRenders.delete(l),this.logger.debug("renderer.debounce.cancel_scheduled",{debounceKey:l,token:o}),N()},J=()=>{var ee,re;D&&this.pendingRenders.get(l)===D&&this.pendingRenders.delete(l),this.logger.info("renderer.debounce.execute",{debounceKey:l,token:o,signalAborted:(re=(ee=t.signal)==null?void 0:ee.aborted)!=null?re:!1}),this.renderRemote(s,c.metadata,n,l,o,t.requireConnected,t.signal).finally(N)};if(u<=0){J();return}j=setTimeout(J,u),this.logger.info("renderer.debounce.schedule",{debounceKey:l,token:o,debounceMs:u}),D={timer:j,supersede:ce},this.pendingRenders.set(l,D),(ze=t.signal)==null||ze.addEventListener("abort",N,{once:!0}),(Ge=t.signal)!=null&&Ge.aborted&&(this.logger.debug("renderer.debounce.post_listener_aborted",{debounceKey:l,token:o}),N())})}async renderRemote(r,n,t,i,l,o,a){var s,d,u;if(o&&!t.isConnected){this.logger.info("renderer.remote.skip_detached",{debounceKey:i,token:l});return}let c=()=>this.activeRenderTokens.get(i)===l;try{this.logger.info("renderer.remote.await",{debounceKey:i,token:l,provider:r.provider,type:r.type,theme:r.theme,signalAborted:(s=a==null?void 0:a.aborted)!=null?s:!1});let p=await this.getOrStartRemoteRender(r);if(a!=null&&a.aborted||!c()){this.logger.info("renderer.remote.skip_replace_stale",{debounceKey:i,token:l,signalAborted:(d=a==null?void 0:a.aborted)!=null?d:!1,isCurrentRender:c(),svgLength:p.length});return}this.logger.info("renderer.remote.replace",{debounceKey:i,token:l,svgLength:p.length}),this.replaceWithDiagram(t,p,n,r,i,l)}catch(p){if(this.logger.warn("renderer.remote.error",{debounceKey:i,token:l,signalAborted:(u=a==null?void 0:a.aborted)!=null?u:!1,isCurrentRender:c(),...P(p)}),a!=null&&a.aborted||!c())return;t.replaceChildren(un(p))}}getOrStartRemoteRender(r){let n=$(r),t=L(n),i=this.inFlightRemoteRenders.get(n);if(i)return this.logger.info("renderer.remote.reuse_inflight",xe(r,t)),i;let l=Date.now();this.logger.info("renderer.remote.start_inflight",xe(r,t));let o=this.client.renderDiagram(r).then(async a=>{var c;return await((c=this.cache)==null?void 0:c.set(r,a)),this.logger.info("renderer.remote.done_inflight",{...xe(r,t),durationMs:Date.now()-l,svgLength:a.length}),a}).finally(()=>{this.inFlightRemoteRenders.delete(n),this.logger.debug("renderer.remote.clear_inflight",xe(r,t))});return this.inFlightRemoteRenders.set(n,o),o}replaceWithDiagram(r,n,t,i,l,o){let a=$(i),c=L(a),s=Date.now();this.logger.debug("renderer.dom.sanitize_start",{debounceKey:l,token:o,renderDigest:c,provider:t.provider,type:t.type,svgLength:n.length});let d=this.getOrCreateSanitizedSvgTemplate(a,c,n,t,l,o),u=Date.now(),p=qr(d,this.createSvgIdScope());p.classList.add("pumler-render__svg"),this.logger.debug("renderer.dom.clone_done",{debounceKey:l,token:o,renderDigest:c,durationMs:Date.now()-u});let f=Date.now();r.replaceChildren(wo(p,t)),this.logger.info("renderer.dom.replace_done",{debounceKey:l,token:o,renderDigest:c,provider:t.provider,type:t.type,title:t.title,replaceDurationMs:Date.now()-f,totalDurationMs:Date.now()-s})}getOrCreateSanitizedSvgTemplate(r,n,t,i,l,o){let a=this.sanitizedSvgTemplates.get(r);if(a)return this.sanitizedSvgTemplates.delete(r),this.sanitizedSvgTemplates.set(r,a),this.logger.debug("renderer.dom.template_cache_hit",{debounceKey:l,token:o,renderDigest:n,provider:i.provider,type:i.type,templateCacheSize:this.sanitizedSvgTemplates.size}),a;let c=Date.now(),s=Kr(t);for(this.sanitizedSvgTemplates.set(r,s);this.sanitizedSvgTemplates.size>vo;){let d=this.sanitizedSvgTemplates.keys().next().value;if(!d)break;this.sanitizedSvgTemplates.delete(d)}return this.logger.info("renderer.dom.template_cache_miss",{debounceKey:l,token:o,renderDigest:n,provider:i.provider,type:i.type,sanitizeDurationMs:Date.now()-c,svgLength:t.length,templateCacheSize:this.sanitizedSvgTemplates.size}),s}createSvgIdScope(){return this.nextSvgIdScope+=1,`pumler-svg-${this.nextSvgIdScope}`}};function xe(e,r){return{provider:e.provider,type:e.type,theme:e.theme,sourceLength:e.source.length,sourceDigest:L(e.source),renderDigest:r}}var tn=new WeakMap,on=0;function xo(e){let r=tn.get(e);if(r)return r;on+=1;let n=`element-${on}`;return tn.set(e,n),n}function wo(e,r){let n=document.createElement("div");n.className="pumler-render__figure";let t=document.createElement("div");t.className="pumler-render__viewport",t.appendChild(e);let i=!0,l=Ao(r,e,()=>{o(!i)}),o=a=>{i=a,t.hidden=!a,l.button.setAttribute("aria-expanded",String(a)),l.button.setAttribute("aria-label",a?"Collapse Pumler diagram":"Expand Pumler diagram"),l.button.setAttribute("title",a?"Collapse diagram":"Expand diagram"),l.stateIcon.replaceChildren(a?Eo():_o()),n.classList.toggle("is-collapsed",!a)};return o(!0),n.appendChild(l.button),n.appendChild(t),n}function Ao(e,r,n){let t=document.createElement("button");t.type="button",t.className="pumler-render__collapsed",t.addEventListener("click",n);let i=document.createElement("span");i.className="pumler-render__collapsed-icon",i.appendChild(Co());let l=document.createElement("span");l.className="pumler-render__panel-action pumler-render__open-button",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-label","Open large preview"),l.setAttribute("title","Open large preview"),l.appendChild(bo()),l.addEventListener("click",d=>{d.stopPropagation(),ln(r)}),l.addEventListener("keydown",d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),d.stopPropagation(),ln(r))});let o=document.createElement("span");o.className="pumler-render__collapsed-text";let a=document.createElement("span");a.className="pumler-render__collapsed-title",a.textContent=e.title||"Pumler diagram";let c=document.createElement("span");c.className="pumler-render__collapsed-meta",c.textContent=`${e.provider} / ${e.type}`;let s=document.createElement("span");return s.className="pumler-render__collapsed-expand",o.appendChild(a),o.appendChild(c),t.appendChild(i),t.appendChild(o),t.appendChild(l),t.appendChild(s),{button:t,stateIcon:s}}function bo(){let e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("class","pumler-render__open-icon"),e.setAttribute("viewBox","0 0 24 24"),e.setAttribute("aria-hidden","true"),e.setAttribute("focusable","false");let r=document.createElementNS("http://www.w3.org/2000/svg","circle");r.setAttribute("cx","11"),r.setAttribute("cy","11"),r.setAttribute("r","7");let n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1","16.5"),n.setAttribute("y1","16.5"),n.setAttribute("x2","21"),n.setAttribute("y2","21"),e.appendChild(r),e.appendChild(n),e}function Eo(){let e=Z("pumler-render__control-icon"),r=document.createElementNS("http://www.w3.org/2000/svg","polyline");return r.setAttribute("points","6 15 12 9 18 15"),e.appendChild(r),e}function _o(){let e=Z("pumler-render__control-icon"),r=document.createElementNS("http://www.w3.org/2000/svg","polyline");return r.setAttribute("points","6 9 12 15 18 9"),e.appendChild(r),e}function So(){let e=Z("pumler-render__control-icon"),r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("x1","18"),r.setAttribute("y1","6"),r.setAttribute("x2","6"),r.setAttribute("y2","18");let n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1","6"),n.setAttribute("y1","6"),n.setAttribute("x2","18"),n.setAttribute("y2","18"),e.appendChild(r),e.appendChild(n),e}function Co(){let e=Z("pumler-render__collapsed-diagram-icon");e.setAttribute("viewBox","0 0 400 400");let r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("x1","70"),r.setAttribute("y1","155"),r.setAttribute("x2","298"),r.setAttribute("y2","155"),r.setAttribute("class","pumler-render__collapsed-logo-primary");let n=document.createElementNS("http://www.w3.org/2000/svg","polygon");n.setAttribute("points","340,155 294,132 294,178"),n.setAttribute("class","pumler-render__collapsed-logo-primary-fill");let t=document.createElementNS("http://www.w3.org/2000/svg","line");t.setAttribute("x1","330"),t.setAttribute("y1","245"),t.setAttribute("x2","102"),t.setAttribute("y2","245"),t.setAttribute("class","pumler-render__collapsed-logo-secondary");let i=document.createElementNS("http://www.w3.org/2000/svg","polygon");return i.setAttribute("points","60,245 106,222 106,268"),i.setAttribute("class","pumler-render__collapsed-logo-secondary-fill"),e.appendChild(r),e.appendChild(n),e.appendChild(t),e.appendChild(i),e}function Z(e){let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("class",e),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("aria-hidden","true"),r.setAttribute("focusable","false"),r}function ln(e){let r=document.createElement("div");r.className="pumler-render__modal",r.setAttribute("role","dialog"),r.setAttribute("aria-modal","true");let n=document.createElement("div");n.className="pumler-render__modal-preview";let t=document.createElement("div");t.className="pumler-render__modal-toolbar";let i=document.createElement("button");i.type="button",i.className="pumler-render__icon-button pumler-render__modal-zoom-out",i.setAttribute("aria-label","Zoom out"),i.setAttribute("title","Zoom out"),i.appendChild(Po());let l=document.createElement("span");l.className="pumler-render__modal-zoom-value";let o=document.createElement("button");o.type="button",o.className="pumler-render__icon-button pumler-render__modal-zoom-in",o.setAttribute("aria-label","Zoom in"),o.setAttribute("title","Zoom in"),o.appendChild(Ro());let a=document.createElement("button");a.type="button",a.className="pumler-render__icon-button pumler-render__modal-close",a.setAttribute("aria-label","Close preview"),a.setAttribute("title","Close preview"),a.appendChild(So()),t.appendChild(i),t.appendChild(l),t.appendChild(o),t.appendChild(a);let c=document.createElement("div");c.className="pumler-render__modal-viewport";let s=e.cloneNode(!0);s.classList.remove("pumler-render__svg"),s.classList.add("pumler-render__modal-svg");let d=new Map,u=je,p=null,f=je,g=(h=u,X)=>{let Q=u,O=s.getBoundingClientRect(),I=c.getBoundingClientRect(),T=c.scrollLeft+O.left-I.left,j=c.scrollTop+O.top-I.top,M=To(X,O,I);u=Math.min(en,Math.max(Jr,h));let D=Math.round(u*100);s.setAttribute("style",`width: ${D}%;`),l.textContent=`${D}%`,i.disabled=u<=Jr,o.disabled=u>=en;let N=Q>0?u/Q:1,ce=cn(s.getBoundingClientRect().width,O.width,N),J=cn(s.getBoundingClientRect().height,O.height,N);if(X==="diagram-center"){c.scrollLeft=we(T+ce/2-ko(c,I)/2),c.scrollTop=we(j+J/2-Do(c,I)/2);return}M&&(c.scrollLeft=we(T+M.ratioX*ce-M.offsetX),c.scrollTop=we(j+M.ratioY*J-M.offsetY))};i.addEventListener("click",()=>{g(u-rn,"diagram-center")}),o.addEventListener("click",()=>{g(u+rn,"diagram-center")}),c.addEventListener("wheel",h=>{!h.ctrlKey&&!h.metaKey||(h.preventDefault(),g(u+(h.deltaY<0?nn:-nn),{clientX:h.clientX,clientY:h.clientY}))},{passive:!1}),c.addEventListener("pointerdown",h=>{d.set(h.pointerId,{x:h.clientX,y:h.clientY}),d.size===2&&(p=an(d),f=u)}),c.addEventListener("pointermove",h=>{d.has(h.pointerId)&&(d.set(h.pointerId,{x:h.clientX,y:h.clientY}),!(d.size!==2||p===null||p<=0)&&(h.preventDefault(),g(f*(an(d)/p),Lo(d))))});let y=h=>{d.delete(h.pointerId),d.size<2&&(p=null,f=u)};c.addEventListener("pointerup",y),c.addEventListener("pointercancel",y),c.addEventListener("pointerleave",y),c.addEventListener("lostpointercapture",y),c.addEventListener("dblclick",()=>{g(je)}),g();let v=()=>{document.removeEventListener("keydown",A),r.remove()},A=h=>{h.key==="Escape"&&v()};a.addEventListener("click",v),r.addEventListener("click",h=>{h.target===r&&v()}),document.addEventListener("keydown",A),c.appendChild(s),n.appendChild(t),n.appendChild(c),r.appendChild(n),document.body.appendChild(r),a.focus()}function an(e){let[r,n]=Array.from(e.values());return!r||!n?0:Math.hypot(n.x-r.x,n.y-r.y)}function Lo(e){let[r,n]=Array.from(e.values());return!r||!n?{clientX:0,clientY:0}:{clientX:(r.x+n.x)/2,clientY:(r.y+n.y)/2}}function To(e,r,n){return!e||e==="diagram-center"||r.width<=0||r.height<=0?null:{ratioX:sn((e.clientX-r.left)/r.width,0,1),ratioY:sn((e.clientY-r.top)/r.height,0,1),offsetX:e.clientX-n.left,offsetY:e.clientY-n.top}}function cn(e,r,n){return e>0?e:r>0?r*n:0}function ko(e,r){return e.clientWidth>0?e.clientWidth:r.width}function Do(e,r){return e.clientHeight>0?e.clientHeight:r.height}function sn(e,r,n){return Math.min(n,Math.max(r,e))}function we(e){return Math.max(0,Math.round(e))}function Po(){let e=Z("pumler-render__control-icon"),r=document.createElementNS("http://www.w3.org/2000/svg","line");return r.setAttribute("x1","5"),r.setAttribute("y1","12"),r.setAttribute("x2","19"),r.setAttribute("y2","12"),e.appendChild(r),e}function Ro(){let e=Z("pumler-render__control-icon"),r=document.createElementNS("http://www.w3.org/2000/svg","line");r.setAttribute("x1","5"),r.setAttribute("y1","12"),r.setAttribute("x2","19"),r.setAttribute("y2","12");let n=document.createElementNS("http://www.w3.org/2000/svg","line");return n.setAttribute("x1","12"),n.setAttribute("y1","5"),n.setAttribute("x2","12"),n.setAttribute("y2","19"),e.appendChild(r),e.appendChild(n),e}function Oo(e){let r=document.createElement("div");return r.className="pumler-render__status",r.textContent=e,r}function un(e){let r=document.createElement("div");r.className="pumler-render__error";let n=document.createElement("div");n.className="pumler-render__error-title",n.textContent=Io(e),r.appendChild(n);let t=document.createElement("div");if(t.className="pumler-render__error-message",t.textContent=e instanceof Error?e.message:"Unknown Pumler rendering error",r.appendChild(t),e instanceof U&&(e.line!==void 0||e.column!==void 0)){let i=document.createElement("div");i.className="pumler-render__error-location",i.textContent=Mo(e.line,e.column),r.appendChild(i)}return r}function Io(e){return e instanceof b?"Invalid Pumler diagram settings":"Pumler rendering failed"}function Mo(e,r){let n=[];return e!==void 0&&n.push(`line ${e}`),r!==void 0&&n.push(`column ${r}`),n.join(", ")}var be=class extends Ee.Plugin{async onload(){let r=this.manifest.dir?new se(this.app.vault.adapter,`${this.manifest.dir}/pumler-debug.log`):F,n=this.manifest.dir?new de(this.app.vault.adapter,`${this.manifest.dir}/cache`,void 0,r):void 0,t=new Ae(new ue(r),n,r);r.info("plugin.load",{pluginDir:this.manifest.dir,version:this.manifest.version}),this.registerWorkspaceLogging(r),this.registerMarkdownCodeBlockProcessor("pumler",(i,l,o)=>{let a=Fo(i,l,o);r.info("processor.block",{sourcePath:o.sourcePath,docId:o.docId,debounceKey:a,sourceLength:i.length,sourceDigest:L(i)}),o.addChild(new Ue(this.app,l,i,t,a,o.sourcePath,r))})}registerWorkspaceLogging(r){this.registerEvent(this.app.workspace.on("file-open",n=>{r.info("workspace.file_open",{path:n==null?void 0:n.path,activeLeaf:$e(this.app.workspace.activeLeaf)}),window.setTimeout(()=>{r.info("workspace.file_open.after_tick",pn(this.app))},0)})),this.registerEvent(this.app.workspace.on("active-leaf-change",n=>{r.info("workspace.active_leaf_change",{leaf:$e(n)})})),this.registerEvent(this.app.workspace.on("layout-change",()=>{r.info("workspace.layout_change",pn(this.app))}))}},Ue=class extends Ee.MarkdownRenderChild{constructor(n,t,i,l,o,a,c){super(t);this.app=n;this.source=i;this.renderer=l;this.debounceKey=o;this.sourcePath=a;this.logger=c;this.abortController=null}onload(){this.logger.info("render_child.load",this.createLogData()),this.registerEvent(this.app.workspace.on("css-change",()=>{No(this.source)&&(this.logger.info("render_child.css_change_rerender",this.createLogData()),this.render())})),this.render()}onunload(){this.logger.info("render_child.unload",this.createLogData()),this.abortActiveRender()}render(){this.abortActiveRender();let n=new AbortController;this.abortController=n,this.logger.info("render_child.render",this.createLogData()),this.renderer.render(this.source,this.containerEl,{debounceKey:this.debounceKey,signal:n.signal})}abortActiveRender(){this.abortController&&(this.logger.debug("render_child.abort_active",this.createLogData()),this.abortController.abort()),this.abortController=null}createLogData(){return{sourcePath:this.sourcePath,debounceKey:this.debounceKey,sourceLength:this.source.length,sourceDigest:L(this.source)}}};function No(e){try{return ve(e).metadata.theme==="auto"}catch(r){return!1}}function Fo(e,r,n){var i;let t=n.getSectionInfo(r);return t?`${n.docId}:${n.sourcePath}:${Bo(e,t.text,t.lineStart)}`:`${n.docId}:${n.sourcePath}:${(i=r.dataset.pumlerDebounceKey)!=null?i:Ho(r)}`}function Bo(e,r,n){let t=r.replace(/\r\n/g,` -`),i=e.replace(/\r\n/g,` -`),l=t.indexOf(i);return l<0?n:n+Yo(t.slice(0,l))}function Yo(e){return e.split(` -`).length-1}var dn=0;function Ho(e){dn+=1;let r=`element-${dn}`;return e.dataset.pumlerDebounceKey=r,r}function pn(e){return{activeLeaf:$e(e.workspace.activeLeaf),markdownLeafCount:e.workspace.getLeavesOfType("markdown").length}}function $e(e){var t,i,l;if(!e)return null;let r=e.view,n=e.getViewState();return{viewType:typeof r.getViewType=="function"?r.getViewType():n.type,stateType:n.type,mode:typeof r.getMode=="function"?r.getMode():void 0,stateMode:typeof((t=n.state)==null?void 0:t.mode)=="string"?n.state.mode:void 0,filePath:(i=r.file)==null?void 0:i.path,stateFile:typeof((l=n.state)==null?void 0:l.file)=="string"?n.state.file:void 0}} -/*! Bundled license information: - -js-yaml/dist/js-yaml.mjs: - (*! js-yaml 4.1.1 https://github.com/nodeca/js-yaml @license MIT *) -*/ diff --git a/package.json b/package.json index d4a9d1f..ed54823 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pumler-obsidian-plugin", - "version": "0.1.0", + "version": "1.0.0", "description": "Render PlantUML, Structurizr DSL, and Mermaid diagrams from pumler code blocks using the Pumler API.", "private": true, "type": "module",