Files

236 lines
357 KiB
JavaScript
Raw Permalink Normal View History

2025-10-25 20:35:10 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var Md=Object.create;var Ni=Object.defineProperty;var $d=Object.getOwnPropertyDescriptor;var Bd=Object.getOwnPropertyNames;var Ud=Object.getPrototypeOf,jd=Object.prototype.hasOwnProperty;var z=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Oe=(n,e)=>{for(var t in e)Ni(n,t,{get:e[t],enumerable:!0})},ds=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of Bd(e))!jd.call(n,r)&&r!==t&&Ni(n,r,{get:()=>e[r],enumerable:!(i=$d(e,r))||i.enumerable});return n};var eo=(n,e,t)=>(t=n!=null?Md(Ud(n)):{},ds(e||!n||!n.__esModule?Ni(t,"default",{value:n,enumerable:!0}):t,n)),Hd=n=>ds(Ni({},"__esModule",{value:!0}),n);var $o=z((vw,Zl)=>{"use strict";Zl.exports=Ph;function Ph(n,e){for(var t=new Array(arguments.length-1),i=0,r=2,o=!0;r<arguments.length;)t[i++]=arguments[r++];return new Promise(function(s,l){t[i]=function(p){if(o)if(o=!1,p)l(p);else{for(var m=new Array(arguments.length-1),h=0;h<m.length;)m[h++]=arguments[h];s.apply(null,m)}};try{n.apply(e||null,t)}catch(c){o&&(o=!1,l(c))}})}});var Xl=z(Kl=>{"use strict";var er=Kl;er.length=function(e){var t=e.length;if(!t)return 0;for(var i=0;--t%4>1&&e.charAt(t)==="=";)++i;return Math.ceil(e.length*3)/4-i};var _n=new Array(64),Vl=new Array(123);for(Ze=0;Ze<64;)Vl[_n[Ze]=Ze<26?Ze+65:Ze<52?Ze+71:Ze<62?Ze-4:Ze-59|43]=Ze++;var Ze;er.encode=function(e,t,i){for(var r=null,o=[],a=0,s=0,l;t<i;){var c=e[t++];switch(s){case 0:o[a++]=_n[c>>2],l=(c&3)<<4,s=1;break;case 1:o[a++]=_n[l|c>>4],l=(c&15)<<2,s=2;break;case 2:o[a++]=_n[l|c>>6],o[a++]=_n[c&63],s=0;break}a>8191&&((r||(r=[])).push(String.fromCharCode.apply(String,o)),a=0)}return s&&(o[a++]=_n[l],o[a++]=61,s===1&&(o[a++]=61)),r?(a&&r.push(String.fromCharCode.apply(String,o.slice(0,a))),r.join("")):String.fromCharCode.apply(String,o.slice(0,a))};var Gl="invalid encoding";er.decode=function(e,t,i){for(var r=i,o=0,a,s=0;s<e.length;){var l=e.charCodeAt(s++);if(l===61&&o>1)break;if((l=Vl[l])===void 0)throw Error(Gl);switch(o){case 0:a=l,o=1;break;case 1:t[i++]=a<<2|(l&48)>>4,a=l,o=2;break;case 2:t[i++]=(a&15)<<4|(l&60)>>2,a=l,o=3;break;case 3:t[i++]=(a&3)<<6|l,o=0;break}}if(o===1)throw Error(Gl);return i-r};er.test=function(e){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e)}});var Ql=z((Tw,Jl)=>{"use strict";Jl.exports=tr;function tr(){this._listeners={}}tr.prototype.on=function(e,t,i){return(this._listeners[e]||(this._listeners[e]=[])).push({fn:t,ctx:i||this}),this};tr.prototype.off=function(e,t){if(e===void 0)this._listeners={};else if(t===void 0)this._listeners[e]=[];else for(var i=this._listeners[e],r=0;r<i.length;)i[r].fn===t?i.splice(r,1):++r;return this};tr.prototype.emit=function(e){var t=this._listeners[e];if(t){for(var i=[],r=1;r<arguments.length;)i.push(arguments[r++]);for(r=0;r<t.length;)t[r].fn.apply(t[r++].ctx,i)}return this}});var ac=z((_w,oc)=>{"use strict";oc.exports=ec(ec);function ec(n){return typeof Float32Array!="undefined"?function(){var e=new Float32Array([-0]),t=new Uint8Array(e.buffer),i=t[3]===128;function r(l,c,p){e[0]=l,c[p]=t[0],c[p+1]=t[1],c[p+2]=t[2],c[p+3]=t[3]}function o(l,c,p){e[0]=l,c[p]=t[3],c[p+1]=t[2],c[p+2]=t[1],c[p+3]=t[0]}n.writeFloatLE=i?r:o,n.writeFloatBE=i?o:r;function a(l,c){return t[0]=l[c],t[1]=l[c+1],t[2]=l[c+2],t[3]=l[c+3],e[0]}function s(l,c){return t[3]=l[c],t[2]=l[c+1],t[1]=l[c+2],t[0]=l[c+3],e[0]}n.readFloatLE=i?a:s,n.readFloatBE=i?s:a}():function(){function e(i,r,o,a){var s=r<0?1:0;if(s&&(r=-r),r===0)i(1/r>0?0:2147483648,o,a);else if(isNaN(r))i(2143289344,o,a);else if(r>34028234663852886e22)i((s<<31|2139095040)>>>0,o,a);else if(r<11754943508222875e-54)i((s<<31|Math.round(r/1401298464324817e-60))>>>0,o,a);else{var l=Math.floor(Math.log(r)/Math.LN2),c=Math.round(r*Math.pow(2,-l)*8388608)&8388607;i((s<<31|l+127<<23|c)>>>0,o,a)}}n.writeFloatLE=e.bind(null,tc),n.writeFloatBE=e.bind(null,nc);function t(i,r,o){var a=i(r,o),s=(a>>31)*2+1,l=a>>>23&255,c=a&8388607;return l===255?c?NaN:s*(1/0):l===0?s*1401298464324817e-60*c:s*Math.pow(2,l-150)*(c+8388608)}n.readFloatLE=t.bind(null,ic),n.readFloatBE=t.bind(null,rc)}(),typeof Float64Array!="undefined"?
`+t.join(`
`)+`
}`}return i.toString=r,i}Qo.verbose=!1});var jc=z(($w,Uc)=>{"use strict";Uc.exports=si;var Yh=$o(),zh=Bo(),ea=zh("fs");function si(n,e,t){return typeof e=="function"?(t=e,e={}):e||(e={}),t?!e.xhr&&ea&&ea.readFile?ea.readFile(n,function(r,o){return r&&typeof XMLHttpRequest!="undefined"?si.xhr(n,e,t):r?t(r):t(null,e.binary?o:o.toString("utf8"))}):si.xhr(n,e,t):Yh(si,this,n,e)}si.xhr=function(e,t,i){var r=new XMLHttpRequest;r.onreadystatechange=function(){if(r.readyState===4){if(r.status!==0&&r.status!==200)return i(Error("status "+r.status));if(t.binary){var a=r.response;if(!a){a=[];for(var s=0;s<r.responseText.length;++s)a.push(r.responseText.charCodeAt(s)&255)}return i(null,typeof Uint8Array!="undefined"?new Uint8Array(a):a)}return i(null,r.responseText)}},t.binary&&("overrideMimeType"in r&&r.overrideMimeType("text/plain; charset=x-user-defined"),r.responseType="arraybuffer"),r.open("GET",e),r.send()}});var Wc=z(qc=>{"use strict";var na=qc,Hc=na.isAbsolute=function(e){return/^(?:\/|\w+:)/.test(e)},ta=na.normalize=function(e){e=e.replace(/\\/g,"/").replace(/\/{2,}/g,"/");var t=e.split("/"),i=Hc(e),r="";i&&(r=t.shift()+"/");for(var o=0;o<t.length;)t[o]===".."?o>0&&t[o-1]!==".."?t.splice(--o,2):i?t.splice(o,1):++o:t[o]==="."?t.splice(o,1):++o;return r+t.join("/")};na.resolve=function(e,t,i){return i||(t=ta(t)),Hc(t)?t:(i||(e=ta(e)),(e=e.replace(/(?:\/|^)[^/]+$/,"")).length?ta(e+"/"+t):t)}});var an=z(Yc=>{"use strict";var li=Yc,Zh=be(),Gh=["double","float","int32","uint32","sint32","fixed32","sfixed32","int64","uint64","sint64","fixed64","sfixed64","bool","string","bytes"];function ci(n,e){var t=0,i={};for(e|=0;t<n.length;)i[Gh[t+e]]=n[t++];return i}li.basic=ci([1,5,0,0,0,5,5,0,0,0,1,1,0,2,2]);li.defaults=ci([0,0,0,0,0,0,0,0,0,0,0,0,!1,"",Zh.emptyArray,null]);li.long=ci([0,0,0,1,1],7);li.mapKey=ci([0,0,0,5,5,0,0,0,1,1,0,2],2);li.packed=ci([1,5,0,0,0,5,5,0,0,0,1,1,0])});var Dt=z((jw,Gc)=>{"use strict";Gc.exports=je;var ar=sn();((je.prototype=Object.create(ar.prototype)).constructor=je).className="Field";var zc=Ke(),Zc=an(),fe=be(),ia,Vh=/^required|optional|repeated$/;je.fromJSON=function(e,t){return new je(e,t.id,t.type,t.rule,t.extend,t.options,t.comment)};function je(n,e,t,i,r,o,a){if(fe.isObject(i)?(a=r,o=i,i=r=void 0):fe.isObject(r)&&(a=o,o=r,r=void 0),ar.call(this,n,o),!fe.isInteger(e)||e<0)throw TypeError("id must be a non-negative integer");if(!fe.isString(t))throw TypeError("type must be a string");if(i!==void 0&&!Vh.test(i=i.toString().toLowerCase()))throw TypeError("rule must be a string rule");if(r!==void 0&&!fe.isString(r))throw TypeError("extend must be a string");i==="proto3_optional"&&(i="optional"),this.rule=i&&i!=="optional"?i:void 0,this.type=t,this.id=e,this.extend=r||void 0,this.required=i==="required",this.optional=!this.required,this.repeated=i==="repeated",this.map=!1,this.message=null,this.partOf=null,this.typeDefault=null,this.defaultValue=null,this.long=fe.Long?Zc.long[t]!==void 0:!1,this.bytes=t==="bytes",this.resolvedType=null,this.extensionField=null,this.declaringField=null,this._packed=null,this.comment=a}Object.defineProperty(je.prototype,"packed",{get:function(){return this._packed===null&&(this._packed=this.getOption("packed")!==!1),this._packed}});je.prototype.setOption=function(e,t,i){return e==="packed"&&(this._packed=null),ar.prototype.setOption.call(this,e,t,i)};je.prototype.toJSON=function(e){var t=e?!!e.keepComments:!1;return fe.toObject(["rule",this.rule!=="optional"&&this.rule||void 0,"type",this.type,"id",this.id,"extend",this.extend,"options",this.options,"comment",t?this.comment:void 0])};je.prototype.resolve=function(){if(this.resolved)return this;if((this.typeDefault=Zc.defaults[this.type])===void 0?(this.resolvedType=(this.declaringField?this.declaringField.parent:this.parent).lookupTypeOrEnum(this.type),this.resolvedType instanceof ia?this.typeDefault=null:this.typeDefault=this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]):this.options&&this.options.proto3_optional&&(this.typeDefault=null),this.options&&this.options.default!=null&&(this.typeDefault=this.optio
`,t:" "};function Op(n){return n.replace(Cg,function(e,t){switch(t){case"\\":case"":return t;default:return Ig[t]||""}})}Cp.unescape=Op;function Cp(n,e){n=n.toString();var t=0,i=n.length,r=1,o=0,a={},s=[],l=null;function c(A){return Error("illegal "+A+" (line "+r+")")}function p(){var A=l==="'"?kg:Ag;A.lastIndex=t-1;var O=A.exec(n);if(!O)throw c("string");return t=A.lastIndex,f(l),l=null,Op(O[1])}function m(A){return n.charAt(A)}function h(A,O,_){var k={type:n.charAt(A++),lineEmpty:!1,leading:_},x;e?x=2:x=3;var I=A-x,C;do if(--I<0||(C=n.charAt(I))===`
`){k.lineEmpty=!0;break}while(C===" "||C===" ");for(var N=n.substring(A,O).split(Rg),P=0;P<N.length;++P)N[P]=N[P].replace(e?Sg:Ng,"").trim();k.text=N.join(`
`).trim(),a[r]=k,o=r}function w(A){var O=v(A),_=n.substring(A,O),k=/^\s*\/\//.test(_);return k}function v(A){for(var O=A;O<i&&m(O)!==`
`;)O++;return O}function d(){if(s.length>0)return s.shift();if(l)return p();var A,O,_,k,x,I=t===0;do{if(t===i)return null;for(A=!1;Og.test(_=m(t));)if(_===`
`&&(I=!0,++r),++t===i)return null;if(m(t)==="/"){if(++t===i)throw c("comment");if(m(t)==="/")if(e){if(k=t,x=!1,w(t-1)){x=!0;do if(t=v(t),t===i||(t++,!I))break;while(w(t))}else t=Math.min(i,v(t)+1);x&&(h(k,t,I),I=!0),r++,A=!0}else{for(x=m(k=t+1)==="/";m(++t)!==`
`;)if(t===i)return null;++t,x&&(h(k,t-1,I),I=!0),++r,A=!0}else if((_=m(t))==="*"){k=t+1,x=e||m(k)==="*";do{if(_===`
`&&++r,++t===i)throw c("comment");O=_,_=m(t)}while(O!=="*"||_!=="/");++t,x&&(h(k,t-2,I),I=!0),A=!0}else return"/"}}while(A);var C=t;ka.lastIndex=0;var N=ka.test(m(C++));if(!N)for(;C<i&&!ka.test(m(C));)++C;var P=n.substring(t,t=C);return(P==='"'||P==="'")&&(l=P),P}function f(A){s.push(A)}function g(){if(!s.length){var A=d();if(A===null)return null;f(A)}return s[0]}function E(A,O){var _=g(),k=_===A;if(k)return d(),!0;if(!O)throw c("token '"+_+"', '"+A+"' expected");return!1}function T(A){var O=null,_;return A===void 0?(_=a[r-1],delete a[r-1],_&&(e||_.type==="*"||_.lineEmpty)&&(O=_.leading?_.text:null)):(o<A&&g(),_=a[A],delete a[A],_&&!_.lineEmpty&&(e||_.type==="/")&&(O=_.leading?null:_.text)),O}return Object.defineProperty({next:d,peek:g,push:f,skip:E,cmnt:T},"line",{get:function(){return r}})}});var $p=z((av,Mp)=>{"use strict";Mp.exports=gt;gt.filename=null;gt.defaults={keepCase:!1};var Dg=Na(),Dp=xr(),Fp=gr(),Lp=Dt(),Fg=pr(),Pp=An(),Lg=Ke(),Pg=fr(),Mg=ur(),Sa=an(),Ra=be(),$g=/^[1-9][0-9]*$/,Bg=/^-?[1-9][0-9]*$/,Ug=/^0[x][0-9a-fA-F]+$/,jg=/^-?0[x][0-9a-fA-F]+$/,Hg=/^0[0-7]+$/,qg=/^-?0[0-7]+$/,Wg=/^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,at=/^[a-zA-Z_][a-zA-Z_0-9]*$/,st=/^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,Yg=/^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;function gt(n,e,t){e instanceof Dp||(t=e,e=new Dp),t||(t=gt.defaults);var i=t.preferTrailingComment||!1,r=Dg(n,t.alternateCommentMode||!1),o=r.next,a=r.push,s=r.peek,l=r.skip,c=r.cmnt,p=!0,m,h,w,v,d=!1,f=e,g=t.keepCase?function(b){return b}:Ra.camelCase;function E(b,S,D){var F=gt.filename;return D||(gt.filename=null),Error("illegal "+(S||"token")+" '"+b+"' ("+(F?F+", ":"")+"line "+r.line+")")}function T(){var b=[],S;do{if((S=o())!=='"'&&S!=="'")throw E(S);b.push(o()),l(S),S=s()}while(S==='"'||S==="'");return b.join("")}function A(b){var S=o();switch(S){case"'":case'"':return a(S),T();case"true":case"TRUE":return!0;case"false":case"FALSE":return!1}try{return _(S,!0)}catch(D){if(b&&st.test(S))return S;throw E(S,"value")}}function O(b,S){var D,F;do S&&((D=s())==='"'||D==="'")?b.push(T()):b.push([F=k(o()),l("to",!0)?k(o()):F]);while(l(",",!0));l(";")}function _(b,S){var D=1;switch(b.charAt(0)==="-"&&(D=-1,b=b.substring(1)),b){case"inf":case"INF":case"Inf":return D*(1/0);case"nan":case"NAN":case"Nan":case"NaN":return NaN;case"0":return 0}if($g.test(b))return D*parseInt(b,10);if(Ug.test(b))return D*parseInt(b,16);if(Hg.test(b))return D*parseInt(b,8);if(Wg.test(b))return D*parseFloat(b);throw E(b,"number",S)}function k(b,S){switch(b){case"max":case"MAX":case"Max":return 536870911;case"0":return 0}if(!S&&b.charAt(0)==="-")throw E(b,"id");if(Bg.test(b))return parseInt(b,10);if(jg.test(b))return parseInt(b,16);if(qg.test(b))return parseInt(b,8);throw E(b,"id")}function x(){if(m!==void 0)throw E("package");if(m=o(),!st.test(m))throw E(m,"name");f=f.define(m),l(";")}function I(){var b=s(),S;switch(b){case"weak":S=w||(w=[]),o();break;case"public":o();default:S=h||(h=[]);break}b=T(),l(";"),S.push(b)}function C(){if(l("="),v=T(),d=v==="proto3",!d&&v!=="proto2")throw E(v,"syntax");l(";")}function N(b,S){switch(S){case"option":return U(b,S),l(";"),!0;case"message":return L(b,S),!0;case"enum":return Z(b,S),!0;case"service":return Yt(b,S),!0;case"extend":return u(b,S),!0}return!1}function P(b,S,D){var F=r.line;if(b&&(typeof b.comment!="string"&&(b.comment=c()),b.filename=gt.filename),l("{",!0)){for(var $;($=o())!=="}";)S($);l(";",!0)}else D&&D(),l(";"),b&&(typeof b.comment!="string"||i)&&(b.comment=c(F)||b.comment)}function L(b,S){if(!at.test(S=o()))throw E(S,"type name");var D=new Fp(S);P(D,function($){if(!N(D,$))switch($){case"map":M(D,$);break;case"required":case"repeated":j(D,$);break;case"optional":d?j(D,"proto3_optional"):j(D,"optional");break;case"oneof":ne(D,$);break;case"extensions":O(D.extensions||(D.extensions=[]));break;case"reserved":O(D.reserved||(D.reserved=[]),!0);break;default:if(!d||!st.test($))throw E($);a($),j(D,"optional");break}}),b.add(D)}function j(b,S,D){var F=o();if(F==="group"){Y(b,S);return}for(;F.endsWith(".")||s().startsWith(".");)F+=o()
`+i.fence+o+`
`+t.firstChild.textContent+`
`+i.fence+`
`}})}function su(n){n.addRule("strikethrough",{filter:["del","s","strike"],replacement:function(e){return"~~"+e+"~~"}})}var s0=Array.prototype.indexOf,l0=Array.prototype.every,Mt={},c0={left:":---",right:"---:",center:":---:"},Ma=null,lu=null,ou=new WeakMap;function p0(n){return n?(n.getAttribute("align")||n.style.textAlign||"").toLowerCase():""}function cu(n){return n?c0[n]:"---"}function pu(n,e){for(var t={left:0,right:0,center:0,"":0},i="",r=0;r<n.rows.length;++r){var o=n.rows[r];if(e<o.childNodes.length){var a=p0(o.childNodes[e]);++t[a],t[a]>t[i]&&(i=a)}}return i}Mt.tableCell={filter:["th","td"],replacement:function(n,e){return Ba(mu(e))?n:uu(n,e)}};Mt.tableRow={filter:"tr",replacement:function(n,e){let t=mu(e);if(Ba(t))return n;var i="";if(u0(e)){let a=hu(t);for(var r=0;r<a;r++){let s=r<e.childNodes.length?e.childNodes[r]:null;var o=cu(pu(t,r));i+=uu(o,s,r)}}return`
`+n+(i?`
`+i:"")}};Mt.table={filter:function(n,e){return n.nodeName==="TABLE"},replacement:function(n,e){if(du(e,lu)){let s=e.outerHTML,l=m0(e);return l===null||!l.classList.contains("joplin-table-wrapper")?`
<div class="joplin-table-wrapper">${s}</div>
`:s}else{if(Ba(e))return n;n=n.replace(/\n+/g,`
`);var t=n.trim().split(`
`);t.length>=2&&(t=t[1]);var i=/\| :?---/.test(t),r=hu(e),o="";if(r&&!i){o="|"+" |".repeat(r)+`
|`;for(var a=0;a<r;++a)o+=" "+cu(pu(e,a))+" |"}let s=e.caption&&e.caption.textContent||"",l=s?`${s}
`:"",c=`${o}${n}`.trimStart();return`
${l}${c}
`}}};Mt.tableCaption={filter:["caption"],replacement:()=>""};Mt.tableColgroup={filter:["colgroup","col"],replacement:()=>""};Mt.tableSection={filter:["thead","tbody","tfoot"],replacement:function(n){return n}};function u0(n){var e=n.parentNode;return e.nodeName==="THEAD"||e.firstChild===n&&(e.nodeName==="TABLE"||f0(e))&&l0.call(n.childNodes,function(t){return t.nodeName==="TH"})}function f0(n){var e=n.previousSibling;return n.nodeName==="TBODY"&&(!e||e.nodeName==="THEAD"&&/^\s*$/i.test(e.textContent))}function uu(n,e=null,t=null){t===null&&(t=s0.call(e.parentNode.childNodes,e));var i=" ";t===0&&(i="| ");let r=n.trim().replace(/\n\r/g,"<br>").replace(/\n/g,"<br>");for(r=r.replace(/\|+/g,"\\|");r.length<3;)r+=" ";return e&&(r=h0(r,e," ")),i+r+" |"}function fu(n){if(!n.childNodes)return!1;for(let e=0;e<n.childNodes.length;e++){let t=n.childNodes[e];if(t.nodeName==="TABLE"||fu(t))return!0}return!1}var $a=(n,e)=>{if(!n.childNodes)return!1;for(let t=0;t<n.childNodes.length;t++){let i=n.childNodes[t];if(e==="code"&&Ma&&Ma(i)||e.includes(i.nodeName)||$a(i,e))return!0}return!1},du=(n,e)=>{let t=["UL","OL","H1","H2","H3","H4","H5","H6","HR","BLOCKQUOTE"];return e.preserveNestedTables&&t.push("TABLE"),$a(n,"code")||$a(n,t)};function Ba(n){let e=ou.get(n);if(e!==void 0)return e;let t=d0(n);return ou.set(n,t),t}function d0(n){return!!(!n||!n.rows||n.rows.length===1&&n.rows[0].childNodes.length<=1||fu(n))}function m0(n){let e=n.parentNode;for(;e.nodeName!=="DIV";)if(e=e.parentNode,!e)return null;return e}function mu(n){let e=n.parentNode;for(;e.nodeName!=="TABLE";)if(e=e.parentNode,!e)return null;return e}function h0(n,e,t){let i=e.getAttribute("colspan")||1;for(let r=1;r<i;r++)n+=" | "+t.repeat(3);return n}function hu(n){let e=0;for(let t=0;t<n.rows.length;t++){let r=n.rows[t].childNodes.length;r>e&&(e=r)}return e}function gu(n){Ma=n.isCodeBlock,lu=n.options,n.keep(function(t){return!!(t.nodeName==="TABLE"&&du(t,n.options))});for(var e in Mt)n.addRule(e,Mt[e])}function yu(n){n.addRule("taskListItems",{filter:function(e){return e.type==="checkbox"&&e.parentNode.nodeName==="LI"},replacement:function(e,t){return(t.checked?"[x]":"[ ]")+" "}})}function g0(n){n.use([au,su,gu,yu])}cn.gfm=g0;cn.highlightedCodeBlock=au;cn.strikethrough=su;cn.tables=gu;cn.taskListItems=yu});var Jf=z(Pr=>{(function(n){n.parser=function(y,u){return new t(y,u)},n.SAXParser=t,n.SAXStream=c,n.createStream=l,n.MAX_BUFFER_LENGTH=64*1024;var e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];n.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function t(y,u){if(!(this instanceof t))return new t(y,u);var R=this;r(R),R.q=R.c="",R.bufferCheckPosition=n.MAX_BUFFER_LENGTH,R.opt=u||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!y,R.noscript=!!(y||R.opt.noscript),R.state=x.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(n.XML_ENTITIES):Object.create(n.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(v)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),C(R,"onready")}Object.create||(Object.create=function(y){function u(){}u.prototype=y;var R=new u;return R}),Object.keys||(Object.keys=function(y){var u=[];for(var R in y)y.hasOwnProperty(R)&&u.push(R);return u});function i(y){for(var u=Math.max(n.MAX_BUFFER_LENGTH,10),R=0,b=0,S=e.length;b<S;b++){var D=y[e[b]].length;if(D>u)switch(e[b]){case"textNode":P(y);break;case"cdata":N(y,"oncdata",y.cdata),y.cdata="";break;case"script":N(y,"onscript",y.script),y.script="";break;default:j(y,"Max buffer length exceeded: "+e[b])}R=Math.max(R,D)}var F=n.MAX_BUFFER_LENGTH-R;y.bufferCheckPosition=F+y.position}function r(y){for(var u=0,R=e.length;u<R;u++)y[e[u]]=""}func
`||y==="\r"||y===" "}function A(y){return y==='"'||y==="'"}function O(y){return y===">"||T(y)}function _(y,u){return y.test(u)}function k(y,u){return!_(y,u)}var x=0;n.STATE={BEGIN:x++,BEGIN_WHITESPACE:x++,TEXT:x++,TEXT_ENTITY:x++,OPEN_WAKA:x++,SGML_DECL:x++,SGML_DECL_QUOTED:x++,DOCTYPE:x++,DOCTYPE_QUOTED:x++,DOCTYPE_DTD:x++,DOCTYPE_DTD_QUOTED:x++,COMMENT_STARTING:x++,COMMENT:x++,COMMENT_ENDING:x++,COMMENT_ENDED:x++,CDATA:x++,CDATA_ENDING:x++,CDATA_ENDING_2:x++,PROC_INST:x++,PROC_INST_BODY:x++,PROC_INST_ENDING:x++,OPEN_TAG:x++,OPEN_TAG_SLASH:x++,ATTRIB:x++,ATTRIB_NAME:x++,ATTRIB_NAME_SAW_WHITE:x++,ATTRIB_VALUE:x++,ATTRIB_VALUE_QUOTED:x++,ATTRIB_VALUE_CLOSED:x++,ATTRIB_VALUE_UNQUOTED:x++,ATTRIB_VALUE_ENTITY_Q:x++,ATTRIB_VALUE_ENTITY_U:x++,CLOSE_TAG:x++,CLOSE_TAG_SAW_WHITE:x++,SCRIPT:x++,SCRIPT_ENDING:x++},n.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},n.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(n.ENTITIES).forEach(function(y){var u=n.ENTITIES[y],R=typeof u=="number"?String.fromCharCode(u):u;n.ENTITIES[y]=R});for(var I in n.STATE)n.STATE[n.STATE[I]]=I;x=n.STATE;function C(y,u,R){y[u]&&y[u](R)}function N(y,u,R){y.textNode&&P(y),C(y,u,R)}function P(y){y.textNode=L(y.opt,y.textNode),y.textNode&&C(y,"ontext",y.textNode),y.textNode=""}function L(y,u){return y.trim&&(u=u.trim()),y.normalize&&(u=u.replace(/\s+/g," ")),u}function j(y,u){return P(y),y.trackPosition&&(u+=`
Line: `+y.line+`
Column: `+y.column+`
Char: `+y.c),u=new Error(u),y.error=u,C(y,"onerror",u),y}function Y(y){return y.sawRoot&&!y.closedRoot&&M(y,"Unclosed root tag"),y.state!==x.BEGIN&&y.state!==x.BEGIN_WHITESPACE&&y.state!==x.TEXT&&j(y,"Unexpected end"),P(y),y.c="",y.closed=!0,C(y,"onend"),t.call(y,y.strict,y.opt),y}function M(y,u){if(typeof y!="object"||!(y instanceof t))throw new Error("bad call to strictFail");y.strict&&j(y,u)}function ne(y){y.strict||(y.tagName=y.tagName[y.looseCase]());var u=y.tags[y.tags.length-1]||y,R=y.tag={name:y.tagName,attributes:{}};y.opt.xmlns&&(R.ns=u.ns),y.attribList.length=0,N(y,"onopentagstart",R)}function Z(y,u){var R=y.indexOf(":"),b=R<0?["",y]:y.split(":"),S=b[0],D=b[1];return u&&y==="xmlns"&&(S="xmlns",D=""),{prefix:S,local:D}}function pe(y){if(y.strict||(y.attribName=y.attribName[y.looseCase]()),y.attribList.indexOf(y.attribName)!==-1||y.tag.attributes.hasOwnProperty(y.attribName)){y.attribName=y.attribValue="";return}if(y.opt.xmlns){var u=Z(y.attribName,!0),R=u.prefix,b=u.local;if(R==="xmlns")if(b==="xml"&&y.attribValue!==h)M(y,"xml: prefix must be bound to "+h+`
Actual: `+y.attribValue);else if(b==="xmlns"&&y.attribValue!==w)M(y,"xmlns: prefix must be bound to "+w+`
Actual: `+y.attribValue);else{var S=y.tag,D=y.tags[y.tags.length-1]||y;S.ns===D.ns&&(S.ns=Object.create(D.ns)),S.ns[b]=y.attribValue}y.attribList.push([y.attribName,y.attribValue])}else y.tag.attributes[y.attribName]=y.attribValue,N(y,"onattribute",{name:y.attribName,value:y.attribValue});y.attribName=y.attribValue=""}function U(y,u){if(y.opt.xmlns){var R=y.tag,b=Z(y.tagName);R.prefix=b.prefix,R.local=b.local,R.uri=R.ns[b.prefix]||"",R.prefix&&!R.uri&&(M(y,"Unbound namespace prefix: "+JSON.stringify(y.tagName)),R.uri=b.prefix);var S=y.tags[y.tags.length-1]||y;R.ns&&S.ns!==R.ns&&Object.keys(R.ns).forEach(function(fs){N(y,"onopennamespace",{prefix:fs,uri:R.ns[fs]})});for(var D=0,F=y.attribList.length;D<F;D++){var $=y.attribList[D],W=$[0],te=$[1],ee=Z(W,!0),re=ee.prefix,gn=ee.local,Qr=re===""?"":R.ns[re]||"",zt={name:W,value:te,prefix:re,local:gn,uri:Qr};re&&re!=="xmlns"&&!Qr&&(M(y,"Unbound namespace prefix: "+JSON.stringify(re)),zt.uri=re),y.tag.attributes[W]=zt,N(y,"onattribute",zt)}y.attribList.length=0}y.tag.isSelfClosing=!!u,y.sawRoot=!0,y.tags.push(y.tag),N(y,"onopentag",y.tag),u||(!y.noscript&&y.tagName.toLowerCase()==="script"?y.state=x.SCRIPT:y.state=x.TEXT,y.tag=null,y.tagName=""),y.attribName=y.attribValue="",y.attribList.length=0}function Re(y){if(!y.tagName){M(y,"Weird empty close tag."),y.textNode+="</>",y.state=x.TEXT;return}if(y.script){if(y.tagName!=="script"){y.script+="</"+y.tagName+">",y.tagName="",y.state=x.SCRIPT;return}N(y,"onscript",y.script),y.script=""}var u=y.tags.length,R=y.tagName;y.strict||(R=R[y.looseCase]());for(var b=R;u--;){var S=y.tags[u];if(S.name!==b)M(y,"Unexpected close tag");else break}if(u<0){M(y,"Unmatched closing tag: "+y.tagName),y.textNode+="</"+y.tagName+">",y.state=x.TEXT;return}y.tagName=R;for(var D=y.tags.length;D-- >u;){var F=y.tag=y.tags.pop();y.tagName=y.tag.name,N(y,"onclosetag",y.tagName);var $={};for(var W in F.ns)$[W]=F.ns[W];var te=y.tags[y.tags.length-1]||y;y.opt.xmlns&&F.ns!==te.ns&&Object.keys(F.ns).forEach(function(ee){var re=F.ns[ee];N(y,"onclosenamespace",{prefix:ee,uri:re})})}u===0&&(y.closedRoot=!0),y.tagName=y.attribValue=y.attribName="",y.attribList.length=0,y.state=x.TEXT}function G(y){var u=y.entity,R=u.toLowerCase(),b,S="";return y.ENTITIES[u]?y.ENTITIES[u]:y.ENTITIES[R]?y.ENTITIES[R]:(u=R,u.charAt(0)==="#"&&(u.charAt(1)==="x"?(u=u.slice(2),b=parseInt(u,16),S=b.toString(16)):(u=u.slice(1),b=parseInt(u,10),S=b.toString(10))),u=u.replace(/^0+/,""),isNaN(b)||S.toLowerCase()!==u?(M(y,"Invalid character entity"),"&"+y.entity+";"):String.fromCodePoint(b))}function Q(y,u){u==="<"?(y.state=x.OPEN_WAKA,y.startTagPosition=y.position):T(u)||(M(y,"Non-whitespace before first tag."),y.textNode=u,y.state=x.TEXT)}function ct(y,u){var R="";return u<y.length&&(R=y.charAt(u)),R}function Yt(y){var u=this;if(this.error)throw this.error;if(u.closed)return j(u,"Cannot write after close. Assign an onready handler.");if(y===null)return Y(u);typeof y=="object"&&(y=y.toString());for(var R=0,b="";b=ct(y,R++),u.c=b,!!b;)switch(u.trackPosition&&(u.position++,b===`
`?(u.line++,u.column=0):u.column++),u.state){case x.BEGIN:if(u.state=x.BEGIN_WHITESPACE,b==="\uFEFF")continue;Q(u,b);continue;case x.BEGIN_WHITESPACE:Q(u,b);continue;case x.TEXT:if(u.sawRoot&&!u.closedRoot){for(var S=R-1;b&&b!=="<"&&b!=="&";)b=ct(y,R++),b&&u.trackPosition&&(u.position++,b===`
`?(u.line++,u.column=0):u.column++);u.textNode+=y.substring(S,R-1)}b==="<"&&!(u.sawRoot&&u.closedRoot&&!u.strict)?(u.state=x.OPEN_WAKA,u.startTagPosition=u.position):(!T(b)&&(!u.sawRoot||u.closedRoot)&&M(u,"Text data outside of root node."),b==="&"?u.state=x.TEXT_ENTITY:u.textNode+=b);continue;case x.SCRIPT:b==="<"?u.state=x.SCRIPT_ENDING:u.script+=b;continue;case x.SCRIPT_ENDING:b==="/"?u.state=x.CLOSE_TAG:(u.script+="<"+b,u.state=x.SCRIPT);continue;case x.OPEN_WAKA:if(b==="!")u.state=x.SGML_DECL,u.sgmlDecl="";else if(!T(b))if(_(d,b))u.state=x.OPEN_TAG,u.tagName=b;else if(b==="/")u.state=x.CLOSE_TAG,u.tagName="";else if(b==="?")u.state=x.PROC_INST,u.procInstName=u.procInstBody="";else{if(M(u,"Unencoded <"),u.startTagPosition+1<u.position){var D=u.position-u.startTagPosition;b=new Array(D).join(" ")+b}u.textNode+="<"+b,u.state=x.TEXT}continue;case x.SGML_DECL:(u.sgmlDecl+b).toUpperCase()===p?(N(u,"onopencdata"),u.state=x.CDATA,u.sgmlDecl="",u.cdata=""):u.sgmlDecl+b==="--"?(u.state=x.COMMENT,u.comment="",u.sgmlDecl=""):(u.sgmlDecl+b).toUpperCase()===m?(u.state=x.DOCTYPE,(u.doctype||u.sawRoot)&&M(u,"Inappropriately located doctype declaration"),u.doctype="",u.sgmlDecl=""):b===">"?(N(u,"onsgmldeclaration",u.sgmlDecl),u.sgmlDecl="",u.state=x.TEXT):(A(b)&&(u.state=x.SGML_DECL_QUOTED),u.sgmlDecl+=b);continue;case x.SGML_DECL_QUOTED:b===u.q&&(u.state=x.SGML_DECL,u.q=""),u.sgmlDecl+=b;continue;case x.DOCTYPE:b===">"?(u.state=x.TEXT,N(u,"ondoctype",u.doctype),u.doctype=!0):(u.doctype+=b,b==="["?u.state=x.DOCTYPE_DTD:A(b)&&(u.state=x.DOCTYPE_QUOTED,u.q=b));continue;case x.DOCTYPE_QUOTED:u.doctype+=b,b===u.q&&(u.q="",u.state=x.DOCTYPE);continue;case x.DOCTYPE_DTD:u.doctype+=b,b==="]"?u.state=x.DOCTYPE:A(b)&&(u.state=x.DOCTYPE_DTD_QUOTED,u.q=b);continue;case x.DOCTYPE_DTD_QUOTED:u.doctype+=b,b===u.q&&(u.state=x.DOCTYPE_DTD,u.q="");continue;case x.COMMENT:b==="-"?u.state=x.COMMENT_ENDING:u.comment+=b;continue;case x.COMMENT_ENDING:b==="-"?(u.state=x.COMMENT_ENDED,u.comment=L(u.opt,u.comment),u.comment&&N(u,"oncomment",u.comment),u.comment=""):(u.comment+="-"+b,u.state=x.COMMENT);continue;case x.COMMENT_ENDED:b!==">"?(M(u,"Malformed comment"),u.comment+="--"+b,u.state=x.COMMENT):u.state=x.TEXT;continue;case x.CDATA:b==="]"?u.state=x.CDATA_ENDING:u.cdata+=b;continue;case x.CDATA_ENDING:b==="]"?u.state=x.CDATA_ENDING_2:(u.cdata+="]"+b,u.state=x.CDATA);continue;case x.CDATA_ENDING_2:b===">"?(u.cdata&&N(u,"oncdata",u.cdata),N(u,"onclosecdata"),u.cdata="",u.state=x.TEXT):b==="]"?u.cdata+="]":(u.cdata+="]]"+b,u.state=x.CDATA);continue;case x.PROC_INST:b==="?"?u.state=x.PROC_INST_ENDING:T(b)?u.state=x.PROC_INST_BODY:u.procInstName+=b;continue;case x.PROC_INST_BODY:if(!u.procInstBody&&T(b))continue;b==="?"?u.state=x.PROC_INST_ENDING:u.procInstBody+=b;continue;case x.PROC_INST_ENDING:b===">"?(N(u,"onprocessinginstruction",{name:u.procInstName,body:u.procInstBody}),u.procInstName=u.procInstBody="",u.state=x.TEXT):(u.procInstBody+="?"+b,u.state=x.PROC_INST_BODY);continue;case x.OPEN_TAG:_(f,b)?u.tagName+=b:(ne(u),b===">"?U(u):b==="/"?u.state=x.OPEN_TAG_SLASH:(T(b)||M(u,"Invalid character in tag name"),u.state=x.ATTRIB));continue;case x.OPEN_TAG_SLASH:b===">"?(U(u,!0),Re(u)):(M(u,"Forward-slash in opening tag not followed by >"),u.state=x.ATTRIB);continue;case x.ATTRIB:if(T(b))continue;b===">"?U(u):b==="/"?u.state=x.OPEN_TAG_SLASH:_(d,b)?(u.attribName=b,u.attribValue="",u.state=x.ATTRIB_NAME):M(u,"Invalid attribute name");continue;case x.ATTRIB_NAME:b==="="?u.state=x.ATTRIB_VALUE:b===">"?(M(u,"Attribute without value"),u.attribValue=u.attribName,pe(u),U(u)):T(b)?u.state=x.ATTRIB_NAME_SAW_WHITE:_(f,b)?u.attribName+=b:M(u,"Invalid attribute name");continue;case x.ATTRIB_NAME_SAW_WHITE:if(b==="=")u.state=x.ATTRIB_VALUE;else{if(T(b))continue;M(u,"Attribute without value"),u.tag.attributes[u.attribName]="",u.attribValue="",N(u,"onattribute",{name:u.attribName,value:""}),u.attribName="",b===">"?U(u):_(d,b)?(u.attribName=b,u.state=x.ATTRIB_NAME):(M(u,"Invalid attribute name"),u.state=x.ATTRIB)}continue;case x.ATTRIB_VALUE:if(T(b))continue;A(b)?(u.q=b,u
`:"";function s(l,c,p){let m="",h,w=c,v=p?a+p:"",d=p+t,f="";return l=l||"",l.constructor===Array?(l.forEach(g=>{m+=s(g,w,p)}),m):(!w&&l.$name&&(w=l.$name),w&&(m=`${v}<${w}`,l.$attrs&&typeof l.$attrs=="object"&&(h=Object.keys(l.$attrs),h.forEach(g=>{m+=` ${g}=${JSON.stringify(String(l.$attrs[g]))}`}))),l==null||l===""||(typeof l=="object"?(h=Object.keys(l),h.forEach(g=>{let E=l[g];switch(g){case"$name":case"$attrs":break;case"$text":case"$markup":f+=s(E,null,d);break;case"$script":f+=s(E,"script",d);break;case"$cdata":f+=`${v}<![CDATA[${E}]]>`;break;default:f+=s(E,g,d)}})):f+=v+r(l)),w?f?m+=`>${f}${a}${p}</${w}>`:i?m+="/>":m+=`></${w}>`:m+=f,m)}return s(e,o,"")};rd.exports=Ei});var m1={};Oe(m1,{ATTACHMENT_EXTS:()=>$n,AUTH_REDIRECT_URI:()=>Yr,ImportContext:()=>Xr,ImporterModal:()=>ki,default:()=>Jr});module.exports=Hd(m1);var Wt=require("obsidian");var lt=require("obsidian");var vt=class{constructor(e){this.importer=e,this.app=e.app}};var Un=class extends vt{constructor(e,t){super(e),this.scan=t.mergableDataObject,this.objects=this.scan.mergeableDataObjectData.mergeableDataObjectEntry}async format(e,t){let i=[];for(let r of this.objects){if(!r.customMap)continue;let o=r.customMap.mapEntry[0].value.stringValue,a=await this.importer.database.get`
SELECT z_pk, zmedia, ztypeuti FROM ziccloudsyncingobject
WHERE zidentifier = ${o}`,s=await this.importer.resolveAttachment(a.Z_PK,"com.apple.notes.gallery");if(s||(s=await this.importer.resolveAttachment(a.ZMEDIA,a.ZTYPEUTI)),s)i.push(this.importer.app.fileManager.generateMarkdownLink(s,t));else return"**Cannot decode scan**"}return`
${i.join(`
`)}
`}};Un.protobufType="ciofecaforensics.MergableDataProto";var jn=class extends vt{constructor(t,i){super(t);this.rowLocations={};this.columnLocations={};this.table=i.mergableDataObject;let r=this.table.mergeableDataObjectData;this.keys=r.mergeableDataObjectKeyItem,this.types=r.mergeableDataObjectTypeItem,this.uuids=r.mergeableDataObjectUuidItem.map(this.uuidToString),this.objects=r.mergeableDataObjectEntry}async parse(){let t=this.objects.find(r=>r.customMap&&this.types[r.customMap.type]=="com.apple.notes.ICTable");if(!t)return null;let i=null;for(let r of t.customMap.mapEntry){let o=this.objects[r.value.objectIndex];switch(this.keys[r.key]){case"crRows":[this.rowLocations,this.rowCount]=this.findLocations(o);break;case"crColumns":[this.columnLocations,this.columnCount]=this.findLocations(o);break;case"cellColumns":i=o;break}}return i?await this.computeCells(i):null}findLocations(t){let i=[],r={};for(let o of t.orderedSet.ordering.array.attachment)i.push(this.uuidToString(o.uuid));for(let o of t.orderedSet.ordering.contents.element){let a=this.getTargetUuid(o.key),s=this.getTargetUuid(o.value);r[s]=i.indexOf(a)}return[r,i.length]}async computeCells(t){let i=Array(this.rowCount).fill(0).map(()=>Array(this.columnCount));for(let r of t.dictionary.element){let o=this.columnLocations[this.getTargetUuid(r.key)],a=this.objects[r.value.objectIndex];for(let s of a.dictionary.element){let l=this.rowLocations[this.getTargetUuid(s.key)],c=this.objects[s.value.objectIndex];if(!(l in i)||!c)continue;let p=new Zt(this.importer,c);i[l][o]=await p.format(!0)}}return i}async format(){let t=await this.parse();if(!t)return"";let i=`
`;for(let r=0;r<t.length;r++)i+=`| ${t[r].join(" | ")} |
`,r==0&&(i+=`|${" -- |".repeat(t[0].length)}
`);return i+`
`}getTargetUuid(t){let r=this.objects[t.objectIndex].customMap.mapEntry[0].value.unsignedIntegerValue;return this.uuids[r]}uuidToString(t){return Buffer.from(t).toString("hex")}};jn.protobufType="ciofecaforensics.MergableDataProto";var qd=/(^\s+|(?:\s+)?\n(?:\s+)?|\s+$)/,to=/applenotes:note\/([-0-9a-f]+)(?:\?ownerIdentifier=.*)?/,Wd=".AppleColorEmojiUI",hs=[100,101,102,103],Zt=class extends vt{constructor(t,i){super(t);this.listNumber=0;this.listIndent=0;this.multiRun=0;this.note=i.note}parseTokens(){let t=0,i=0,r=0,o=[];for(;t<this.note.attributeRun.length;){let a,s="",l=!0;do a=this.note.attributeRun[t],r=r+a.length,s+=this.note.noteText.substring(i,r),i=r,l=t==this.note.attributeRun.length-1?!1:gs(a,this.note.attributeRun[t+1]),t++;while(l);for(let c of s.split(qd))c&&o.push({attr:a,fragment:c})}return o}async format(t=!1,i=""){var s;let r=this.parseTokens(),o=!t&&this.importer.omitFirstLine&&this.note.noteText.contains(`
`),a="";for(let l=0;l<r.length;l++){let{attr:c,fragment:p}=r[l];if(o)if(p.contains(`
`)||c.attachmentInfo)o=!1;else continue;c.fragment=p,c.atLineStart=l==0?!0:(s=r[l-1])==null?void 0:s.fragment.contains(`
`),a+=this.formatMultiRun(c),!/\S/.test(c.fragment)||this.multiRun==1?a+=c.fragment:c.attachmentInfo?a+=await this.formatAttachment(c,i):c.superscript||c.underlined||c.color||c.font||this.multiRun==2?a+=await this.formatHtmlAttr(c):a+=await this.formatAttr(c)}return this.multiRun!=0&&(a+=this.formatMultiRun({})),t&&a.replace(`
`,"<br>").replace("|","&#124;"),a.trim()}formatMultiRun(t){var o,a,s,l,c,p;let i=(o=t.paragraphStyle)==null?void 0:o.styleType,r="";switch(this.multiRun){case 3:(((a=t.paragraphStyle)==null?void 0:a.indentAmount)==0&&!hs.includes(i)||Yd(t))&&(this.multiRun=0);break;case 1:i!=4&&(this.multiRun=0,r+="```\n");break;case 2:(s=t.paragraphStyle)!=null&&s.alignment||(this.multiRun=0,r+=`</p>
`);break}if(this.multiRun==0){if(i==4)this.multiRun=1,r+="\n```\n";else if(hs.includes(i))this.multiRun=3,(l=t.paragraphStyle)!=null&&l.indentAmount&&(r+=`
- &nbsp;
`);else if((c=t.paragraphStyle)!=null&&c.alignment){this.multiRun=2;let m=this.convertAlign((p=t==null?void 0:t.paragraphStyle)==null?void 0:p.alignment);r+=`
<p style="text-align:${m};margin:0">`}}return r}async formatHtmlAttr(t){var r,o;t.strikethrough&&(t.fragment=`<s>${t.fragment}</s>`),t.underlined&&(t.fragment=`<u>${t.fragment}</u>`),t.superscript==1&&(t.fragment=`<sup>${t.fragment}</sup>`),t.superscript==-1&&(t.fragment=`<sub>${t.fragment}</sub>`);let i="";switch(t.fontWeight){case 1:t.fragment=`<b>${t.fragment}</b>`;break;case 2:t.fragment=`<i>${t.fragment}</i>`;break;case 3:t.fragment=`<b><i>${t.fragment}</i></b>`;break}return(r=t.font)!=null&&r.fontName&&t.font.fontName!==Wd&&(i+=`font-family:${t.font.fontName};`),(o=t.font)!=null&&o.pointSize&&(i+=`font-size:${t.font.pointSize}pt;`),t.color&&(i+=`color:${this.convertColor(t.color)};`),t.link&&!to.test(t.link)?(i&&(i=` style="${i}"`),t.fragment=`<a href="${t.link}" rel="noopener" class="external-link" target="_blank"${i}>${t.fragment}</a>`):i&&(t.link&&(t.fragment=await this.getInternalLink(t.link,t.fragment)),t.fragment=`<span style="${i}">${t.fragment}</span>`),t.atLineStart?this.formatParagraph(t):t.fragment}async formatAttr(t){switch(t.fontWeight){case 1:t.fragment=`**${t.fragment}**`;break;case 2:t.fragment=`*${t.fragment}*`;break;case 3:t.fragment=`***${t.fragment}***`;break}return t.strikethrough&&(t.fragment=`~~${t.fragment}~~`),t.link&&t.link!=t.fragment&&(to.test(t.link)?t.fragment=await this.getInternalLink(t.link,t.fragment):t.fragment=`[${t.fragment}](${t.link})`),t.atLineStart?this.formatParagraph(t):t.fragment}formatParagraph(t){var a,s,l,c,p,m;let i=" ".repeat(((a=t.paragraphStyle)==null?void 0:a.indentAmount)||0),r=(s=t.paragraphStyle)==null?void 0:s.styleType,o=(l=t.paragraphStyle)!=null&&l.blockquote?"> ":"";switch(this.listNumber!=0&&(r!==102||this.listIndent!==((c=t.paragraphStyle)==null?void 0:c.indentAmount))&&(this.listIndent=((p=t.paragraphStyle)==null?void 0:p.indentAmount)||0,this.listNumber=0),r){case 0:return`${o}# ${t.fragment}`;case 1:return`${o}## ${t.fragment}`;case 2:return`${o}### ${t.fragment}`;case 101:case 100:return`${o}${i}- ${t.fragment}`;case 102:return this.listNumber++,`${o}${i}${this.listNumber}. ${t.fragment}`;case 103:let h=(m=t.paragraphStyle.checklist)!=null&&m.done?"[x]":"[ ]";return`${o}${i}- ${h} ${t.fragment}`}return this.multiRun==3&&(o+=i),`${o}${t.fragment}`}async formatAttachment(t,i){var c,p,m;let r,o,a;switch((c=t.attachmentInfo)==null?void 0:c.typeUti){case"com.apple.notes.inlinetextattachment.hashtag":case"com.apple.notes.inlinetextattachment.mention":return r=await this.importer.database.get`
SELECT zalttext FROM ziccloudsyncingobject
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,r.ZALTTEXT;case"com.apple.notes.inlinetextattachment.link":return r=await this.importer.database.get`
SELECT ztokencontentidentifier FROM ziccloudsyncingobject
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,await this.getInternalLink(r.ZTOKENCONTENTIDENTIFIER,void 0,i);case"com.apple.notes.table":return r=await this.importer.database.get`
SELECT hex(zmergeabledata1) as zhexdata FROM ziccloudsyncingobject
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,a=this.importer.decodeData(r.zhexdata,jn),await a.format();case"public.url":return r=await this.importer.database.get`
SELECT ztitle, zurlstring FROM ziccloudsyncingobject
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,`[**${r.ZTITLE}**](${r.ZURLSTRING})`;case"com.apple.notes.gallery":return r=await this.importer.database.get`
SELECT hex(zmergeabledata1) as zhexdata FROM ziccloudsyncingobject
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,a=this.importer.decodeData(r.zhexdata,Un),await a.format(!1,i);case"com.apple.paper.doc.scan":case"com.apple.drawing":case"com.apple.drawing.2":case"com.apple.paper":r=await this.importer.database.get`
SELECT z_pk, zhandwritingsummary
FROM (SELECT *, NULL AS zhandwritingsummary FROM ziccloudsyncingobject)
WHERE zidentifier = ${t.attachmentInfo.attachmentIdentifier}`,o=r==null?void 0:r.Z_PK;break;default:r=await this.importer.database.get`
SELECT zmedia FROM ziccloudsyncingobject
WHERE zidentifier = ${(p=t.attachmentInfo)==null?void 0:p.attachmentIdentifier}`,o=r==null?void 0:r.ZMEDIA;break}if(!o)return` **(unknown attachment: ${(m=t.attachmentInfo)==null?void 0:m.typeUti})** `;let s=await this.importer.resolveAttachment(o,t.attachmentInfo.typeUti),l=s?`
${this.app.fileManager.generateMarkdownLink(s,i)}
`:" **(error reading attachment)**";return this.importer.includeHandwriting&&r.ZHANDWRITINGSUMMARY&&(l=`
> [!Handwriting]-
> ${r.ZHANDWRITINGSUMMARY.replace(`
`,`
> `)}${l}`),l}async getInternalLink(t,i=void 0,r=""){let o=t.match(to)[1],a=await this.importer.database.get`
SELECT z_pk FROM ziccloudsyncingobject
WHERE zidentifier = ${o.toUpperCase()}`,s=await this.importer.resolveNote(a.Z_PK);return s?this.app.fileManager.generateMarkdownLink(s,r,void 0,i):"(unknown file link)"}convertColor(t){let i="#";for(let r of Object.values(t))i+=Math.floor(r*255).toString(16);return i}convertAlign(t){switch(t){default:return"left";case 1:return"center";case 2:return"right";case 3:return"justify"}}};Zt.protobufType="ciofecaforensics.Document";function Yd(n){return n.attachmentInfo?!n.attachmentInfo.typeUti.includes("com.apple.notes.inlinetextattachment"):!1}function gs(n,e){var t,i;if(!e||n.$type!=e.$type)return!1;for(let r of n.$type.fieldsArray)if(r.name!="length"){if((t=n[r.name])!=null&&t.$type&&((i=e[r.name])!=null&&i.$type)){if(!gs(n[r.name],e[r.name]))return!1}else if(n[r.name]!=e[r.name])return!1}return!0}var ys={nested:{ciofecaforensics:{nested:{Color:{fields:{red:{type:"float",id:1},green:{type:"float",id:2},blue:{type:"float",id:3},alpha:{type:"float",id:4}}},AttachmentInfo:{fields:{attachmentIdentifier:{type:"string",id:1},typeUti:{type:"string",id:2}}},Font:{fields:{fontName:{type:"string",id:1},pointSize:{type:"float",id:2},fontHints:{type:"int32",id:3}}},ParagraphStyle:{fields:{styleType:{type:"int32",id:1,options:{default:-1}},alignment:{type:"int32",id:2},indentAmount:{type:"int32",id:4},checklist:{type:"Checklist",id:5},blockquote:{type:"int32",id:8}}},Checklist:{fields:{uuid:{type:"bytes",id:1},done:{type:"int32",id:2}}},DictionaryElement:{fields:{key:{type:"ObjectID",id:1},value:{type:"ObjectID",id:2}}},Dictionary:{fields:{element:{rule:"repeated",type:"DictionaryElement",id:1,options:{packed:!1}}}},ObjectID:{fields:{unsignedIntegerValue:{type:"uint64",id:2},stringValue:{type:"string",id:4},objectIndex:{type:"int32",id:6}}},RegisterLatest:{fields:{contents:{type:"ObjectID",id:2}}},MapEntry:{fields:{key:{type:"int32",id:1},value:{type:"ObjectID",id:2}}},AttributeRun:{fields:{length:{type:"int32",id:1},paragraphStyle:{type:"ParagraphStyle",id:2},font:{type:"Font",id:3},fontWeight:{type:"int32",id:5},underlined:{type:"int32",id:6},strikethrough:{type:"int32",id:7},superscript:{type:"int32",id:8},link:{type:"string",id:9},color:{type:"Color",id:10},attachmentInfo:{type:"AttachmentInfo",id:12}}},NoteStoreProto:{fields:{document:{type:"Document",id:2}}},Document:{fields:{version:{type:"int32",id:2},note:{type:"Note",id:3}}},Note:{fields:{noteText:{type:"string",id:2},attributeRun:{rule:"repeated",type:"AttributeRun",id:5,options:{packed:!1}}}},MergableDataProto:{fields:{mergableDataObject:{type:"MergableDataObject",id:2}}},MergableDataObject:{fields:{version:{type:"int32",id:2},mergeableDataObjectData:{type:"MergeableDataObjectData",id:3}}},MergeableDataObjectData:{fields:{mergeableDataObjectEntry:{rule:"repeated",type:"MergeableDataObjectEntry",id:3,options:{packed:!1}},mergeableDataObjectKeyItem:{rule:"repeated",type:"string",id:4},mergeableDataObjectTypeItem:{rule:"repeated",type:"string",id:5},mergeableDataObjectUuidItem:{rule:"repeated",type:"bytes",id:6}}},MergeableDataObjectEntry:{fields:{registerLatest:{type:"RegisterLatest",id:1},list:{type:"List",id:5},dictionary:{type:"Dictionary",id:6},unknownMessage:{type:"UnknownMergeableDataObjectEntryMessage",id:9},note:{type:"Note",id:10},customMap:{type:"MergeableDataObjectMap",id:13},orderedSet:{type:"OrderedSet",id:16}}},UnknownMergeableDataObjectEntryMessage:{fields:{unknownEntry:{type:"UnknownMergeableDataObjectEntryMessageEntry",id:1}}},UnknownMergeableDataObjectEntryMessageEntry:{fields:{unknownInt1:{type:"int32",id:1},unknownInt2:{type:"int64",id:2}}},MergeableDataObjectMap:{fields:{type:{type:"int32",id:1},mapEntry:{rule:"repeated",type:"MapEntry",id:3,options:{packed:!1}}}},OrderedSet:{fields:{ordering:{type:"OrderedSetOrdering",id:1},elements:{type:"Dictionary",id:2}}},OrderedSetOrdering:{fields:{array:{type:"OrderedSetOrderingArray",id:1},contents:{type:"Dictionary",id:2}}},OrderedSetOrderingArray:{fields:{contents:{type:"Note",id:1},attachment:{rule:"repeated",type:"OrderedSetOrderingArrayAttachment",id:2,options:{packed:!1}}}},OrderedSetOrderingArrayAttachme
`],{type:"text/javascript"}));n({workerScripts:{inflate:[e],deflate:[e]}})}ql(Ii);var K=tn.Platform.isDesktopApp?window.require("node:original-fs"):null,$e=tn.Platform.isDesktopApp?K.promises:null,nn=tn.Platform.isDesktopApp?window.require("node:os"):null,q=tn.Platform.isDesktopApp?window.require("node:path"):null,ni=tn.Platform.isDesktopApp?window.require("node:url"):null,Wl=tn.Platform.isDesktopApp?window.require("node:zlib"):null;function Ji(n,e=0,t=n.byteLength){return n.buffer.slice(n.byteOffset+e,n.byteOffset+e+t)}var Be=class{constructor(e){this.type="file";this.filepath=e;let t=this.name=q.basename(e);this.fullpath=t;let i=q.extname(t);this.extension=i.substring(1).toLowerCase(),this.basename=q.basename(t,i)}async readText(){return $e.readFile(this.filepath,"utf8")}async read(){let e=await $e.readFile(this.filepath);return Ji(e)}async readZip(e){let t=null;try{t=await $e.open(this.filepath,"r");let i=await t.stat();return await e(new Qt(new Fo(t,i.size)))}finally{await(t==null?void 0:t.close())}}createReadStream(){return K.createReadStream(this.filepath)}toString(){return this.filepath}},en=class n{constructor(e){this.type="folder";this.filepath=e,this.name=q.basename(e)}async list(){let{filepath:e}=this,t=await $e.readdir(e,{withFileTypes:!0}),i=[];for(let r of t)r.isFile()?i.push(new Be(q.join(e,r.name))):r.isDirectory()&&i.push(new n(q.join(e,r.name)));return i}toString(){return this.filepath}},Xi=class{constructor(e){this.type="file";this.file=e;let t=this.name=e.name;this.fullpath=t;let{basename:i,extension:r}=oe(t);this.basename=i,this.extension=r}readText(){let{file:e}=this;return e.text?e.text():new Promise((t,i)=>{let r=new FileReader;r.addEventListener("load",()=>t(r.result)),r.addEventListener("error",i),r.readAsText(this.file)})}async read(){let{file:e}=this;return e.arrayBuffer?e.arrayBuffer():new Promise((t,i)=>{let r=new FileReader;r.addEventListener("load",()=>t(r.result)),r.addEventListener("error",i),r.readAsArrayBuffer(this.file)})}async readZip(e){return e(new Qt(new Rt(this.file)))}toString(){return this.file.toString()}};async function Lo(n,e){let t=[];for(let i of n)try{i.type==="folder"?t.push(...await Lo(await i.list(),e)):i.type==="file"&&(!e||e(i))&&t.push(i)}catch(r){console.log("Skipping path: ",i.name,r)}return t}function oe(n){let e=Math.max(n.lastIndexOf("/"),n.lastIndexOf("\\")),t=n,i="";e>=0&&(t=n.substring(e+1),i=n.substring(0,e));let[r,o]=Po(t);return{parent:i,name:t,basename:r,extension:o}}function Po(n){let e=n.lastIndexOf("."),t=n,i="";return e>0&&(t=n.substring(0,e),i=n.substring(e+1).toLowerCase()),[t,i]}var Fo=class extends vn{constructor(e,t){super(e),this.fd=e,this.size=t}async readUint8Array(e,t){let i=Buffer.alloc(t),r=await this.fd.read(i,0,t,e);return new Uint8Array(Ji(i,0,r.bytesRead))}};var Yl=require("obsidian"),Sh=/[\/\?<>\\:\*\|"]/g,Rh=/[\x00-\x1f\x80-\x9f]/g,Oh=/^\.+$/,Ch=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,Ih=/[\. ]+$/,Dh=/^\./,Fh=/[\[\]#|^]/g;function ze(n){return n.replace(Sh,"").replace(Rh,"").replace(Oh,"").replace(Ch,"").replace(Ih,"").replace(Dh,"").replace(Fh,"")}function Tn(n){let e=[];for(let t=0;t<n;t++)e.push((Math.random()*16|0).toString(16));return e.join("")}function dt(n){return new DOMParser().parseFromString(n,"text/html").documentElement}function Lh(n){return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}function Mo(n){return Lh(new TextEncoder().encode(n))}function Qi(n){return Object.isEmpty(n)?"":`---
`+(0,Yl.stringifyYaml)(n)+`---
`}function ii(n,e,t="..."){return n.length<e?n:n.substring(0,e)+t}var Ce=require("obsidian");var zl=300,ue=class{constructor(e,t){this.files=[];this.outputLocation="";this.notAvailable=!1;this.outputFolder=null;this.app=e,this.vault=e.vault,this.modal=t,this.init()}registerAuthCallback(e){this.modal.plugin.registerAuthCallback(e)}addFileChooserSetting(e,t,i=!1){let r=new Ce.Setting(this.modal.contentEl).setName("Files to import").setDesc("Pick the files that you want to import.").addButton(a=>a.setButtonText(i?"Choose files":"Choose file").onClick(async()=>{if(Ce.Platform.isDesktopApp){let s=["openFile","dontAddToRecent"];i&&s.push("multiSelections");let l=window.electron.remote.dialog.showOpenDialogSync({title:"Pick files to import",properties:s,filters:[{name:e,extensions:t}]});l&&l.length>0&&(this.files=l.map(c=>new Be(c)),o())}else{let s=createEl("input");s.type="file",s.accept=t.map(l=>"."+l.toLowerCase()).join(","),s.addEventListener("change",()=>{if(!s.files)return;let l=Array.from(s.files);l.length>0&&(this.files=l.map(c=>new Xi(c)).filter(c=>t.contains(c.extension)),o())}),s.click()}}));i&&Ce.Platform.isDesktopApp&&r.addButton(a=>a.setButtonText("Choose folders").onClick(async()=>{if(Ce.Platform.isDesktopApp){let s=window.electron.remote.dialog.showOpenDialogSync({title:"Pick folders to import",properties:["openDirectory","multiSelections","dontAddToRecent"]});if(s&&s.length>0){r.setDesc("Reading folders...");let l=s.map(c=>new en(c));this.files=await Lo(l,c=>t.contains(c.extension)),o()}}}));let o=()=>{let a=document.createDocumentFragment(),s=this.files.length,l=this.files.map(c=>c.name).join(", ");l.length>zl&&(l=l.substring(0,zl)+"..."),a.createEl("span",{text:`These ${s} files will be imported: `}),a.createEl("br"),a.createEl("span",{cls:"u-pop",text:l}),r.setDesc(a)}}addOutputLocationSetting(e){this.outputLocation=e,new Ce.Setting(this.modal.contentEl).setName("Output folder").setDesc("Choose a folder in the vault to put the imported files. Leave empty to output to vault root.").addText(t=>t.setValue(e).onChange(i=>{this.outputLocation=i,this.outputFolder=null}))}async getOutputFolder(){if(this.outputFolder)return this.outputFolder;let{vault:e}=this.app,t=this.outputLocation;t===""&&(t="/");let i=e.getAbstractFileByPath(t);return(i===null||!(i instanceof Ce.TFolder))&&(await e.createFolder(t),i=e.getAbstractFileByPath(t)),i instanceof Ce.TFolder?(this.outputFolder=i,i):null}async getAvailablePathForAttachment(e,t){let i=await this.getOutputFolder(),r=i?{parent:i}:null,{basename:o,extension:a}=oe(e),s=await this.vault.getAvailablePathForAttachments(o,a,r),l=oe(s),c=l.extension?"."+l.extension:"."+a,p=1,m=s;for(;t.includes(m)||this.vault.getAbstractFileByPath(m);)m=q.join(l.parent,`${l.name} ${p}${c}`),p++;return m}async pause(e,t,i){let r=new Promise(o=>setTimeout(o,e*1e3));if(i){let o=i.statusMessage;i.status(`\u23F8\uFE0F Pausing import for ${e} seconds (${t})`),await r,i.status(o)}else await r}sanitizeFilePath(e){return e.replace(/[:|?<>*\\]/g,"")}async createFolders(e){let t=e.split("/").map(o=>o.replace(/^\.+/,"")).join("/"),i=(0,Ce.normalizePath)(t),r=this.vault.getAbstractFileByPathInsensitive(i);if(r&&r instanceof Ce.TFolder)return r;if(await this.vault.createFolder(i),r=this.vault.getAbstractFileByPathInsensitive(i),!(r instanceof Ce.TFolder))throw new Error(`Failed to create folder at "${e}"`);return r}async saveAsMarkdownFile(e,t,i){let r=ze(t);return await this.app.fileManager.createNewMarkdownFile(e,r,i)}};var tu=eo(Yp());var Da=require("obsidian");var zp=n=>{let t=Tr.execSync(`${n} --version`).toString().toString().match(/(\d+)\.(\d+).(\d+)/);return(t==null?void 0:t[1])>3||(t==null?void 0:t[2])>32},Zp=n=>{let e=[];if(!n)return e;let t=[],i=0,r=-1,o={};for(;i<n.length;){let a="";if(n[i]==="'")for(i++;i<n.length;)if(n[i]!=="'"){let s=n.indexOf("'",i);a+=n.substring(i,s),i=s}else if(n[i+1]==="'")a+=n[i],i+=2;else{i++;break}else if(n[i]==="N")a=null,i+=4;else{let s=Math.min(...[n.indexOf(",",i),n.indexOf(`
`,i)].filter(l=>l>0),n.length-1);a=parseFloat(n.substring(i,s)),i=s}r==-1?t.push(a):(o[t[r]]=a,r++),(n[i]==`
`||t.length<r)&&(r!==-1&&e.push(o),r=0,o={}),i++}return e};function Gp(n){for(var e=n[0],t=1,i=arguments.length;t<i;t++)e+=arguments[t]+n[t];return e}var{isArray:Zg}=Array,_r=class extends String{},Vp=(n,...e)=>{let t=[n[0]],i=[t];for(let r=0;r<e.length;r++)e[r]instanceof _r?t[t.length-1]+=e[r]+n[r+1]:(Zg(e[r])?(t.push(...e[r].slice(1).map(o=>",")),i.push(...e[r].length?e[r]:[""])):i.push(e[r]),t.push(n[r+1]));return i},Kp=n=>new _r(n);var hi=(n,e)=>{let t="SQLITE_ERROR",i=new Error(t+": "+e);return i.code=t,n(i),""},Xp=(...n)=>Kp(Gp(...n)),{from:Gg}=Array,Vg=/'/g,Kg=n=>n.toString(16).padStart(2,"0"),Xg=n=>`x'${Gg(n,Kg).join("")}'`,Jg=n=>{switch(typeof n){case"string":return"'"+n.replace(Vg,"''")+"'";case"number":if(!isFinite(n))return;case"boolean":return+n;case"object":case"undefined":switch(!0){case!n:return"NULL";case n instanceof Date:return"'"+n.toISOString()+"'";case n instanceof Buffer:case n instanceof ArrayBuffer:n=new Uint8Array(n);case n instanceof Uint8Array:case n instanceof Uint8ClampedArray:return Xg(n)}}},Oa=(n,e)=>{let[t,...i]=Vp(...e),r=[t[0]];for(let a=0;a<i.length;a++){let s=Jg(i[a]);if(s===void 0)return hi(n,"incompatible "+typeof s+"value");r.push(s,t[a+1])}let o=r.join("").trim();return o.length?o:hi(n,"empty query")};var Ca=Da.Platform.isDesktopApp?window.require("node:crypto"):null,Tr=Da.Platform.isDesktopApp?window.require("node:child_process"):null,Fa=Ca==null?void 0:Ca.randomUUID(),Qg=`[{"_":"${Fa}"}]
`,e0=`'_'
'${Fa}'
`,{isArray:t0}=Array,{parse:Qp}=JSON,{defineProperty:n0}=Object,i0=()=>{},r0=(n,e,t,i,r,o)=>{let a=[],{stdout:s,stderr:l}=Tr.spawn(i,r,o).on("close",p=>{if(c||p!==0){p!==0&&hi(e,"busy DB or query too slow");return}let m=a.join("").trim();if(t==="query")n(m);else{let h=Qp(m||"[]");n(t==="get"&&t0(h)?h.shift():h)}});s.on("data",p=>{a.push(p)});let c=!1;l.on("data",p=>{c=!0,hi(e,"".trim.call(p))})},o0=(n,e,t)=>{let i=zp(n),r=i?Qg:e0,{stdin:o,stdout:a,stderr:s}=Tr.spawn(n,e);i?o.write(`.mode json
`):o.write(`.mode quote
.headers on
`),t&&o.write(`.timeout ${t}
`);let l=Promise.resolve();return(c,p,m,h,w)=>{m==="close"?(o.write(`.quit
`),l=null):l&&(l=l.then(()=>new Promise(v=>{let d="",f=T=>{d+=T;let A=!1;for(;d.endsWith(r);)A=!0,d=d.slice(0,-r.length);if(A){for(E();d.startsWith(r);)d=d.slice(r.length);if(m==="query")c(d);else{let O=i?Qp(d||"[]"):Zp(d);c(m==="get"?O.shift():O)}}},g=T=>{E(),p(new Error(T))},E=()=>{v(),a.removeListener("data",f),s.removeListener("data",g)};a.on("data",f),s.once("data",g),o.write(`${w[w.length-1]};
`),o.write(`SELECT '${Fa}' as _;
`)})))}},Ia=(n,e,t,i,r)=>(...o)=>new Promise((a,s)=>{let l=Oa(s,o);l.length&&(n==="get"&&/^SELECT\s+/i.test(l)&&!/\s+LIMIT\s+\d+$/i.test(l)&&(l+=" LIMIT 1"),t(a,s,n,e,i.concat(l),r))}),Jp="";function La(n,e={}){n===":memory:"&&(n=Jp||(Jp=q.join(nn.tmpdir(),randomUUID())));let t=e.timeout||0,i=e.bin||"sqlite3",r=[n,"-bail"],o={timeout:t};e.readonly&&r.push("-readonly"),t&&r.push("-cmd",".timeout "+t);let a=r.concat("-json"),s=e.exec||(e.persistent?o0(i,r,t):r0);return{transaction(){let l=[];return n0((...c)=>{l.push(c)},"commit",{value(){return new Promise((c,p)=>{let m=["BEGIN TRANSACTION"];for(let h of l){let w=Oa(p,h);if(!w.length)return;m.push(w)}m.push("COMMIT"),s(c,p,"query",i,r.concat(m.join(";")),o)})}})},query:Ia("query",i,s,r,o),get:Ia("get",i,s,a,o),all:Ia("all",i,s,a,o),close:e.persistent?()=>s(null,null,"close"):i0,raw:Xp}}var Pa="Library/Group Containers/group.com.apple.notes",eu="NoteStore.sqlite",a0=978307200,Ar=class extends ue{constructor(){super(...arguments);this.owners={};this.resolvedAccounts={};this.resolvedFiles={};this.resolvedFolders={};this.multiAccount=!1;this.noteCount=0;this.parsedNotes=0;this.omitFirstLine=!0;this.importTrashed=!1;this.includeHandwriting=!1;this.trashFolders=[]}init(){if(!lt.Platform.isMacOS||!lt.Platform.isDesktop){this.modal.contentEl.createEl("p",{text:"Due to platform limitations, Apple Notes cannot be exported from this device. Open your vault on a Mac to export from Apple Notes."}),this.notAvailable=!0;return}this.addOutputLocationSetting("Apple Notes"),new lt.Setting(this.modal.contentEl).setName("Import recently deleted notes").setDesc('Import notes in the "Recently Deleted" folder. Unlike in Apple Notes, they will not be automatically removed after a set amount of time.').addToggle(t=>t.setValue(!1).onChange(async i=>this.importTrashed=i)),new lt.Setting(this.modal.contentEl).setName("Omit first line").setDesc("Don't include the first line in the text, since Apple Notes uses it as the title. It will still be used as the note name.").addToggle(t=>t.setValue(!0).onChange(async i=>this.omitFirstLine=i)),new lt.Setting(this.modal.contentEl).setName("Include handwriting text").setDesc("When Apple Notes has detected handwriting in drawings, include it as text before the drawing.").addToggle(t=>t.setValue(!1).onChange(async i=>this.includeHandwriting=i))}async getNotesDatabase(){let t=q.join(nn.homedir(),Pa),i=window.electron.remote.dialog.showOpenDialogSync({defaultPath:t,properties:["openDirectory"],message:'Select the "group.com.apple.notes" folder to allow Obsidian to read Apple Notes data.'});if(!(i!=null&&i.includes(t)))return new lt.Notice("Data import failed. Ensure you have selected the correct Apple Notes data folder."),null;let r=q.join(t,eu),o=q.join(nn.tmpdir(),eu);return await $e.copyFile(r,o),await $e.copyFile(r+"-shm",o+"-shm"),await $e.copyFile(r+"-wal",o+"-wal"),new La(o,{readonly:!0,persistent:!0})}async import(t){if(this.ctx=t,this.protobufRoot=tu.Root.fromJSON(ys),this.rootFolder=await this.getOutputFolder(),!this.rootFolder){new lt.Notice("Please select a location to export to.");return}if(this.database=await this.getNotesDatabase(),!this.database)return;this.keys=Object.fromEntries((await this.database.all`SELECT z_ent, z_name FROM z_primarykey`).map(a=>[a.Z_NAME,a.Z_ENT]));let i=await this.database.all`
SELECT z_pk FROM ziccloudsyncingobject WHERE z_ent = ${this.keys.ICAccount}
`,r=await this.database.all`
SELECT z_pk, ztitle2 FROM ziccloudsyncingobject WHERE z_ent = ${this.keys.ICFolder}
`;for(let a of i)await this.resolveAccount(a.Z_PK);for(let a of r)try{await this.resolveFolder(a.Z_PK)}catch(s){this.ctx.reportFailed(a.ZTITLE2,s==null?void 0:s.message),console.error(s)}let o=await this.database.all`
SELECT
z_pk, zfolder, ztitle1 FROM ziccloudsyncingobject
WHERE
z_ent = ${this.keys.ICNote}
AND ztitle1 IS NOT NULL
AND zfolder NOT IN (${this.trashFolders})
`;this.noteCount=o.length;for(let a of o)try{await this.resolveNote(a.Z_PK)}catch(s){this.ctx.reportFailed(a.ZTITLE1,s==null?void 0:s.message),console.error(s)}this.database.close()}async resolveAccount(t){!this.multiAccount&&Object.keys(this.resolvedAccounts).length&&(this.multiAccount=!0);let i=await this.database.get`
SELECT zname, zidentifier FROM ziccloudsyncingobject
WHERE z_ent = ${this.keys.ICAccount} AND z_pk = ${t}
`;this.resolvedAccounts[t]={name:i.ZNAME,uuid:i.ZIDENTIFIER,path:q.join(nn.homedir(),Pa,"Accounts",i.ZIDENTIFIER)}}async resolveFolder(t){var a;if(t in this.resolvedFiles)return this.resolvedFolders[t];let i=await this.database.get`
SELECT ztitle2, zparent, zidentifier, zfoldertype, zowner
FROM ziccloudsyncingobject
WHERE z_ent = ${this.keys.ICFolder} AND z_pk = ${t}
`,r;if(i.ZFOLDERTYPE==3)return null;if(!this.importTrashed&&i.ZFOLDERTYPE==1)return this.trashFolders.push(t),null;if(i.ZPARENT!==null)r=((a=await this.resolveFolder(i.ZPARENT))==null?void 0:a.path)+"/";else if(this.multiAccount){let s=this.resolvedAccounts[i.ZOWNER].name;r=`${this.rootFolder.path}/${s}/`}else r=`${this.rootFolder.path}/`;i.ZIDENTIFIER.startsWith("DefaultFolder")||(r+=ze(i.ZTITLE2));let o=await this.createFolders(r);return this.resolvedFolders[t]=o,this.owners[t]=i.ZOWNER,o}async resolveNote(t){if(t in this.resolvedFiles)return this.resolvedFiles[t];let i=await this.database.get`
SELECT
nd.z_pk, hex(nd.zdata) as zhexdata, zcso.ztitle1, zfolder,
zcreationdate1, zcreationdate2, zcreationdate3, zmodificationdate1, zispasswordprotected
FROM
zicnotedata AS nd,
(SELECT
*, NULL AS zcreationdate3, NULL AS zcreationdate2,
NULL AS zispasswordprotected FROM ziccloudsyncingobject
) AS zcso
WHERE
zcso.z_pk = nd.znote
AND zcso.z_pk = ${t}
`;if(i.ZISPASSWORDPROTECTED)return this.ctx.reportSkipped(i.ZTITLE1,"note is password protected"),null;let r=this.resolvedFolders[i.ZFOLDER]||this.rootFolder,o=`${i.ZTITLE1}.md`,a=await this.saveAsMarkdownFile(r,o,"");this.ctx.status(`Importing note ${o}`),this.resolvedFiles[t]=a,this.owners[t]=this.owners[i.ZFOLDER];let s=this.decodeData(i.zhexdata,Zt);return this.vault.modify(a,await s.format(!1,a.path),{ctime:this.decodeTime(i.ZCREATIONDATE3||i.ZCREATIONDATE2||i.ZCREATIONDATE1),mtime:this.decodeTime(i.ZMODIFICATIONDATE1)}),this.parsedNotes++,this.ctx.reportProgress(this.parsedNotes,this.noteCount),a}async resolveAttachment(t,i){if(t in this.resolvedFiles)return this.resolvedFiles[t];let r,o,a,s,l;switch(i){case"com.apple.paper.doc.scan":s=await this.database.get`
SELECT
zidentifier, zfallbackpdfgeneration, zcreationdate, zmodificationdate, znote
FROM
(SELECT *, NULL AS zfallbackpdfgeneration FROM ziccloudsyncingobject)
WHERE
z_ent = ${this.keys.ICAttachment}
AND z_pk = ${t}
`,r=q.join("FallbackPDFs",s.ZIDENTIFIER,s.ZFALLBACKPDFGENERATION||"","FallbackPDF.pdf"),o="Scan",a="pdf";break;case"com.apple.notes.gallery":s=await this.database.get`
SELECT
zidentifier, zsizeheight, zsizewidth, zcreationdate, zmodificationdate, znote
FROM ziccloudsyncingobject
WHERE
z_ent = ${this.keys.ICAttachment}
AND z_pk = ${t}
`,r=q.join("Previews",`${s.ZIDENTIFIER}-1-${s.ZSIZEWIDTH}x${s.ZSIZEHEIGHT}-0.jpeg`),o="Scan Page",a="jpg";break;case"com.apple.paper":s=await this.database.get`
SELECT
zidentifier, zfallbackimagegeneration, zcreationdate, zmodificationdate,
znote, zhandwritingsummary
FROM
(SELECT *, NULL AS zfallbackimagegeneration FROM ziccloudsyncingobject)
WHERE
z_ent = ${this.keys.ICAttachment}
AND z_pk = ${t}
`,s.ZFALLBACKIMAGEGENERATION?r=q.join("FallbackImages",s.ZIDENTIFIER,s.ZFALLBACKIMAGEGENERATION,"FallbackImage.png"):r=q.join("FallbackImages",`${s.ZIDENTIFIER}.jpg`),o="Drawing",a="png";break;default:s=await this.database.get`
SELECT
a.zidentifier, a.zfilename,
a.zgeneration1, b.zcreationdate, b.zmodificationdate, b.znote
FROM
(SELECT *, NULL AS zgeneration1 FROM ziccloudsyncingobject) AS a,
ziccloudsyncingobject AS b
WHERE
a.z_ent = ${this.keys.ICMedia}
AND a.z_pk = ${t}
AND a.z_pk = b.zmedia
`,r=q.join("Media",s.ZIDENTIFIER,s.ZGENERATION1||"",s.ZFILENAME),[o,a]=Po(s.ZFILENAME);break}try{let c=await this.getAttachmentSource(this.resolvedAccounts[this.owners[s.ZNOTE]],r),p=await this.getAvailablePathForAttachment(`${o}.${a}`,[]);l=await this.vault.createBinary(p,c,{ctime:this.decodeTime(s.ZCREATIONDATE),mtime:this.decodeTime(s.ZMODIFICATIONDATE)})}catch(c){return this.ctx.reportFailed(r),console.error(c),null}return this.resolvedFiles[t]=l,this.ctx.reportAttachmentSuccess(this.resolvedFiles[t].path),l}decodeData(t,i){let r=Wl.gunzipSync(Buffer.from(t,"hex")),o=this.protobufRoot.lookupType(i.protobufType).decode(r);return new i(this,o)}decodeTime(t){return!t||t<1?new Date().getTime():Math.floor((t+a0)*1e3)}async getAttachmentSource(t,i){try{return await $e.readFile(q.join(t.path,i))}catch(r){return await $e.readFile(q.join(nn.homedir(),Pa,i))}}};var On=require("obsidian");var gi=class{constructor(e,t){this.type="file";this.entry=t,this.fullpath=e.fullpath+"/"+t.filename;let{parent:i,name:r,basename:o,extension:a}=oe(t.filename);this.parent=i,this.name=r,this.basename=o,this.extension=a}async readText(){return this.entry.getData(new Yi)}async read(){return(await this.entry.getData(new Jn)).arrayBuffer()}get filepath(){return this.entry.filename}get size(){return this.entry.uncompressedSize}get ctime(){return this.entry.creationDate}get mtime(){return this.entry.lastModDate}async readZip(e){return e(new Qt(new Rt(new Blob([await this.read()]))))}};async function yt(n,e){await n.readZip(async t=>{let r=(await t.getEntries()).filter(o=>!o.directory&&!!o.getData).map(o=>new gi(n,o));return e(t,r)})}var kr=class extends ue{constructor(){super(...arguments);this.attachmentMap={}}init(){this.addFileChooserSetting("Bear2bk",["bear2bk"]),this.addOutputLocationSetting("Bear")}async import(t){let{files:i}=this;if(i.length===0){new On.Notice("Please pick at least one file to import.");return}let r=await this.getOutputFolder();if(!r){new On.Notice("Please select a location to export to.");return}let o=r,a=new RegExp("\\[[^\\]]*\\]\\((assets/[^\\)]+)\\)","gm"),s=await this.createFolders(`${r.path}/archive`),l=await this.createFolders(`${r.path}/trash`);for(let c of i){if(t.isCancelled())return;t.status("Processing "+c.name),await yt(c,async(p,m)=>{let h=await this.collectMetadata(t,m);for(let w of m){if(t.isCancelled())return;let{fullpath:v,filepath:d,parent:f,name:g,extension:E}=w;if(!(g==="info.json"||g==="tags.json")){t.status("Processing "+g);try{if(E==="md"||E==="markdown"){let T=oe(f).basename;t.status("Importing note "+T);let A=await w.readText();A=this.removeMarkdownHeader(T,A);let O=[...A.matchAll(a)];if(O.length>0)for(let C of O){let[N,P]=C,L=q.join(f,decodeURI(P)),j=await this.getAttachmentStoragePath(L);j=encodeURI(j);let Y=N.replace(P,j);A=A.replace(N,Y)}let _=(0,On.normalizePath)(T),k=h[f],x=o;k!=null&&k.archived?x=s:k!=null&&k.trashed&&(x=l);let I=await this.saveAsMarkdownFile(x,_,A);k!=null&&k.ctime&&(k!=null&&k.mtime)&&await this.modifFileTimestamps(k,I),t.reportNoteSuccess(T)}else if(d.match(/\/assets\//g)){t.status("Importing asset "+w.name);let T=await this.getAttachmentStoragePath(w.filepath),A=await w.read();await this.vault.createBinary(T,A),t.reportAttachmentSuccess(w.fullpath)}else t.reportSkipped(v,"unknown type of file")}catch(T){t.reportFailed(v,T)}}}})}}async modifFileTimestamps(t,i){let r={ctime:t.ctime,mtime:t.mtime};await this.vault.append(i,"",r)}async collectMetadata(t,i){let r={};for(let o of i){if(t.isCancelled())return r;if(o.name!=="info.json")continue;let a=await o.readText(),l=JSON.parse(a)["net.shinyfrog.bear"],c=Date.parse(l.creationDate),p=Date.parse(l.modificationDate);r[o.parent]={ctime:isNaN(c)?void 0:c,mtime:isNaN(p)?void 0:p,archived:l.archived===1,trashed:l.trashed===1}}return r}async getAttachmentStoragePath(t){let i=(0,On.normalizePath)(t);if(this.attachmentMap[i])return this.attachmentMap[i];let r=Object.values(this.attachmentMap),o=await this.getAvailablePathForAttachment(i,r);return o=o.replace(/:/g,""),this.attachmentMap[i]=o,o}removeMarkdownHeader(t,i){if(!i.startsW
`),o=r>0?i.substring(2,r):i.substring(2);return o=o.trim(),o!==t.trim()&&o!==""?i:r>0?i.substring(r+1):""}};var Ti=require("obsidian");var ad=require("obsidian");var nu=require("obsidian");var iu=n=>({...n,created:yi(n.created),statusupdated:yi(n.statusupdated),updated:yi(n.updated),duedate:yi(n.duedate),taskflag:n.taskflag==="true",reminderdate:n.reminder?yi(n.reminder.reminderdate):void 0,sortweight:n.sortweight}),yi=n=>n?(0,nu.moment)(n,"YYYYMMDDThhmmssZ").toDate():void 0;var Bu=eo(bu());var de=n=>{let e={get(t,i){return t[i]}};return new Proxy(n.attributes,e)};var xu="\n```\n",Ua=n=>{let e=de(n);return e.style&&e.style.value.indexOf("-en-codeblock:true")>=0},y0=n=>{let e=de(n),t="padding-left:",i=0;return e.style&&e.style.value.indexOf(t)>=0&&(i=Math.floor(e.style.value.split(t)[1].split("px")[0]/20)),i},ja=n=>n.replace(/\\(.)/g,"$1"),wu=(n,e)=>{let t=y0(e);return n=`${" ".repeat(t)}${n}`,Ua(e)?(n=ja(n),`${xu}${n}${xu}`):e.parentElement&&Ua(e.parentElement)&&e.parentElement.firstElementChild===e?`${n}`:e.parentElement&&Ua(e.parentElement)?`
${n}`:e.isBlock?`
${n}
`:n};var Nr="\n```\n",b0="-en-codeblock:true",x0=/\b(Courier|Mono|Consolas|Console|Inconsolata|Pitch|Monaco|monospace)\b/,vu=n=>{var o,a;if(n.nodeType!==1)return null;let e=n.childNodes,t=e.length;if(t>1)return"mixed";if(t===1){let s=vu(e[0]);if(s)return s}let i=de(n);if(n.tagName==="FONT")return(o=i.face)==null?void 0:o.value;let r=(a=i.style)==null?void 0:a.value;if(r){let s=r.match(/font-family:([^;]+)/);if(s)return s[1]}return null},bi=n=>{var r;let t=(r=de(n).style)==null?void 0:r.value;if(t&&t.includes(b0))return!0;let i=vu(n);return!!i&&x0.test(i)},Eu=(n,e)=>{if(bi(e)){let t=e.previousSibling,i=t&&t.tagName===e.tagName&&bi(t),r=e.nextSibling,o=r&&r.tagName===e.tagName&&bi(r);return i||o?(n=i?`
${n}`:`${Nr}${n}`,n=o?`${n}
`:`${n}${Nr}`,n):(n=ja(n),n.trim()?`${Nr}${n}${Nr}`:n)}return e.parentElement&&bi(e.parentElement)&&e.parentElement.firstElementChild===e?n:e.parentElement&&bi(e.parentElement)?`
${n}`:e.isBlock?`
${n}
`:n};var Ye=n=>e=>e.nodeName===n||e.nodeName.toLowerCase()===n;var Tu={filter:Ye("IMG"),replacement:(n,e)=>{let t=de(e);if(!t.src)return"";let i=t.src.value,r=e.width||"",o=e.height||"",a=i;B.sanitizeResourceNameSpaces?a=a.replace(/ /g,B.replacementChar):B.urlEncodeFileNamesAndLinks&&(a=encodeURI(a));let s=r||o?` =${r}x${o}`:"";if(B.keepImageSize)return s=r||o?`|${r||0}x${o||0}`:"",a.startsWith("./")?`![[${a}${s}]]`:`![${s}](${a})`;if(!i.match(/^[a-z]+:/))return`![[${a}]]`;let l=t.src.value.split("/");return`![${l[l.length-1]}](${a})`}};var ke=class n{constructor(){this.noteIdNameMap={},this.noteIdNameTOCMap={}}static getInstance(){return n.instance||(n.instance=new n),n.instance}addItemToMap(e){this.noteIdNameMap[e.url]={...this.noteIdNameMap[e.url],title:e.title,noteName:this.currentNoteName,notebookName:this.currentNotebookName,uniqueEnd:e.uniqueEnd}}addItemToTOCMap(e){this.noteIdNameTOCMap[e.url]={...this.noteIdNameMap[e.url],title:e.title,noteName:this.currentNoteName,notebookName:this.currentNotebookName,uniqueEnd:e.uniqueEnd}}getNoteIdNameMap(){return this.noteIdNameMap}getNoteIdNameTOCMap(){return this.noteIdNameTOCMap}getAllNoteIdNameMap(){return{...this.noteIdNameMap,...this.noteIdNameTOCMap}}getNoteIdNameMapByNoteTitle(e){return Object.values(this.getAllNoteIdNameMap()).filter(t=>t.title===e)}setCurrentNotebookName(e){this.currentNotebookName=e}getCurrentNotebookName(){return this.currentNotebookName}setCurrentNotebookFullpath(e){this.currentNotebookFullpath=e}setCurrentNoteName(e){this.currentNoteName=e}getCurrentNoteName(){return this.currentNoteName}getCurrentNotePath(){return this.currentNotePath}setCurrentNotePath(e){this.currentNotePath=e}getCurrentNotebookFullpath(){return this.currentNotebookFullpath}};var _u=require("obsidian");var Cn=n=>n.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&");var w0={"application/andrew-inset":"ez","application/applixware":"aw","application/atom+xml":"atom","application/atomcat+xml":"atomcat","application/atomdeleted+xml":"atomdeleted","application/atomsvc+xml":"atomsvc","application/atsc-dwd+xml":"dwd","application/atsc-held+xml":"held","application/atsc-rsat+xml":"rsat","application/bdoc":"bdoc","application/calendar+xml":"xcs","application/ccxml+xml":"ccxml","application/cdfx+xml":"cdfx","application/cdmi-capability":"cdmia","application/cdmi-container":"cdmic","application/cdmi-domain":"cdmid","application/cdmi-object":"cdmio","application/cdmi-queue":"cdmiq","application/cpl+xml":"cpl","application/cu-seeme":"cu","application/dash+xml":"mpd","application/dash-patch+xml":"mpp","application/davmount+xml":"davmount","application/docbook+xml":"dbk","application/dssc+der":"dssc","application/dssc+xml":"xdssc","application/ecmascript":"es","application/emma+xml":"emma","application/emotionml+xml":"emotionml","application/epub+zip":"epub","application/exi":"exi","application/express":"exp","application/fdt+xml":"fdt","application/font-tdpfr":"pfr","application/geo+json":"geojson","application/gml+xml":"gml","application/gpx+xml":"gpx","application/gxf":"gxf","application/gzip":"gz","application/hjson":"hjson","application/hyperstudio":"stk","application/inkml+xml":"ink","application/ipfix":"ipfix","application/its+xml":"its","application/java-archive":"jar","application/java-serialized-object":"ser","application/java-vm":"class","application/javascript":"js","application/json":"json","application/json5":"json5","application/jsonml+json":"jsonml","application/ld+json":"jsonld","application/lgr+xml":"lgr","application/lost+xml":"lostxml","application/mac-binhex40":"hqx","application/mac-compactpro":"cpt","application/mads+xml":"mads","application/manifest+json":"webmanifest","application/marc":"mrc","application/marcxml+xml":"mrcx","application/mathematica":"ma","application/mathml+xml":"mathml","application/mbox":"mbox","application/media-policy-dataset+xml":"mpf","application/mediaservercontrol+xml":"mscml","application/metalink+xml":"metalink","application/metalink4+xml":"meta4","application/mets+xml":"mets","application/mmt-aei+xml":"maei","application/mmt-usd+xml":"musd","appl
`).replace(/\n/gm,`
${Mu}`),l=o>0?a:i(e)?`${Cr} `:r(e)?`${Or} `:"* ",c=e.parentNode;if(c.nodeName==="OL"){let m=c.getAttribute("start"),h=Array.prototype.indexOf.call(c.children,e);l=`${m?Number(m)+h:h+1}. `}let p;return p=l+s+(e.nextSibling&&!/\n$/.test(s)?`
`:""),p}};var Rr=n=>{let e=new window.TurndownService({br:"",...n.turndownOptions,blankReplacement:(t,i)=>i.isBlock?`
`:"",keepReplacement:(t,i)=>i.isBlock?`
${i.outerHTML}
`:i.outerHTML,defaultReplacement:(t,i)=>i.isBlock?`
${t}
`:t});return e.use(Bu.gfm),e.addRule("span",Cu),e.addRule("strikethrough",Iu),e.addRule("evernote task items",Du),e.addRule("wikistyle links",Ru),e.addRule("images",Tu),e.addRule("list",$u),e.addRule("italic",Pu),n.keepMDCharactersOfENNotes&&(e.escape=t=>t),e.addRule("divBlock",Lu),n.keepOriginalAmountOfNewlines&&e.addRule("newline",Fu),e};var Uu=n=>{n.replaceWith(...Array.from(n.children))},ju=n=>{let e=n.parentElement;e.replaceWith(...Array.from(e.childNodes)),e.append(...Array.from(n.childNodes)),n.appendChild(e)},M0=n=>(Array.from(n.querySelectorAll("span>en-todo")).forEach(ju),Array.from(n.querySelectorAll("a>en-todo")).forEach(ju),n),$0=n=>{let e=n.replace(/<li>/g,"<li><div>");return e=e.replace(/<\/li>/g,"</div></li>"),e=e.replace(/<li><div>(\s)*<div>/g,"<li><div>"),e=e.replace(/<\/div>(\s)*<\/div><\/li>/g,"</div></li>"),e},B0=n=>{var o;let e=Array.from(n.getElementsByTagName("ul")),t=Array.from(n.getElementsByTagName("ol")),i=e.concat(t);i.forEach(a=>{a.parentElement.tagName==="LI"&&a.parentElement.replaceWith(a),a.previousElementSibling&&a.previousElementSibling.tagName==="LI"&&a.previousElementSibling.appendChild(a)});for(let a of i){let s=a.parentElement;(s==null?void 0:s.tagName)==="DIV"&&((o=s==null?void 0:s.parentElement)==null?void 0:o.tagName)==="UL"&&Uu(s),((s==null?void 0:s.tagName)==="UL"||(s==null?void 0:s.tagName)==="OL")&&(s==null?void 0:s.childNodes.length)===1&&Uu(s)}let r=Array.from(n.getElementsByTagName("li"));for(let a of r){let s=a.firstElementChild;if(s&&s.tagName==="DIV"){let l=Array.from(s.childNodes);s.replaceWith(...l)}}return n},Hu=(n,{htmlContent:e})=>{let t=e.replace(/<!DOCTYPE en-note [^>]*>/,"<!DOCTYPE html>").replace(/(<a [^>]*)\/>/,"$1></a>").replace(/<div[^\/\<]*\/>/g,""),i=new DOMParser().parseFromString($0(t),"text/html").getElementsByTagName("en-note").item(0),r=Rr(n).turndown(M0(B0(i))),o=new RegExp("<YARLE_NEWLINE_PLACEHOLDER>","g");return r=r.replace(o,""),r&&r!=="undefined"?{content:r}:{content:""}};var Ff=eo(require("crypto"));var bt=require("obsidian");var qu=(n,e)=>({createdAt:U0(n),updatedAt:j0(n),sourceUrl:H0(n),location:q0(n),reminderTime:W0(n),reminderOrder:Y0(n),reminderDoneTime:z0(n),notebookName:e});var U0=n=>!B.skipCreationTime&&n.created?(0,bt.moment)(n.created).format(B.dateFormat):"",j0=n=>!B.skipUpdateTime&&n.updated?(0,bt.moment)(n.updated).format(B.dateFormat):"",H0=n=>!B.skipSourceUrl&&n["note-attributes"]?n["note-attributes"]["source-url"]:"",q0=n=>!B.skipLocation&&n["note-attributes"]&&n["note-attributes"].longitude?`${n["note-attributes"].latitude},${n["note-attributes"].longitude}`:"",W0=n=>!B.skipReminderTime&&n["note-attributes"]&&n["note-attributes"]["reminder-time"]?(0,bt.moment)(n["note-attributes"]["reminder-time"]).format(B.dateFormat):"",Y0=n=>!B.skipReminderOrder&&n["note-attributes"]&&n["note-attributes"]["reminder-order"]?n["note-attributes"]["reminder-order"]:"",z0=n=>!B.skipReminderDoneTime&&n["note-attributes"]&&n["note-attributes"]["reminder-done-time"]?(0,bt.moment)(n["note-attributes"]["reminder-done-time"]).format(B.dateFormat):"",Wu=n=>({tags:Z0(n)}),Z0=n=>{if(!B.skipTags&&n.tag){let e=Array.isArray(n.tag)?n.tag:[n.tag],t=B.nestedTags;return e.map(r=>{let o=r.toString().replace(/^#/,"");t&&(o=o.replace(new RegExp(Cn(t.separatorInEN),"g"),t.replaceSeparatorWith));let a=t&&t.replaceSpaceWith||"-";return o=o.replace(/ /g,a),`${B.useHashTags?"#":""}${o}`}).join(" ")}return""},Wa;try{Wa=window.require("btime")}catch(n){}var Ir=(n,e)=>{let t=(0,bt.moment)(e.created).valueOf();t>0&&Wa&&Wa.btime(n,t);let r=(0,bt.moment)(e.updated).valueOf()/1e3;try{K.utimesSync(n,r,r)}catch(o){}},Yu=n=>n["resource-attributes"]&&n["resource-attributes"].timestamp?(0,bt.moment)(n["resource-attributes"].timestamp):(0,bt.moment)();var zu=(n,e,t)=>{let i=n.lastIndexOf(e);return i<0?n:n.substring(0,i)+t+n.substring(i+e.length)};var Ne={mdPath:"",resourcePath:""},Fr=249,Zu=(n,e)=>qa(n,e).replace(/\s/g,"_"),Gu=(n,e)=>{if(n.length<=11)throw Error("FATAL: note folder directory path exceeds the OS limitation. Please pick a destination closer to the root folder.");ret
|\r|
))*?(?=${i})${i}`;return n.replace(new RegExp(a,"g"),"")};var Bt=(n,e,t,i)=>({template:n,check:e,startBlockPlaceholder:t.START_BLOCK,endBlockPlaceholder:t.END_BLOCK,valuePlaceholder:t.CONTENT_PLACEHOLDER,value:i});var sf=(n,e,t)=>{let i=Bt(e,t,Za,n.content);return $t(i)};var wi={};Oe(wi,{CONTENT_PLACEHOLDER:()=>ey,END_BLOCK:()=>ny,START_BLOCK:()=>ty});var ey="{tags}",ty="{tags-block}",ny="{end-tags-block}";var lf=(n,e,t)=>{let i=Bt(e,t,wi,n.tags);return $t(i)};var Ga={};Oe(Ga,{CONTENT_PLACEHOLDER:()=>iy,END_BLOCK:()=>oy,START_BLOCK:()=>ry});var iy="{title}",ry="{title-block}",oy="{end-title-block}";var cf=(n,e,t)=>{let i=Bt(e,t,Ga,n.title);return $t(i)};var pn={};Oe(pn,{CONTENT_PLACEHOLDER:()=>ay,END_BLOCK:()=>ly,START_BLOCK:()=>sy});var ay="{created-at}",sy="{created-at-block}",ly="{end-created-at-block}";var Te=(n,e,t)=>n.replace(new RegExp(`${e.CONTENT_PLACEHOLDER}`,"g"),t||"").replace(new RegExp(`${e.START_BLOCK}`,"g"),"").replace(new RegExp(`${e.END_BLOCK}`,"g"),"");var pf=(n,e)=>Te(e,pn,n.createdAt);var un={};Oe(un,{CONTENT_PLACEHOLDER:()=>cy,END_BLOCK:()=>uy,START_BLOCK:()=>py});var cy="{updated-at}",py="{updated-at-block}",uy="{end-updated-at-block}";var uf=(n,e)=>Te(e,un,n.updatedAt);var fn={};Oe(fn,{CONTENT_PLACEHOLDER:()=>fy,END_BLOCK:()=>my,START_BLOCK:()=>dy});var fy="{source-url}",dy="{source-url-block}",my="{end-source-url-block}";var ff=(n,e)=>Te(e,fn,n.sourceUrl);var dn={};Oe(dn,{CONTENT_PLACEHOLDER:()=>hy,END_BLOCK:()=>yy,START_BLOCK:()=>gy});var hy="{location}",gy="{location-block}",yy="{end-location-block}";var df=(n,e)=>Te(e,dn,n.location);var mn={};Oe(mn,{CONTENT_PLACEHOLDER:()=>by,END_BLOCK:()=>wy,START_BLOCK:()=>xy});var by="{notebook}",xy="{notebook-block}",wy="{end-notebook-block}";var mf=(n,e)=>Te(e,mn,n.notebookName);var Dn={};Oe(Dn,{CONTENT_PLACEHOLDER:()=>vy,END_BLOCK:()=>Ty,START_BLOCK:()=>Ey});var vy="{reminder-time}",Ey="{reminder-time-block}",Ty="{end-reminder-time-block}";var hf=(n,e)=>Te(e,Dn,n.reminderTime);var Fn={};Oe(Fn,{CONTENT_PLACEHOLDER:()=>_y,END_BLOCK:()=>ky,START_BLOCK:()=>Ay});var _y="{reminder-order}",Ay="{reminder-order-block}",ky="{end-reminder-order-block}";var gf=(n,e)=>Te(e,Fn,n.reminderOrder);var Ln={};Oe(Ln,{CONTENT_PLACEHOLDER:()=>Ny,END_BLOCK:()=>Ry,START_BLOCK:()=>Sy});var Ny="{reminder-done-time}",Sy="{reminder-done-time-block}",Ry="{end-reminder-done-time-block}";var yf=(n,e)=>Te(e,Ln,n.reminderDoneTime);var vi={};Oe(vi,{CONTENT_PLACEHOLDER:()=>Oy,END_BLOCK:()=>Iy,START_BLOCK:()=>Cy});var Oy="{tags-yaml-list}",Cy="{tags-yaml-list-block}",Iy="{end-tags-yaml-list-block}";var bf=(n,e,t)=>{let i;n.tags&&(i=`
`+n.tags.split(" ").map(o=>` - ${o.replace(/^#/,"")}`).join(`
`));let r=Bt(e,t,vi,i);return $t(r)};var Va="{metadata-block}",Ka="{end-metadata-block}";var xf=`\r?
?`;var me=(n,e)=>n.replace(new RegExp(`${e.START_BLOCK}(?<=${e.START_BLOCK})(.*)(?=${e.END_BLOCK})${e.END_BLOCK}${xf}`,"g"),"");var wf=n=>me(n,pn);var vf=n=>me(n,un);var Ef=n=>me(n,fn);var Tf=n=>me(n,mn);var _f=n=>me(n,dn);var Lr={};Oe(Lr,{CONTENT_PLACEHOLDER:()=>Fy,END_BLOCK:()=>Py,START_BLOCK:()=>Ly});var Fy="{link-to-original}",Ly="{link-to-original-block}",Py="{end-link-to-original-block}";var Af=n=>me(n,Lr);var kf=n=>me(n,Dn);var Nf=n=>me(n,Ln);var Sf=n=>me(n,Fn);var Rf=(n,e)=>{let t=e.currentTemplate;return t=cf(n,t,()=>n.title),t=lf(n,t,()=>!e.skipTags),t=bf(n,t,()=>!e.skipTags),t=sf(n,t,()=>n.content),t=Af(t),t=!e.skipCreationTime&&n.createdAt?pf(n,t):wf(t),t=!e.skipUpdateTime&&n.updatedAt?uf(n,t):vf(t),t=!e.skipSourceUrl&&n.sourceUrl?ff(n,t):Ef(t),t=!e.skipLocation&&n.location?df(n,t):_f(t),t=e.isNotebookNameNeeded&&n.notebookName?mf(n,t):Tf(t),t=!e.skipReminderTime&&n.reminderTime?hf(n,t):kf(t),t=!e.skipReminderOrder&&n.reminderOrder?gf(n,t):Sf(t),t=!e.skipReminderDoneTime&&n.reminderDoneTime?yf(n,t):Nf(t),t=t.replace(Va,"").replace(Ka,""),t};var Of=(n,e,t)=>{try{K.writeFileSync(n,e),Ir(n,t)}catch(i){throw console.error("Cannot write file ",i),i}};var Cf=(n,e)=>{let t=Vu(e);ke.getInstance().setCurrentNotePath(t),Of(t,n,e),console.log(`Note saved to ${t}`)};var Lf=n=>{let e=new RegExp(`\\${q.sep}`,"g"),t=Ku(n).replace(e,B.pathSeparator||"/");return{absoluteResourceWorkDir:Ya(n),relativeResourceWorkDir:t}},Pf=n=>{let e={},t=n.content,{absoluteResourceWorkDir:i,relativeResourceWorkDir:r}=Lf(n);if(console.log(`relative resource work dir: ${r}`),console.log(`absolute resource work dir: ${i}`),Xu(n),Array.isArray(n.resource))for(let o of n.resource)e={...e,...Df(i,o)};else e={...e,...Df(i,n.resource)};for(let o of Object.keys(e))t=My(t,e,o,r);return t},My=(n,e,t,i)=>{let r=`${i}${B.pathSeparator}${e[t].fileName.replace(/ /g," ")}`;console.log(`mediaReference src ${r} added`);let o,a=`<en-media ([^>]*)hash="${t}".([^>]*)>`,s=new RegExp(a,"g"),l=n.match(s),c=l&&l.length>0&&l[0].split("type=");if(c&&c.length>1&&c[1].startsWith('"image')){let p=l[0].match(/width="(\w+)"/),m=p?` width="${p[1]}"`:"",h=l[0].match(/height="(\w+)"/),w=h?` height="${h[1]}"`:"";o=n.replace(s,`<img src="${r}"${m}${w} alt="${e[t].fileName}">`)}else o=n.replace(s,`<a href="${r}" type="file">${e[t].fileName}</a>`);return o},Df=(n,e)=>{let t={},i=e.data.$text,r=Yu(e),a=Au(n,e).fileName,s=`${n}${q.sep}${a}`;console.log(e),console.log(i);let l=Buffer.from(i,"base64");K.writeFileSync(s,l);let c=r.valueOf()/1e3;try{K.utimesSync(s,c,c)}catch(p){}if(e.recognition&&a){let p=e.recognition.match(/[a-f0-9]{32}/);console.log(`resource ${a} added with hash ${p}`),t[p]={fileName:a,alreadyUsed:!1}}else{let p=Ff.default.createHash("md5");p.update(l);let m=p.digest("hex");t[m]={fileName:a,alreadyUsed:!1}}return t},Mf=(n,e)=>{if(e.indexOf('src="data:')<0)return e;let{absoluteResourceWorkDir:t,relativeResourceWorkDir:i}=Lf(n);return K.mkdirSync(t,{recursive:!0}),e.replace(/src="data:([^;,]*)(;base64)?,([^"]*)"/g,(r,o,a,s)=>{let l=$y(o,a===";base64",s,t,n);return`src="${`${i}${B.pathSeparator}${l}`}"`})},$y=(n,e,t,i,r)=>{let o="embedded",a=By(n)||".dat",s=xi(i,o),l=s<1?`${o}.${a}`:`${o}.${s}.${a}`,c=`${i}${q.sep}${l}`;return e||(t=decodeURIComponent(t)),K.writeFileSync(c,t,e?"base64":void 0),Ir(c,r),console.log(`data url resource ${l} added`),l},By=n=>n.split("/").pop().split("+")[0];var $f=(n,e)=>{let t=new Date;ke.getInstance().setCurrentNoteName(n.title),Array.isArray(n.content)&&(n.content=n.content.join(""));let r={title:n.title,content:n.content,htmlContent:n.content,originalContent:n.content};console.log(`Converting for note "${r.title}" started at ${t}...`);try{of(n)&&(r.htmlContent=Pf(n)),r.htmlContent=Mf(n,r.htmlContent),r={...r,...Hu(B,r)},r={...r,...qu(n,e)},r={...r,...Wu(n)};let o=Rf(r,B);Cf(o,n)}catch(o){throw console.error(`Failed to convert note: ${r.title}`,o),o}finally{let o=new Date,a=(o.getTime()-t.getTime())/1e3;console.log(`Conversion for note "${r.title}" finished at ${o}. Took ${a} seconds`)}};var jf=require("obsidian");var Bf=n=>n.taskstatus=
`,Wy=`{source-url-block}source: {source-url}{end-source-url-block}
`,Yy=`{tags-yaml-list-block}
tags: {tags-yaml-list}
{end-tags-yaml-list-block}`,zy=`{content-block}{content}{end-content-block}
`,Xf=Kf+Yy+Wy+Kf+zy;var lb=ad.Platform.isDesktopApp?od():null,$r={enexSources:[],currentTemplate:"",outputDir:"./mdNotes",isMetadataNeeded:!1,isNotebookNameNeeded:!1,isZettelkastenNeeded:!1,useZettelIdAsFilename:!1,plainTextNotesOnly:!1,skipWebClips:!1,useHashTags:!0,nestedTags:{separatorInEN:"_",replaceSeparatorWith:"/",replaceSpaceWith:"-"},obsidianTaskTag:"",urlEncodeFileNamesAndLinks:!1,sanitizeResourceNameSpaces:!1,replacementChar:"_",pathSeparator:"/",resourcesDir:"_resources",turndownOptions:{headingStyle:"atx"}},cb="@@@",B={...$r};function pb(n){return n==null?n:JSON.parse(JSON.stringify(n))}function sd(n,...e){for(let t of e)for(let i of Object.keys(t)){let r=t[i],o=n[i];!Array.isArray(r)&&typeof r=="object"&&!Array.isArray(o)&&typeof o=="object"?n[i]=sd({},o,r):n[i]=pb(r)}return n}var ub=n=>{B=sd({},$r,n);let e=B.templateFile?K.readFileSync(B.templateFile,"utf-8"):Xf;e=B.currentTemplate?B.currentTemplate:e,B.skipCreationTime=!Wf(e),B.skipLocation=!Yf(e),B.skipSourceUrl=!Zf(e),B.skipTags=!Gf(e),B.skipUpdateTime=!Vf(e),B.isNotebookNameNeeded=zf(e),B.currentTemplate=e,console.log(`Current config is: ${JSON.stringify(B,null,4)}`),console.log(`Path separator:${q.sep}`)},fb=async(n,e,t)=>{if(!(e instanceof Be))throw new Error("Evernote import currently only works on desktop");let i=ke.getInstance();t.status("Processing "+e.name),console.log(`Getting stream from ${e}`);let r=e.createReadStream(),o={},a=i.getCurrentNotebookName();return new Promise((s,l)=>{let c=h=>(t.reportFailed(i.getCurrentNotebookFullpath(),h),l(h)),p=lb(r),m=null;p.on("tag:note-attributes",h=>{m=h}),p.on("tag:note",h=>{if(t.isCancelled()){r.close();return}if(n.skipWebClips&&af(h))t.reportSkipped(h.title);else{t.status("Importing note "+h.title),m&&(h["note-attributes"]=m);try{$f(h,a),t.reportNoteSuccess(a+"/"+h.title)}catch(v){return t.reportFailed(h.title||e,v),s()}}m=null;let w=i.getCurrentNotePath();if(w)for(let v of Object.keys(o)){let d=`<YARLE-EN-V10-TASK>${v}</YARLE-EN-V10-TASK>`,f=K.readFileSync(w,"utf8"),g=new Map([...o[v]].sort()),E=f.replace(d,[...g.values()].join(`
`));K.writeFileSync(w,E)}}),p.on("tag:task",h=>{let w=iu(h);o[w.taskgroupnotelevelid]||(o[w.taskgroupnotelevelid]=new Map),o[w.taskgroupnotelevelid].set(w.sortweight,Hf(w,a))}),p.on("end",s),p.on("error",c),r.on("error",c)})};async function ld(n,e){ub(n);let t=[],i=n.outputDir;for(let r of n.enexSources){if(e.isCancelled())return;let o,a=ke.getInstance();r.basename.includes(cb)?(n.outputDir=ef(r,n),o=Qu(r),nf(o,n),a.setCurrentNotebookName(o.basename),a.setCurrentNotebookFullpath(o.fullpath)):(tf(r,n),a.setCurrentNotebookName(r.basename),a.setCurrentNotebookFullpath(r.fullpath)),await fb(n,r,e),t.push(za()),n.outputDir=i}e.isCancelled()||await qf(n,t)}var Br=class extends ue{init(){this.addFileChooserSetting("Evernote",["enex"],!0),this.addOutputLocationSetting("Evernote")}async import(e){let{files:t}=this;if(t.length===0){new Ti.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new Ti.Notice("Please select a location to export to.");return}let{app:r}=this,o=r.vault.adapter;if(!(o instanceof Ti.FileSystemAdapter))return;let a={...$r,enexSources:t,outputDir:q.join(o.getBasePath(),i.path)};await ld(a,e)}};var Se=require("obsidian");var Ur=class extends ue{init(){this.addFileChooserSetting("HTML",["htm","html"],!0),this.addAttachmentSizeLimit(0),this.addMinimumImageSize(65),this.addOutputLocationSetting("HTML import")}addAttachmentSizeLimit(e){this.attachmentSizeLimit=e*10**6,new Se.Setting(this.modal.contentEl).setName("Attachment size limit (MB)").setDesc("Set 0 to disable.").addText(t=>t.then(({inputEl:i})=>{i.type="number",i.step="0.1"}).setValue(e.toString()).onChange(i=>{let r=["+","-"].includes(i)?0:Number(i);if(Number.isNaN(r)||r<0){t.setValue((this.attachmentSizeLimit/10**6).toString());return}this.attachmentSizeLimit=r*10**6}))}addMinimumImageSize(e){this.minimumImageSize=e,new Se.Setting(this.modal.contentEl).setName("Minimum image size (px)").setDesc("Set 0 to disable.").addText(t=>t.then(({inputEl:i})=>i.type="number").setValue(e.toString()).onChange(i=>{let r=["+","-"].includes(i)?0:Number(i);if(!Number.isInteger(r)||r<0){t.setValue(this.minimumImageSize.toString());return}this.minimumImageSize=r}))}async import(e){let{files:t}=this;if(t.length===0){new Se.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new Se.Notice("Please select a location to export to.");return}let r=new Map;e.reportProgress(0,t.length);for(let l=0;l<t.length;l++){if(e.isCancelled())return;let c=t[l],p=await this.processFile(e,i,c);p&&r.set(c instanceof Be?ni.pathToFileURL(c.filepath).href:c.name,{file:c,tFile:p}),e.reportProgress(l+1,t.length)}let{metadataCache:o}=this.app,a,s=new Promise(l=>{a=l});o.onCleanCache(async()=>{for(let[l,{file:c,tFile:p}]of r){if(e.isCancelled())break;try{let m=await this.app.vault.cachedRead(p),h=o.computeMetadataAsync?await o.computeMetadataAsync(Mo(m)):o.getFileCache(p);if(!h)continue;let w=[];if(h.links)for(let{link:v,position:d,displayText:f}of h.links){let{path:g,subpath:E}=(0,Se.parseLinktext)(v),T;if(ni){let O=new URL(encodeURI(g),l);O.hash="",O.search="",T=decodeURIComponent(O.href)}else T=oe(g.replace(/#/gu,"%23")).name;let A=r.get(T);if(A){let O=this.app.fileManager.generateMarkdownLink(A.tFile,p.path,E,f);w.push({from:d.start.offset,to:d.end.offset,text:O})}}w.sort((v,d)=>d.from-v.from);for(let v of w)m=m.substring(0,v.from)+v.text+m.substring(v.to);await this.vault.modify(p,m)}catch(m){e.reportFailed(c.fullpath,m)}}a()}),await s}async processFile(e,t,i){e.status("Processing "+i.name);try{let r=await i.readText(),o=dt(r);db(o);let a=i instanceof Be?ni.pathToFileURL(i.filepath):void 0,s=new Map,l=new Map;for(let m of o.findAll("img, audio, video")){if(e.isCancelled())return;let h=m.getAttribute("src");if(h)try{let w=new URL(h.startsWith("//")?`https:${h}`:h,a),v=w.href,d=s.get(v);s.has(v)||(e.status("Downloading attachment for "+i.name),d=await this.downloadAttachment(t,m,w),s.set(v,d),d?(l.set(d.path,d),e.reportAttachmentSuccess(d.name)):e.reportSkipped(h)),d&&(m.setAttribute("src",d.path.replace(/
`).filter(p=>p!==r);c.length>0&&(a.aliases=c)}let s=[];if(t.color&&t.color!=="DEFAULT"){let c=t.color.toLowerCase();c=pd(c),s.push(`Keep/Color/${c}`)}if(t.isPinned&&s.push("Keep/Pinned"),t.attachments&&s.push("Keep/Attachment"),t.isArchived&&s.push("Keep/Archived"),t.isTrashed&&s.push("Keep/Deleted"),t.labels)for(let c of t.labels)s.push(`Keep/Label/${c.name}`);if(s.length>0&&(a.tags=s.map(c=>ts(c))),o.push(Qi(a)),t.textContent&&(o.push(`
`),o.push(ns(t.textContent))),t.listContent){let c=[];for(let p of t.listContent){if(!p.text)continue;let m=`- [${p.isChecked?"X":" "}] ${p.text}`;c.push(ns(m))}o.push(`
`),o.push(c.join(`
`))}if(t.attachments){o.push(`
`);for(let c of t.attachments)o.push(`![[${c.filePath}]]`)}let l=await this.saveAsMarkdownFile(i,r,o.join(""));await this.vault.append(l,"",{ctime:t.createdTimestampUsec/1e3,mtime:t.userEditedTimestampUsec/1e3})}};var wt=require("obsidian");var is=require("obsidian");function ud({info:n,vault:e,targetFolderPath:t,parentsInSubfolders:i}){let r=e.getAllLoadedFiles(),o=new Set,a=new Set(r.map(s=>s.name));i&&Tb(n),Eb({info:n,pathDuplicateChecks:o,titleDuplicateChecks:a}),_b({info:n,loadedFiles:r,titleDuplicateChecks:a,targetFolderPath:t})}function Eb({info:n,pathDuplicateChecks:e,titleDuplicateChecks:t}){for(let i of Object.values(n.idsToFileInfo)){let r=n.getPathForFile(i);if(e.has(`${r}${i.title}`)){let o=2;for(i.title=i.title+" "+o;e.has(`${r}${i.title}`);)o++,i.title=`${i.title.replace(/ \d+$/,"")} ${o}`}t.has(i.title+".md")&&(i.fullLinkPathNeeded=!0),e.add(`${r}${i.title}`),t.add(i.title+".md")}}function Tb(n){let e=new Set(Object.values(n.idsToFileInfo).map(t=>t.parentIds).concat(Object.values(n.pathsToAttachmentInfo).map(t=>t.parentIds)).map(t=>t.length>0?t[t.length-1]:""));for(let t of Object.keys(n.idsToFileInfo))e.has(t)&&n.idsToFileInfo[t].parentIds.push(t)}function _b({info:n,loadedFiles:e,titleDuplicateChecks:t,targetFolderPath:i}){var l;let r=new Set(e.filter(c=>!c.path.endsWith(".md")).map(c=>c.path)),o=n.attachmentPath,a=/^\.\//.test(o),s=(l=o.match(/\.\/(.*)/))==null?void 0:l[1];for(let c of Object.values(n.pathsToAttachmentInfo)){t.has(c.nameWithExtension)&&(c.fullLinkPathNeeded=!0);let p="";if(a?p=(0,is.normalizePath)(`${i}${n.getPathForFile(c)}${s!=null?s:""}`):p=(0,is.normalizePath)(o+"/"),p.endsWith("/")||(p+="/"),r.has(p+c.nameWithExtension)){let m=2,{basename:h,extension:w}=oe(c.path);for(;r.has(`${p}${h} ${m}.${w}`);)m++;c.nameWithExtension=`${h} ${m}.${w}`}c.targetParentFolder=p,r.add(p+c.nameWithExtension),t.add(c.nameWithExtension)}}var Bn=require("obsidian");var fd=n=>n.replace(/-/g,"").replace(/[ -]?[a-z0-9]{32}(\.|$)/,"$1"),xt=n=>{var e;return(e=n.replace(/-/g,"").match(/([a-z0-9]{32})(\?|\.|$)/))==null?void 0:e[1]},rs=n=>{let{parent:e}=oe(n);return e.split("/").map(t=>xt(t)).filter(t=>t)};function os(n){return n.hour()===0&&n.minute()===0?n.format("YYYY-MM-DD"):n.format("YYYY-MM-DDTHH:mm")}function dd(n){return n.replace(/^(\.\.\/)+/,"")}function md(n){let e=/#\d*?(?:[-_/a-z]|[^\x00-\x7F])/gi;if(!e.test(n))return n;let t=n.split(`
`);for(let i=0;i<t.length;i++){let r=t[i].match(e);if(!r)continue;let o=t[i];for(let a of r)new RegExp(`\\[\\[[^\\]]*${a}(?:.*[^\\]])?\\]\\]|\\[[^\\]]*${a}[^\\]]*\\]\\([^\\)]*\\)|\\[[^\\]]*\\]\\([^\\)]*${a}[^\\)]*\\)|\\\\${a}|\`[^\`]*${a}[^\`]*\``).test(o)||(o=o.replace(a,"\\"+a));t[i]=o}return n=t.join(`
`),n}function as(n){n.replaceWith(...Array.from(n.childNodes))}async function _d(n,e){var p;let t=await e.readText(),i=dt(t),r=i.find("div[class=page-body]");if(r===null)throw new Error("page body was not found");let o=gd(n,r);Td(n,o,!0);let a={},s=i.find("table[class=properties] > tbody");if(s){let m=gd(n,s);Td(n,m,!1),Yb(s);for(let h of Array.from(s.rows)){let w=Ab(h);w&&(w.title=="Tags"&&(w.title="tags",typeof w.content=="string"?w.content=w.content.replace(/ /g,"-"):w.content instanceof Array&&(w.content=w.content.map(v=>v.replace(/ /g,"-")))),a[w.title]=w.content)}}Lb(r,["strong","em","mark","del"]),Ib(r),Nb(r),jb(r),Ob(r),Ub(r),Nd(r),vd(r,"div.indented"),vd(r,"details"),Hb(r),Ed(r,"ul"),Ed(r,"ol"),qb(r),Wb(r),Bb(r),Db(r);let l=(0,Bn.htmlToMarkdown)(r.innerHTML);n.singleLineBreaks&&(l=l.replace(/\n\n(?!>)/g,`
`)),l=md(l),l=kb(l);let c=(p=i.find("p[class*=page-description]"))==null?void 0:p.textContent;return c&&(l=c+`
`+l),Qi(a)+l}var hd={checkbox:["checkbox"],date:["created_time","last_edited_time","date"],list:["file","multi_select","relation"],number:["number","auto_increment_id"],text:["email","person","phone_number","text","url","status","select","formula","rollup","last_edited_by","created_by"]};function Ab(n){var a,s,l,c,p,m;let e=(a=n.className.match(/property-row-(.*)/))==null?void 0:a[1];if(!e)throw new Error("property type not found for: "+n);let t=(0,Bn.htmlToMarkdown)((s=n.cells[0].textContent)!=null?s:""),i=n.cells[1],r=Object.keys(hd).find(h=>hd[h].includes(e));if(!r)throw new Error("type not found for: "+i);let o="";switch(r){case"checkbox":o=i.innerHTML.includes("checkbox-on");break;case"number":if(o=Number(i.textContent),isNaN(o))return;break;case"date":Nd(i);let h=i.getElementsByTagName("time");if(h.length===0)o="";else if(h.length===1)o=os((0,Bn.moment)((l=h.item(0))==null?void 0:l.textContent));else{let d=[];for(let f=0;f<h.length;f++)d.push(os((0,Bn.moment)((c=h.item(f))==null?void 0:c.textContent)));o=d.join(" - ")}if(o.length===0)return;break;case"list":let w=i.children,v=[];for(let d=0;d<w.length;d++){let f=(p=w.item(d))==null?void 0:p.textContent;f&&v.push(f)}if(o=v,o.length===0)return;break;case"text":if(o=(m=i.textContent)!=null?m:"",o.length===0)return;break}return{title:t,content:o}}function gd(n,e){var i,r;let t=[];for(let o of e.findAll("a")){let a=dd(decodeURI((i=o.getAttribute("href"))!=null?i:"")),s=xt(a),l=Object.keys(n.pathsToAttachmentInfo).find(c=>c.includes(a));s&&a.endsWith(".html")?t.push({type:"relation",a:o,id:s}):l?t.push({type:"attachment",a:o,path:l}):s&&a.startsWith("#")&&((r=o.parentElement)!=null&&r.classList.contains("table_of_contents-item"))&&t.push({type:"toc-item",a:o,id:s})}return t}function kb(n){let e=/\[\[[^\]]*(\\\\)\|[^\]]*\]\]/,t=n.match(new RegExp(e,"g"));return t==null||t.forEach(i=>{n=n.replace(i,i.replace(/\\\\\|/g,"\\|"))}),n}function Nb(n){Fb(n,"style"),Ad(n,"span.notion-text-equation-token");let e=n.ownerDocument,t=n.findAll("figure.equation");for(let r of t){let o=r.find("annotation");if(!o)continue;let a=e.createElement("div");a.className="annotation",a.appendText(`$$${yd(o.textContent)}$$`),r.replaceWith(a)}let i=n.findAll("span.notion-text-equation-token");for(let r of i){let o=r.find("annotation");o&&r.replaceWith(`$${yd(o.textContent,!0)}$`)}}function yd(n,e=!1){var i;let t=new RegExp(/^(?:\s|\\\\|\\\s)*(.*?)[\s\\]*$/,"s");return(i=n==null?void 0:n.replace(t,"$1").replace(/[\r\n]+/g,e?" ":`
`))!=null?i:""}function Sb(n){var t;let e=(t=n.match(/^[^\.\?\!\n]*[\.\?\!]?/))==null?void 0:t[0];return e!=null?e:""}function Rb(n){var e;return!!/callout|bookmark/.test((e=n.getAttribute("class"))!=null?e:"")}function Ob(n){var t;let e=n.ownerDocument;for(let i of n.findAll("figure.callout")){let r=(t=i.lastElementChild)==null?void 0:t.childNodes;if(!r)continue;let o=e.createElement("blockquote");o.append(...Array.from(r)),Cb(o),i.replaceWith(o)}}function Cb(n){var o,a,s;let e=n.firstChild,t=(o=e==null?void 0:e.nodeName)!=null?o:"",i=n.ownerDocument.createElement("p"),r="";t=="#text"?r=(a=e==null?void 0:e.textContent)!=null?a:"":t=="P"?r=e.innerHTML:["EM","STRONG","DEL","MARK"].includes(t)?r=e.outerHTML:n.prepend(i),r=r.replace(/<br>/g,"&lt;br&gt;"),i.innerHTML=`[!important] ${r}`,(s=n.firstChild)==null||s.replaceWith(i)}function Ib(n){var e,t,i;for(let r of n.findAll("a.bookmark.source")){let o=r.getAttribute("href"),a=(e=r.find("div.bookmark-title"))==null?void 0:e.textContent,s=Sb((i=(t=r.find("div.bookmark-description"))==null?void 0:t.textContent)!=null?i:""),l=`> [!info] ${a}
> ${s}
> [${o}](${o})
`;r.nextElementSibling&&Rb(r.nextElementSibling)&&(l+=`
`),r.replaceWith(l)}}function Db(n){var e,t,i;for(let r of n.findAll("span[class=user]"))r.innerText=(e=r.textContent)!=null?e:"";for(let r of n.findAll("td div[class*=checkbox]")){let o=createSpan();o.setText(r.hasClass("checkbox-on")?"X":""),r.replaceWith(o)}for(let r of n.findAll("table span[class*=selected-value]"))((t=r.parentElement)==null?void 0:t.lastElementChild)!==r&&r.setText(r.textContent+", ");for(let r of n.findAll("a[href]"))if(!/^(https?:\/\/|www\.)/.test(r.href)){let o=createSpan();o.setText((i=r.textContent)!=null?i:""),r.replaceWith(o)}}function Fb(n,e){for(let t of n.findAll(e))t.remove()}function Lb(n,e){for(let t of e)Pb(n,t);for(let t of e)Mb(n,t);for(let t of e)Ad(n,t);for(let t of e)$b(n,t)}function Pb(n,e){for(let t of n.findAll(e)){if(!t.parentElement||t.parentElement.tagName===e.toUpperCase())continue;let i=t.find(e);for(;i;)as(i),i=t.find(e)}}function Mb(n,e){let t=n.findAll(e);if(!t)return;let i=new RegExp(`</${e}>( *)<${e}>`,"g");for(let r of t){if(!r||!r.parentElement)continue;let o=r.parentElement,a=o==null?void 0:o.innerHTML;o.innerHTML=a==null?void 0:a.replace(i,"$1")}}function Ad(n,e){let t=n.findAll(e);if(t)for(let i of t){let r=i.previousSibling;(r==null?void 0:r.nodeName)=="BR"&&(r==null||r.remove())}}function $b(n,e){let t=n.innerHTML,i=t.match(new RegExp(`<${e}>.*?</${e}>`,"sg"));if(i){for(let r of i.filter(o=>o.includes("<br>")))t=t.replace(r,r.split("<br>").join(`</${e}><br><${e}>`));n.innerHTML=t}}function bd(n){var e;return Number((e=n==null?void 0:n.classList[1].slice(-1))!=null?e:-1)}function kd(n,e){let t=bd(n),i=bd(e);if(t>i&&e.childElementCount==1){let r=createEl("ul");r.append(n),e.append(r)}else if(t>i&&e.childElementCount==2){let r=e.lastElementChild;r==null||r.append(n)}else if(t==i){let r=e.parentElement;r==null||r.append(n)}else t<i&&(e=e.parentElement.parentElement,kd(n,e))}function xd(n){var t;let e=createEl("li");return e.className=n.className,e.append((t=n.firstElementChild)!=null?t:""),e}function Bb(n){let e=n.find(".table_of_contents"),t=e==null?void 0:e.children;if(!e||t.length==0)return;let i=createEl("ul"),r=xd(t[0]);i.append(r);let o=r;for(let a=1;a<t.length;a++)r=xd(t[a]),kd(r,o),o=r;e.replaceWith(i)}function Ub(n){n.innerHTML=n.innerHTML.replace(/(?:\n|<br ?\/>)/g,"<br>");for(let e of n.findAll("code"))for(let t of e.findAll("br"))t.replaceWith(`
`)}function jb(n){var e;for(let t of n.findAll("link"))t.innerText=(e=t.textContent)!=null?e:""}function Nd(n){var e,t;for(let i of n.findAll("time"))i.textContent=(t=(e=i.textContent)==null?void 0:e.replace(/@/g,""))!=null?t:""}var wd={"1.875em":"h1","1.5em":"h2","1.25em":"h3"};function Hb(n){var t;let e=n.findAll("summary");for(let i of e){let r=i.getAttribute("style");if(r){for(let o of Object.keys(wd))if(r.includes(o)){i.replaceWith(createEl(wd[o],{text:(t=i.textContent)!=null?t:""}));break}}}}function vd(n,e){let t=n.findAll(e);for(let i of t)as(i)}function qb(n){for(let e of n.findAll(".language-Mermaid"))e.removeClass("language-Mermaid"),e.addClass("language-mermaid")}function Ed(n,e){for(let t of n.findAll(e)){let i=[],r=[],o=t;for(;o.tagName===e.toUpperCase();){i.push(o);for(let s=0;s<o.children.length;s++)r.push(o.children[s]);if(!o.nextElementSibling||o.getAttribute("class")!==o.nextElementSibling.getAttribute("class"))break;o=o.nextElementSibling}let a=n.createEl(e);for(let s of r)a.appendChild(s);i[0].replaceWith(a),i.slice(1).forEach(s=>s.remove())}}function Wb(n){for(let e of n.findAll(".checkbox.checkbox-on"))e.replaceWith("[x] ");for(let e of n.findAll(".checkbox.checkbox-off"))e.replaceWith("[ ] ")}function Yb(n){var t;let e=n.findAll("a");if(e.length===0)return n;for(let i of e){let r=createSpan();r.setText((t=i.getAttribute("href"))!=null?t:""),i.replaceWith(r)}}function Td(n,e,t){var i,r,o;for(let a of e){let s=createSpan(),l="";switch(a.type){case"relation":let c=n.idsToFileInfo[a.id];if(c){let h=a.a.closest("table");l=`[[${c.fullLinkPathNeeded?`${n.getPathForFile(c)}${c.title}${h?"\\":""}|${c.title}`:c.title}]]`}else{console.warn("missing relation data for id: "+a.id);let{basename:h}=oe(decodeURI((i=a.a.getAttribute("href"))!=null?i:""));l=`[[${fd(h)}]]`}break;case"attachment":let p=n.pathsToAttachmentInfo[a.path];if(!p){console.warn("missing attachment data for: "+a.path);continue}l=`${t?"!":""}[[${p.fullLinkPathNeeded?p.targetParentFolder+p.nameWithExtension+"|"+p.nameWithExtension:p.nameWithExtension}]]`;break;case"toc-item":l=(r=a.a.textContent)!=null?r:"";let m=(o=l.endsWith("]"))!=null?o:!1;l=`[[#${l+(m?" ":"")}]]`}s.setText(l),a.a.replaceWith(s)}}var Hr=class{constructor(e,t){this.idsToFileInfo={};this.pathsToAttachmentInfo={};this.attachmentPath=e,this.singleLineBreaks=t}getPathForFile(e){let{idsToFileInfo:t}=this,i=e.path.split("/");return e.parentIds.map(r=>{var o,a,s;return(s=(o=t[r])==null?void 0:o.title)!=null?s:(a=i.find(l=>l.contains(r)))==null?void 0:a.replace(` ${r}`,"")}).filter(r=>r).map(r=>r.replace(/[\. ]+$/,"")).join("/")+"/"}};async function Rd(n,e){var i,r;let{filepath:t}=e;if(e.extension==="html"){let o=await e.readText(),a=dt(o),l=a.find("body").children,c;for(let v=0;v<l.length&&(c=xt((i=l[v].getAttr("id"))!=null?i:""),!c);v++);if(!c)throw new Error("no id found for: "+t);let p=Sd(a,"property-row-created_time"),m=Sd(a,"property-row-last_edited_time"),h=((r=a.find("title"))==null?void 0:r.textContent)||"Untitled",w=zb(ze(h.replace(/\n/g," ").replace(/[:\/]/g,"-").replace(/#/g,"").trim()));n.idsToFileInfo[c]={path:t,parentIds:rs(t),ctime:p,mtime:m,title:w,fullLinkPathNeeded:!1}}else n.pathsToAttachmentInfo[t]={path:t,parentIds:rs(t),nameWithExtension:ze(decodeURIComponent(e.name)),targetParentFolder:"",fullLinkPathNeeded:!1}}function zb(n){if(n.length<200)return n;let e=n.split(" "),t=[],i=0,r=0,o=!1;for(;i<200;){if(!e[r]){o=!0;break}t.push(e[r]),i+=e[r].length+1,r++}let a=t.join(" ");return o||(a+="..."),a}function Zb(n){let e=n.startsWith("@")?n.substr(1).trim():n.trim(),t=new Date(e);return isNaN(t.getTime())?null:t}function Sd(n,e){let t=n.querySelector(`tr.${e}`);if(t){let i=t.querySelector("time");return i&&i.textContent?Zb(i.textContent):null}return null}var qr=class extends ue{init(){this.parentsInSubfolders=!0,this.addFileChooserSetting("Exported Notion",["zip"]),this.addOutputLocationSetting("Notion"),new wt.Setting(this.modal.contentEl).setName("Save parent pages in subfolders").setDesc("Places the parent database pages in the same folder as the nested content."
`))}function Od(n){return _i(n)&&!cs(n)}function Ai(n){return n instanceof HTMLBRElement}function ps(n){let e=[],t=n.nextSibling;for(;_i(t)||Ai(t);)e.push(t),t=t.nextSibling;let i=e.findLastIndex(_i);return i===-1?[]:(e.length=i+1,e)}var us="onenote-importer-refresh-token",Cd="66553851-08fa-44f2-8bb1-1436f121a73d",Id=["user.read","notes.read"],Gb=/<(object|iframe)([^>]*)\/>/g,Dd=/(<\/p>)\s*(<p[^>]*>)|\n \n/g,Vb=5,Kb=new RegExp(/^data:[\w\d]+\/[\w\d]+;base64,/);function Xb(n){throw new Error("Didn't expect to get here")}function Jb(n){if(n==null)throw new Error("response is nullish");if(typeof n!="object")throw new Error("response is not an object type");if("@odata.nextLink"in n){let e=n["@odata.nextLink"];if(typeof e!="string")throw new Error(`Link of unknown type: ${typeof e}`)}if(!("value"in n))throw new Error("Expected response to have a 'value' property");if(!Array.isArray(n.value))throw new Error("Expected response to have an error in 'value' property")}function Qb(n){return n instanceof HTMLElement}var Wr=class extends ue{constructor(){super(...arguments);this.importPreviouslyImported=!1;this.importIncompatibleAttachments=!1;this.selectedIds=[];this.notebooks=[];this.graphData={state:Tn(32),accessToken:""};this.attachmentDownloadPauseCounter=0;this.rememberMe=!1;this.lastSuccessfulFetchTime=performance.now()}async init(){this.addOutputLocationSetting("OneNote"),new xe.Setting(this.modal.contentEl).setName("Import incompatible attachments").setDesc("Imports incompatible attachments which cannot be embedded in Obsidian, such as .exe files.").addToggle(r=>r.setValue(!1).onChange(o=>this.importIncompatibleAttachments=o)),new xe.Setting(this.modal.contentEl).setName("Skip previously imported").setDesc("If enabled, notes imported previously by this plugin will be skipped.").addToggle(r=>r.setValue(!0).onChange(o=>this.importPreviouslyImported=!o));let t=!1;if(this.retrieveRefreshToken())try{await this.updateAccessToken(),t=!0}catch(r){}this.microsoftAccountSetting=new xe.Setting(this.modal.contentEl).setName("Sign in with your Microsoft account").setDesc("You need to sign in to import your OneNote data.").addButton(r=>r.setCta().setButtonText("Sign in").onClick(()=>{this.registerAuthCallback(this.authenticateUser.bind(this));let o=new URLSearchParams({client_id:Cd,scope:"offline_access "+Id.join(" "),response_type:"code",redirect_uri:Yr,response_mode:"query",state:this.graphData.state});window.open(`https://login.microsoftonline.com/common/oauth2/v2.0/authorize?${o.toString()}`)})),this.microsoftAccountSetting.settingEl.toggle(!t);let i=new xe.Setting(this.modal.contentEl).setName("Remember me").setDesc("If checked, you will be automatically logged in for subsequent imports.").addToggle(r=>{r.onChange(o=>{this.rememberMe=o,o&&this.refreshToken?this.storeRefreshToken(this.refreshToken):this.clearStoredRefreshToken()})});i.settingEl.toggle(!t),this.switchUserSetting=new xe.Setting(this.modal.contentEl).addButton(r=>r.setCta().setButtonText("Switch user").onClick(()=>{this.microsoftAccountSetting.settingEl.show(),i.settingEl.show(),this.clearStoredRefreshToken(),this.switchUserSetting.settingEl.hide(),this.contentArea.empty()})),this.loadingArea=this.modal.contentEl.createDiv({text:"Loading notebooks..."}),this.loadingArea.hide(),this.contentArea=this.modal.contentEl.createDiv(),this.contentArea.hide(),t?(await this.setSwitchUser(),await this.showSectionPickerUI()):this.switchUserSetting.settingEl.hide()}async authenticateUser(t){try{if(t.state!==this.graphData.state)throw new Error(`An incorrect state was returned.
Expected state: ${this.graphData.state}
Returned state: ${t.state}`);await this.updateAccessToken(t.code),await this.setSwitchUser(),await this.showSectionPickerUI()}catch(i){console.error("An error occurred while we were trying to sign you in. Error details: ",i),this.modal.contentEl.createEl("div",{text:"An error occurred while trying to sign you in."}).createEl("details",{text:i}).createEl("summary",{text:"Click here to show error details"})}}async setSwitchUser(){let t=await this.fetchResource("https://graph.microsoft.com/v1.0/me","json");this.switchUserSetting.setDesc(`Signed in as ${t.displayName} (${t.mail}). If that's not the correct account, sign in again.`),this.switchUserSetting.settingEl.show(),this.microsoftAccountSetting.settingEl.hide()}async updateAccessToken(t){let i=new URLSearchParams({client_id:Cd,scope:"offline_access "+Id.join(" "),redirect_uri:Yr});if(t)i.set("code",t),i.set("grant_type","authorization_code");else{let o=this.retrieveRefreshToken();if(!o)throw new Error("Missing token required for authentication. Please try logging in again.");i.set("refresh_token",o),i.set("grant_type","refresh_token")}let r=await(0,xe.requestUrl)({method:"POST",url:"https://login.microsoftonline.com/common/oauth2/v2.0/token",contentType:"application/x-www-form-urlencoded",body:i.toString()}).json;if(!r.access_token)throw new Error(`Unexpected data was returned instead of an access token. Error details: ${r}`);r.refresh_token&&this.storeRefreshToken(r.refresh_token),this.graphData.accessToken=r.access_token}storeRefreshToken(t){this.refreshToken=t,this.rememberMe&&localStorage.setItem(us,t)}retrieveRefreshToken(){return this.refreshToken?this.refreshToken:localStorage.getItem(us)}clearStoredRefreshToken(){localStorage.removeItem(us)}async showSectionPickerUI(){var o,a;this.loadingArea.show(),this.selectedIds=[];let t="https://graph.microsoft.com/v1.0/me/onenote/notebooks",i=new URLSearchParams({$expand:"sections($select=id,displayName),sectionGroups($expand=sections,sectionGroups)",$select:"id,displayName,lastModifiedDateTime",$orderby:"lastModifiedDateTime DESC"}),r=`${t}?${i.toString()}`;try{this.notebooks=(await this.fetchResource(r,"json-wrapped")).value,this.contentArea.empty(),this.contentArea.createEl("h4",{text:"Choose data to import"});for(let s of this.notebooks){if(((o=s.sectionGroups)==null?void 0:o.length)!==0)for(let c of s.sectionGroups)await this.fetchNestedSectionGroups(c);let l=this.contentArea.createDiv();new xe.Setting(l).setName(s.displayName).setDesc(`Last edited on: ${xe.moment.utc(s.lastModifiedDateTime).format("Do MMMM YYYY")}. Contains ${(a=s.sections)==null?void 0:a.length} sections.`).addButton(c=>c.setCta().setButtonText("Select all").onClick(()=>{l.querySelectorAll('input[type="checkbox"]:not(:checked)').forEach(p=>p.click())})),this.renderHierarchy(s,l)}}catch(s){this.showContentAreaErrorMessage()}this.loadingArea.hide(),this.contentArea.show()}async fetchNestedSectionGroups(t){if(t.sectionGroups=(await this.fetchResource(t.sectionGroupsUrl+"?$expand=sectionGroups($expand=sections),sections","json-wrapped")).value,t.sectionGroups)for(let i=0;i<t.sectionGroups.length;i++)await this.fetchNestedSectionGroups(t.sectionGroups[i])}renderHierarchy(t,i){if(t.sectionGroups)for(let r of t.sectionGroups){let o=i.createDiv({attr:{style:"padding-inline-start: 1em; padding-top: 8px"}});o.createEl("strong",{text:r.displayName}),this.renderHierarchy(r,o)}if(t.sections){let r=i.createEl("ul",{attr:{style:"padding-inline-start: 1em;"}});for(let o of t.sections){let s=r.createEl("li",{cls:"task-list-item"}).createEl("label"),l=s.createEl("input");l.type="checkbox",s.appendChild(document.createTextNode(o.displayName)),s.createEl("br"),l.addEventListener("change",()=>{if(l.checked)this.selectedIds.push(o.id);else{let c=this.selectedIds.findIndex(p=>p===o.id);c!==-1&&this.selectedIds.splice(c,1)}})}}}showContentAreaErrorMessage(){this.contentArea.empty(),this.contentArea.createEl("p",{text:"Microsoft OneNote has limited how fast notes can be imported. Please try again in 1 hour to continue importing."}),this.contentArea.show(),this.loadingArea.
`,1)[0];t.slice(0,-2);let o=t.split(r);if(o.shift(),o.length===2)for(let a of o){let l=a.split(`
`).find(p=>p.includes("Content-Type")).split(";")[0].split(":")[1].trim(),c=a.split(`
`).slice(2).join(`
`).trim();l==="text/html"?i.html=c:l==="application/inkml+xml"&&(i.inkml=c)}else throw new Error("The input string is incorrect and may be missing data. Inputted string: "+t);return i}convertTags(t){var r,o;let i=Array.from(t.querySelectorAll("[data-tag]"));for(let a of i)if((r=a.getAttribute("data-tag"))!=null&&r.contains("to-do")){let l=a.getAttribute("data-tag")==="to-do:completed"?"[x]":"[ ]";a.innerHTML=`- ${l} ${a.innerHTML}`}else{let s=(o=a.getAttribute("data-tag"))==null?void 0:o.split(",");s==null||s.forEach(l=>{a.innerHTML=a.innerHTML+` #${l.replace(":","-")} `})}return t.outerHTML}convertInternalLinks(t){let i=t.findAll("a");for(let r of i)if(r.href.startsWith("onenote:")){let o=r.href.indexOf("#")+1,a=r.href.indexOf("&",o);r.href=r.href.slice(o,a)}}getEntityPathNoParent(t,i){for(let r of this.notebooks){let o=this.getEntityPath(t,`${i}/${r.displayName}`,r);if(o)return o}return null}getEntityPath(t,i,r){let o=null;if("sectionGroups"in r&&r.sectionGroups){let a=this.searchSectionGroups(t,i,r.sectionGroups);a!==null&&(o=a)}if("sections"in r&&r.sections){let a=this.searchSectionGroups(t,i,r.sections);a!==null&&(o=a)}if("pages"in r&&r.pages){let a=this.searchPages(t,i,r);a!==null&&(o=a)}return o&&(o=this.sanitizeFilePath(o)),o}searchPages(t,i,r){var a;let o=null;for(let s=0;s<r.pages.length;s++){let l=r.pages[s],c=(a=l.contentUrl.split("page-id=")[1])==null?void 0:a.split("}")[0];if(l.id===t||c===t){if(l.level===0)r.pages[s+1]&&r.pages[s+1].level!==0?o=`${i}/${l.title}`:o=i;else{o=i;for(let p=r.pages.indexOf(l)-1;p>=0;p--)if(r.pages[p].level===l.level-1){o+="/"+r.pages[p].title;break}}break}}return o}searchSectionGroups(t,i,r){let o=null;for(let a of r)if(a.id===t)o=`${i}/${a.displayName}`;else{let s=this.getEntityPath(t,`${i}/${a.displayName}`,a);if(s){o=s;break}}return o}sanitizeOCRText(t){return t=t.replace(/[^\w\d\s]/g,""),t=t.replace(/\s+/g," ").trim(),t.length>50&&(t=t.substring(0,50)+"..."),t}async getAllAttachments(t,i){var l,c,p,m;let r=dt(i.replace(Gb,"<$1$2></$1>")),o=r.findAll("object"),a=r.findAll("img"),s=r.findAll("iframe");for(let h of o){for(;h.firstChild;)(l=h.parentNode)==null||l.insertBefore(h.firstChild,h.nextSibling);let w=h.getAttribute("data-attachment").split("."),v=w[w.length-1];if(!(!$n.contains(v)&&!this.importIncompatibleAttachments)){let d=h.getAttribute("data-attachment"),f=h.getAttribute("data"),g=await this.fetchAttachment(t,d,f),E=document.createElement("p");E.innerText=`![[${g}]]`,(c=h.parentNode)==null||c.replaceChild(E,h)}}for(let h=0;h<a.length;h++){let w=a[h],d=w.getAttribute("data-fullres-src-type").split("/")[1],g=`Exported image ${(0,xe.moment)().format("YYYYMMDDHHmmss")}-${h}.${d}`,E=w.getAttribute("data-fullres-src"),T=await this.fetchAttachment(t,g,E);T&&(w.src=encodeURI(T),!w.alt||Kb.test(w.alt)?w.alt="Exported image":w.alt=this.sanitizeOCRText(w.alt)||"Exported image")}for(let h of s)if(h.src.contains("youtube.com")||h.src.contains("youtu.be")){let w=document.createTextNode(`![Embedded YouTube video](${h.src})`);(p=h.parentNode)==null||p.replaceChild(w,h)}else{let w=document.createElement("a");w.href=h.src,(m=h.parentNode)==null||m.replaceChild(w,h)}return r}async fetchAttachment(t,i,r){this.attachmentDownloadPauseCounter===7&&await new Promise(o=>{t.status("Pausing attachment download to avoid rate limiting."),this.attachmentDownloadPauseCounter=0,setTimeout(o,3e3)}),this.attachmentDownloadPauseCounter++,t.status("Downloading attachment "+i);try{let o=await this.getAvailablePathForAttachment(i,[]),a=await this.fetchResource(r,"file",t);return await this.app.vault.createBinary(o,a),t.reportAttachmentSuccess(i),o}catch(o){t.reportFailed(i),console.error(o)}}combineCodeBlocksAsNecessary(t){let i=t.querySelectorAll("p:has(+ br + p)");Array.from(i).reverse().forEach(r=>{let o=r,a=r.nextElementSibling;if(!Ai(a))throw new Error(`Expected a <br> element after the paragraph, but found: ${a==null?void 0:a.nodeName}`);let s=a.nextElementSibling;ls(o)&&ls(s)&&(o.appendChild(a),o.appendChild(a.cloneNode()),o.insertAdjacentHTML("beforeend",s.innerHTML),s.remove())})}styledElement
`:c.innerHTML),c.remove()});let l=document.createElement("pre");l.innerHTML="```\n"+s.join("")+"\n```",a.replaceWith(l)}else if(a.nodeName==="TD"){a.removeAttribute("style");return}else{let s=a.getAttribute("style")||"",l=Object.keys(i).find(c=>s.includes(c));if(l){let c=i[l],p=document.createElement(c);p.innerHTML=a.innerHTML,a.replaceWith(p)}}})}convertDrawings(t){var o;let i=document.createTreeWalker(t,NodeFilter.SHOW_COMMENT),r=!1;for(;i.nextNode();)((o=i.currentNode.nodeValue)==null?void 0:o.trim())==="InkNode is not supported"&&(r=!0);if(r){let a=document.createTextNode("> [!caution] This page contained a drawing which was not converted.");t.insertBefore(a,t.firstChild)}else for(let a=0;a<t.children.length;a++){let s=t.children[a];s instanceof HTMLElement&&this.convertDrawings(s)}}removeExtraListItemParagraphs(t){t.querySelectorAll("li > p:first-child").forEach(i=>{Qb(i)&&i.style.marginBottom==="0pt"&&i.style.marginTop==="0pt"&&i.replaceWith(...Array.from(i.childNodes))})}async fetchResource(t,i,r,o=0){var l;if(o>=Vb)throw new Error("Exceeded maximum retry attempts");let a=performance.now()-this.lastSuccessfulFetchTime,s=1e3*60*90;if(a>s&&this.modal.abortController.abort("stalled for >90 minutes"),this.modal.abortController.signal.aborted){let c=(l=this.modal.abortController.signal.reason)!=null?l:"no reason given";throw new Error(`The import was aborted (${c})`)}try{o>0&&console.log(`Retry attempt #${o} for ${t}`);let c=await fetch(t,{headers:{Authorization:`Bearer ${this.graphData.accessToken}`},signal:this.modal.abortController.signal});if(c.ok){let p;switch(i){case"text":p=await c.text();break;case"file":p=await c.arrayBuffer();break;case"json":p=await c.json();break;case"json-wrapped":p=await c.json(),Jb(p),"@odata.nextLink"in p&&p.value.push(...(await this.fetchResource(p["@odata.nextLink"],"json-wrapped",r)).value);break;default:Xb(i)}return this.lastSuccessfulFetchTime=performance.now(),p}else{let p=null,m=await c.json();if(m.hasOwnProperty("error")&&(p=m.error),console.log("An error has occurred while fetching an resource:",p||m),(p==null?void 0:p.code)==="40001"||(p==null?void 0:p.code)==="InvalidAuthenticationToken"||c.status===401)return await this.updateAccessToken(),this.fetchResource(t,i,r,o+1);if((p==null?void 0:p.code)==="20166"||c.status===429){let w=c.headers.get("Retry-After"),v=w?+w*1:60;return console.log(`Rate limit exceeded, waiting for: ${v} seconds`),await this.pause(v,"OneNote API is rate-limiting us",r),this.fetchResource(t,i,r,o)}return this.fetchResource(t,i,r,o+1)}}catch(c){return console.error(`An internal error occurred while trying to fetch '${t}'. Error details: `,c),this.fetchResource(t,i,r,o+1)}}};var Ht=require("obsidian");var Fd=require("obsidian"),e1=/[\?<>\\:\*\|"]/g,t1=/[\x00-\x1f\x80-\x9f]/g,n1=/^\.+$/,i1=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,r1=/[\. ]+$/,o1=/^\./,a1=/\[/g,s1=/\]/g;function zr(n){return n.replace(e1,"").replace(t1,"").replace(n1,"").replace(i1,"").replace(r1,"").replace(a1,"").replace(s1,"").replace(o1,"")}function Zr(n,e){let t="MMMM Do, YYYY",i=(0,Fd.moment)(n,t);return i.format(t)!==n?n:i.isValid()?i.format(e):n}var Gr=require("obsidian"),l1=["POMO","word-count","date","slider","encrypt","TaoOfRoam","orphans","count","character-count","comment-button","query","streak","attr-table","mentions","search","roam/render","calc"],c1=new RegExp(`\\{\\{(\\[\\[)?(${l1.join("|")})(\\]\\])?.*?\\}\\}(\\})?`,"g"),p1=/{{pdf:|{{\[\[pdf|{{\[\[audio|{{audio:|{{video:|{{\[\[video/,Ld=/https:\/\/firebasestorage(.*?)\?alt(.*?)\)/,u1=/https:\/\/firebasestorage(.*?)\?alt(.*?)/,f1=/(?<=\(\()\b(.*?)\b(?=\)\))/g,Vr=class extends ue{constructor(){super(...arguments);this.downloadAttachments=!1;this.fileDateYAML=!1;this.titleYAML=!1;this.newestTimestamp=0;this.oldestTimestamp=0}init(){this.addFileChooserSetting("Roam (.json)",["json"]),this.addOutputLocationSetting("Roam"),this.userDNPFormat=this.getUserDNPFormat(),new Ht.Setting(this.modal.contentEl).setName("Import settings").setHeading(),new Ht.Setting(this.modal.contentEl).setName("Download all attachments").setDesc(
`),k=_.findIndex(x=>x.contains("* "+E));k!==-1&&(_[k]=_[k].replace(E,T)),w.set(A,_.join(`
`))}}let{vault:v}=this,d=w.size,f=1;for(let[g,E]of w.entries()){if(t.isCancelled())return;try{let{parent:T}=oe(g);await this.createFolders(T);let A=v.getAbstractFileByPath(g);A?await v.modify(A,E):await v.create(g,E),t.reportNoteSuccess(g),t.reportProgress(f,d)}catch(T){console.error("Error saving Markdown to file:",g,T),t.reportFailed(g)}f++}}}getUserDNPFormat(){let t=this.app.internalPlugins.getPluginById("daily-notes").instance;return t?t.options.format||"YYYY-MM-DD":(console.log('Daily note plugin is not enabled. Roam import defaulting to "YYYY-MM-DD" format.'),"YYYY-MM-DD")}preprocess(t){let i=new Map,r=new Map,o=this.userDNPFormat;function a(s,l){if(l.uid){let c=new Date(s.uid);if(!isNaN(c.getTime())){let h=Zr(s.title,o);s.title=h}let p={pageName:zr(s.title),blockString:l.string};/.*?(\(\(.*?\)\)).*?/g.test(l.string)&&r.set(l.uid,p),i.set(l.uid,p)}if(l.children)for(let c of l.children)a(s,c)}for(let s of t)if(s.children)for(let l of s.children)a(s,l);return[i,r]}async roamMarkupScrubber(t,i,r,o=!1){return r=r.replace(c1,""),r.substring(0,8)==":hiccup "&&r.includes(":hr")?"---":(r=r.replace(/\[\[(.*?)\]\]/g,(a,s)=>`[[${Zr(zr(s),this.userDNPFormat)}]]`),r=r.replace(/\[\[(.*\/.*)\]\]/g,(a,s)=>`[[${t}/${s}|${s}]]`),r=r.replace(/\[.+?\]\((\(.+?\)\))\)/g,"$1"),r=r.replace(/\[(.+?)\]\(\[\[(.+?)\]\]\)/g,"[[$2|$1]]"),r=r.replace(/\[\[>\]\]/g,">"),r=r.replace(/{{TODO}}|{{\[\[TODO\]\]}}/g,"[ ]"),r=r.replace(/{{DONE}}|{{\[\[DONE\]\]}}/g,"[x]"),r=r.replace("::",":"),r=r.replace(/{{.*?\bvideo\b.*?(\bhttp.*?\byoutu.*?)}}/g,"![]($1)"),r=r.replace(/(https?:\/\/twitter\.com\/(?:#!\/)?\w+\/status\/\d+(?:\?[\w=&-]+)?)/g,"![]($1)"),r=r.replace(/\_\_(.+?)\_\_/g,"*$1*"),r=r.replace(/\^\^(.+?)\^\^/g,"==$1=="),r=r.replace(/{{\[{0,2}embed.*?(\(\(.*?\)\)).*?}}/g,"$1"),r=r.replace(/{{\[{0,2}embed.*?(\[\[.*?\]\]).*?}}/g,"$1"),this.downloadAttachments&&!o&&r.includes("firebasestorage")&&(r=await this.downloadFirebaseFile(r,i)),r)}async jsonToMarkdown(t,i,r,o="",a=!1,s,l,c){let p=[],m=[],h=r["edit-time"],w=r["create-time"];if(this.newestTimestamp<this.oldestTimestamp&&(this.oldestTimestamp=this.newestTimestamp),this.newestTimestamp=!h||c>h?c:h,w!==void 0?l>10?this.oldestTimestamp=Math.min(l,w):this.oldestTimestamp=w:this.oldestTimestamp=l,"string"in r&&r.string){let v=r.heading?"#".repeat(r.heading)+" ":"",d=await this.roamMarkupScrubber(t,i,r.string);p.push(`${a?o+"* ":o}${v}${d}`)}if(r.children)for(let v of r.children)p.push(await this.jsonToMarkdown(t,i,v,o+" ",!0,"",this.oldestTimestamp,this.newestTimestamp));if((this.fileDateYAML||this.titleYAML)&&!a){let v=this.oldestTimestamp;if(m.push("---"),this.titleYAML&&m.push(`title: "${s}"`),this.fileDateYAML){let d="YYYY-MM-DD HH:mm:ss",f=this.newestTimestamp?(0,Gr.moment)(this.newestTimestamp).format(d):(0,Gr.moment)(new Date).format(d),g=v?(0,Gr.moment)(v).format(d):f;m.push("created: "+g),m.push("updated: "+f)}m.push("---"),p.unshift(m.join(`
`))}return p.join(`
`)}async modifySourceBlockString(t,i,r,o){if(!i.blockString.endsWith("^"+o)){let a=`${r}/${i.pageName}.md`,s=t.get(a);if(s){let l=s.split(`
`),c=l.findIndex(p=>p.contains("* "+i.blockString));if(c!==-1){let p=i.blockString+" ^"+o;l[c]=l[c].replace(i.blockString,p),i.blockString=i.blockString+" ^"+o}t.set(a,l.join(`
`))}}}async extractAndProcessBlockReferences(t,i,r,o){let a=o.match(f1);if(!a)return o;let s=[];for(let p of a)try{let m=i.get(p);if(!m){s.push(p);continue}let h=m.blockString.replace(/\[\[|\]\]/g,""),w=`[[${r}/${m.pageName}#^${p}|${h}]]`;await this.modifySourceBlockString(t,m,r,p),s.push(w)}catch(m){s.push(p)}let l=0;return o.replace(/\(\(\b.*?\b\)\)/g,()=>s[l++])}async downloadFirebaseFile(t,i){let{progress:r,vault:o}=this,a="";try{let s,l;if(p1.test(t)?(s=t.match(/https:\/\/firebasestorage(.*?)\?alt(.*?)\}/),l=t.match(/{{.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):Ld.test(t)?(s=t.match(Ld),l=t.match(/!\[.*https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)):(s=t.match(u1),l=t.match(/https:\/\/firebasestorage.*?alt=media&.*?(?=\s|$)/)),s&&l){let c="https://firebasestorage"+s[1],p=decodeURIComponent(c.split("/").last()||"");if(p){let d=p.split("/");d.length>1&&(d.splice(-1,1),this.createFolders(`${i}/${d.join("/")}`))}else{let d=Math.floor(Date.now()/1e3),f=c.slice(-5).match(/(.*?)\.(.+)/);if(!f)return r.reportSkipped(s[1],"Unexpected file extension"),t;p=`${d}.${f[2]}`}let m=`${i}/${p}`;if(o.getAbstractFileByPath(m))return r.reportSkipped(s[1],"File already exists"),t;a=s[0].slice(0,-1);let v=await(await fetch(a,{})).arrayBuffer();return await o.createBinary(m,v),r.reportAttachmentSuccess(a),t.replace(l[0],`![[${m}]]`)}}catch(s){console.error(s),r.reportFailed(a,s)}return t}};var qt=require("obsidian");var Pd=/!\[\]\(assets\/([^)]*)\)/g,Kr=class extends ue{init(){qt.Platform.isMacOS||this.modal.contentEl.createEl("p",{text:"Due to platform limitations, only textpack and zip files can be imported from this device. Open your vault on a Mac to import textbundle files."});let e=qt.Platform.isMacOS?["textbundle","textpack","zip"]:["textpack","zip"];this.addFileChooserSetting("Textbundle",e,!0),this.addOutputLocationSetting("Textbundle")}async import(e){let{files:t}=this;if(t.length===0){new qt.Notice("Please pick at least one file to import.");return}let i=await this.getOutputFolder();if(!i){new qt.Notice("Please select a location to export to.");return}this.attachmentsFolderPath=await this.createFolders(`${i.path}/assets`);for(let r of t)if(r.extension==="textpack")await yt(r,async(o,a)=>{await this.process(e,r.name,a)});else if(r.extension==="zip")await yt(r,async(o,a)=>{let s=this.groupFilesByTextbundle(r.name,a);for(let l of s)await this.process(e,r.name,l)});else{let a=await new en(`${r.toString()}/`).list();await this.process(e,r.name,a)}}groupFilesByTextbundle(e,t){let i={},r=e+"/",o=".textbundle";for(let a of t){if(!a.fullpath.startsWith(r)){console.log("Skipping",a.fullpath);continue}let s=a.fullpath.slice(r.length);if(s.startsWith("._")||s.startsWith("__MACOSX")){console.log("Skipping",a.fullpath);continue}let l=s.indexOf(o);if(l===-1){console.log("Skipping",a.fullpath);continue}let c=s.slice(0,l)+".textbundle";if(s.slice(l+o.length+1).startsWith("._")){console.log("Skipping",a.fullpath);continue}c in i?i[c].push(a):i[c]=[a]}return Object.values(i)}async process(e,t,i){let r=i.find(o=>o.name==="info.json");if(r){let o=await r.readText(),a=JSON.parse(o);if(a.hasOwnProperty("type")&&a.type!=="net.daringfireball.markdown"){e.reportSkipped(t,"The textbundle does not contain markdown");return}}for(let o of i)if(!o.name.startsWith("._"))try{if(o.type==="file"&&(o.extension==="md"||o.extension==="markdown")){let a="parent"in o?o.parent:t;a=a.replace(/.textbundle$/,"");let s=await o.readText();s.match(Pd)&&(s=s.replace(Pd,`![[${this.attachmentsFolderPath.path}/$1]]`));let l=(0,qt.normalizePath)(a),c=await this.getOutputFolder();await this.saveAsMarkdownFile(c,l,s),e.reportNoteSuccess(a)}else if(o.type==="file"&&o.fullpath.contains("assets/"))await this.importAsset(e,o);else if(o.type==="folder"){let{basename:a}=oe(o.toString());if(a!=="assets")continue;let l=await new en(`${o.toString()}/`).list();for(let c of l)await this.importAsset(e,c)}else o.name!=="info.json"&&e.reportSkipped(o.name,"the file is not a media or markdown file.")}catch(a){e.reportFailed(o.name,a)}}async importAsset(e,t){if(t.type==="folder"
/*! Bundled license information:
sax/lib/sax.js:
(*! http://mths.be/fromcodepoint v0.1.0 by @mathias *)
*/
/* nosourcemap */