/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/

var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// node_modules/js-untar/build/dist/untar.js
var require_untar = __commonJS({
  "node_modules/js-untar/build/dist/untar.js"(exports, module2) {
    !function(e, r) {
      "function" == typeof define && define.amd ? define([], r) : "object" == typeof exports ? module2.exports = r() : e.untar = r();
    }(exports, function() {
      "use strict";
      function e(e2) {
        function r2(e3) {
          for (var r3 = 0, n3 = t2.length; r3 < n3; ++r3)
            t2[r3](e3);
          a2.push(e3);
        }
        if ("function" != typeof Promise)
          throw new Error("Promise implementation not available in this environment.");
        var t2 = [], a2 = [], n2 = new Promise(function(t3, a3) {
          e2(t3, a3, r2);
        });
        n2.progress = function(e3) {
          if ("function" != typeof e3)
            throw new Error("cb is not a function.");
          for (var r3 = 0, i3 = a2.length; r3 < i3; ++r3)
            e3(a2[r3]);
          return t2.push(e3), n2;
        };
        var i2 = n2.then;
        return n2.then = function(e3, r3, t3) {
          return i2.call(n2, e3, r3), void 0 !== t3 && n2.progress(t3), n2;
        }, n2;
      }
      function r(r2) {
        if (!(r2 instanceof ArrayBuffer))
          throw new TypeError("arrayBuffer is not an instance of ArrayBuffer.");
        if (!n.Worker)
          throw new Error("Worker implementation is not available in this environment.");
        return new e(function(e2, n2, i2) {
          var o2 = new Worker(a), s = [];
          o2.onerror = function(e3) {
            n2(e3);
          }, o2.onmessage = function(r3) {
            switch (r3 = r3.data, r3.type) {
              case "log":
                console[r3.data.level]("Worker: " + r3.data.msg);
                break;
              case "extract":
                var a2 = t(r3.data);
                s.push(a2), i2(a2);
                break;
              case "complete":
                o2.terminate(), e2(s);
                break;
              case "error":
                o2.terminate(), n2(new Error(r3.data.message));
                break;
              default:
                o2.terminate(), n2(new Error("Unknown message from worker: " + r3.type));
            }
          }, o2.postMessage({ type: "extract", buffer: r2 }, [r2]);
        });
      }
      function t(e2) {
        return Object.defineProperties(e2, o), e2;
      }
      var a, n = window || this, i = n.URL || n.webkitURL, o = { blob: { get: function() {
        return this._blob || (this._blob = new Blob([this.buffer]));
      } }, getBlobUrl: { value: function() {
        return this._blobUrl || (this._blobUrl = i.createObjectURL(this.blob));
      } }, readAsString: { value: function() {
        for (var e2 = this.buffer, r2 = e2.byteLength, t2 = 1, a2 = new DataView(e2), n2 = [], i2 = 0; i2 < r2; ++i2) {
          var o2 = a2.getUint8(i2 * t2, true);
          n2.push(o2);
        }
        return this._string = String.fromCharCode.apply(null, n2);
      } }, readAsJSON: { value: function() {
        return JSON.parse(this.readAsString());
      } } };
      return a = (window || this).URL.createObjectURL(new Blob(['"use strict";function UntarWorker(){}function decodeUTF8(e){for(var r="",t=0;t<e.length;){var a=e[t++];if(a>127){if(a>191&&a<224){if(t>=e.length)throw"UTF-8 decode: incomplete 2-byte sequence";a=(31&a)<<6|63&e[t]}else if(a>223&&a<240){if(t+1>=e.length)throw"UTF-8 decode: incomplete 3-byte sequence";a=(15&a)<<12|(63&e[t])<<6|63&e[++t]}else{if(!(a>239&&a<248))throw"UTF-8 decode: unknown multibyte start 0x"+a.toString(16)+" at index "+(t-1);if(t+2>=e.length)throw"UTF-8 decode: incomplete 4-byte sequence";a=(7&a)<<18|(63&e[t])<<12|(63&e[++t])<<6|63&e[++t]}++t}if(a<=65535)r+=String.fromCharCode(a);else{if(!(a<=1114111))throw"UTF-8 decode: code point 0x"+a.toString(16)+" exceeds UTF-16 reach";a-=65536,r+=String.fromCharCode(a>>10|55296),r+=String.fromCharCode(1023&a|56320)}}return r}function PaxHeader(e){this._fields=e}function TarFile(){}function UntarStream(e){this._bufferView=new DataView(e),this._position=0}function UntarFileStream(e){this._stream=new UntarStream(e),this._globalPaxHeader=null}if(UntarWorker.prototype={onmessage:function(e){try{if("extract"!==e.data.type)throw new Error("Unknown message type: "+e.data.type);this.untarBuffer(e.data.buffer)}catch(r){this.postError(r)}},postError:function(e){this.postMessage({type:"error",data:{message:e.message}})},postLog:function(e,r){this.postMessage({type:"log",data:{level:e,msg:r}})},untarBuffer:function(e){try{for(var r=new UntarFileStream(e);r.hasNext();){var t=r.next();this.postMessage({type:"extract",data:t},[t.buffer])}this.postMessage({type:"complete"})}catch(a){this.postError(a)}},postMessage:function(e,r){self.postMessage(e,r)}},"undefined"!=typeof self){var worker=new UntarWorker;self.onmessage=function(e){worker.onmessage(e)}}PaxHeader.parse=function(e){for(var r=new Uint8Array(e),t=[];r.length>0;){var a=parseInt(decodeUTF8(r.subarray(0,r.indexOf(32)))),n=decodeUTF8(r.subarray(0,a)),i=n.match(/^\\d+ ([^=]+)=(.*)\\n$/);if(null===i)throw new Error("Invalid PAX header data format.");var s=i[1],o=i[2];0===o.length?o=null:null!==o.match(/^\\d+$/)&&(o=parseInt(o));var f={name:s,value:o};t.push(f),r=r.subarray(a)}return new PaxHeader(t)},PaxHeader.prototype={applyHeader:function(e){this._fields.forEach(function(r){var t=r.name,a=r.value;"path"===t?(t="name",void 0!==e.prefix&&delete e.prefix):"linkpath"===t&&(t="linkname"),null===a?delete e[t]:e[t]=a})}},UntarStream.prototype={readString:function(e){for(var r=1,t=e*r,a=[],n=0;n<e;++n){var i=this._bufferView.getUint8(this.position()+n*r,!0);if(0===i)break;a.push(i)}return this.seek(t),String.fromCharCode.apply(null,a)},readBuffer:function(e){var r;if("function"==typeof ArrayBuffer.prototype.slice)r=this._bufferView.buffer.slice(this.position(),this.position()+e);else{r=new ArrayBuffer(e);var t=new Uint8Array(r),a=new Uint8Array(this._bufferView.buffer,this.position(),e);t.set(a)}return this.seek(e),r},seek:function(e){this._position+=e},peekUint32:function(){return this._bufferView.getUint32(this.position(),!0)},position:function(e){return void 0===e?this._position:void(this._position=e)},size:function(){return this._bufferView.byteLength}},UntarFileStream.prototype={hasNext:function(){return this._stream.position()+4<this._stream.size()&&0!==this._stream.peekUint32()},next:function(){return this._readNextFile()},_readNextFile:function(){var e=this._stream,r=new TarFile,t=!1,a=null,n=e.position(),i=n+512;switch(r.name=e.readString(100),r.mode=e.readString(8),r.uid=parseInt(e.readString(8)),r.gid=parseInt(e.readString(8)),r.size=parseInt(e.readString(12),8),r.mtime=parseInt(e.readString(12),8),r.checksum=parseInt(e.readString(8)),r.type=e.readString(1),r.linkname=e.readString(100),r.ustarFormat=e.readString(6),r.ustarFormat.indexOf("ustar")>-1&&(r.version=e.readString(2),r.uname=e.readString(32),r.gname=e.readString(32),r.devmajor=parseInt(e.readString(8)),r.devminor=parseInt(e.readString(8)),r.namePrefix=e.readString(155),r.namePrefix.length>0&&(r.name=r.namePrefix+"/"+r.name)),e.position(i),r.type){case"0":case"":r.buffer=e.readBuffer(r.size);break;case"1":break;case"2":break;case"3":break;case"4":break;case"5":break;case"6":break;case"7":break;case"g":t=!0,this._globalPaxHeader=PaxHeader.parse(e.readBuffer(r.size));break;case"x":t=!0,a=PaxHeader.parse(e.readBuffer(r.size))}void 0===r.buffer&&(r.buffer=new ArrayBuffer(0));var s=i+r.size;return r.size%512!==0&&(s+=512-r.size%512),e.position(s),t&&(r=this._readNextFile()),null!==this._globalPaxHeader&&this._globalPaxHeader.applyHeader(r),null!==a&&a.applyHeader(r),r}};'])), r;
    });
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => TypstPlugin
});
module.exports = __toCommonJS(main_exports);
var import_obsidian = require("obsidian");

// src/compiler.worker.ts
function inlineWorker() {
  let blob = new Blob(['var re={},o,B=typeof TextDecoder!="undefined"?new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}):{decode:()=>{throw Error("TextDecoder not available")}};typeof TextDecoder!="undefined"&&B.decode();var p=null;function v(){return(p===null||p.byteLength===0)&&(p=new Uint8Array(o.memory.buffer)),p}function M(t,e){return t=t>>>0,B.decode(v().subarray(t,t+e))}var d=new Array(128).fill(void 0);d.push(void 0,null,!0,!1);var T=d.length;function w(t){T===d.length&&d.push(d.length+1);let e=T;return T=d[e],d[e]=t,e}function f(t){return d[t]}function V(t){t<132||(d[t]=T,T=t)}function x(t){let e=f(t);return V(t),e}function O(t){return t==null}var h=null;function X(){return(h===null||h.byteLength===0)&&(h=new Float64Array(o.memory.buffer)),h}var A=null;function _(){return(A===null||A.byteLength===0)&&(A=new Int32Array(o.memory.buffer)),A}var l=0,W=typeof TextEncoder!="undefined"?new TextEncoder("utf-8"):{encode:()=>{throw Error("TextEncoder not available")}},J=typeof W.encodeInto=="function"?function(t,e){return W.encodeInto(t,e)}:function(t,e){let n=W.encode(t);return e.set(n),{read:t.length,written:n.length}};function g(t,e,n){if(n===void 0){let c=W.encode(t),u=e(c.length,1)>>>0;return v().subarray(u,u+c.length).set(c),l=c.length,u}let r=t.length,a=e(r,1)>>>0,i=v(),s=0;for(;s<r;s++){let c=t.charCodeAt(s);if(c>127)break;i[a+s]=c}if(s!==r){s!==0&&(t=t.slice(s)),a=n(a,r,r=s+t.length*3,1)>>>0;let c=v().subarray(a+s,a+r),u=J(t,c);s+=u.written}return l=s,a}var E=128;function K(t){if(E==1)throw new Error("out of js stack");return d[--E]=t,E}function Q(t,e){let n=e(t.length*1,1)>>>0;return v().set(t,n/1),l=t.length,n}var k=null;function Y(){return(k===null||k.byteLength===0)&&(k=new Uint8ClampedArray(o.memory.buffer)),k}function Z(t,e){return t=t>>>0,Y().subarray(t/1,t/1+e)}function R(t,e){try{return t.apply(this,e)}catch(n){o.__wbindgen_exn_store(w(n))}}var U=class{__destroy_into_raw(){let e=this.__wbg_ptr;return this.__wbg_ptr=0,e}free(){let e=this.__destroy_into_raw();o.__wbg_systemworld_free(e)}constructor(e,n){try{let r=g(e,o.__wbindgen_malloc,o.__wbindgen_realloc),a=l,i=o.systemworld_new(r,a,K(n));return this.__wbg_ptr=i>>>0,this}finally{d[E++]=void 0}}compile_image(e,n,r,a,i,s){try{let b=o.__wbindgen_add_to_stack_pointer(-16),m=g(e,o.__wbindgen_malloc,o.__wbindgen_realloc),S=l,L=g(n,o.__wbindgen_malloc,o.__wbindgen_realloc),j=l,D=g(a,o.__wbindgen_malloc,o.__wbindgen_realloc),G=l;o.systemworld_compile_image(b,this.__wbg_ptr,m,S,L,j,r,D,G,i,s);var c=_()[b/4+0],u=_()[b/4+1],y=_()[b/4+2];if(y)throw x(u);return x(c)}finally{o.__wbindgen_add_to_stack_pointer(16)}}compile_svg(e,n){let r,a;try{let m=o.__wbindgen_add_to_stack_pointer(-16),S=g(e,o.__wbindgen_malloc,o.__wbindgen_realloc),L=l,j=g(n,o.__wbindgen_malloc,o.__wbindgen_realloc),D=l;o.systemworld_compile_svg(m,this.__wbg_ptr,S,L,j,D);var i=_()[m/4+0],s=_()[m/4+1],c=_()[m/4+2],u=_()[m/4+3],y=i,b=s;if(u)throw y=0,b=0,x(c);return r=y,a=b,M(y,b)}finally{o.__wbindgen_add_to_stack_pointer(16),o.__wbindgen_free(r,a,1)}}add_font(e){let n=Q(e,o.__wbindgen_malloc),r=l;o.systemworld_add_font(this.__wbg_ptr,n,r)}};async function $(t,e){if(typeof Response=="function"&&t instanceof Response){if(typeof WebAssembly.instantiateStreaming=="function")try{return await WebAssembly.instantiateStreaming(t,e)}catch(r){if(t.headers.get("Content-Type")!="application/wasm")console.warn("`WebAssembly.instantiateStreaming` failed because your server does not serve wasm with `application/wasm` MIME type. Falling back to `WebAssembly.instantiate` which is slower. Original error:\\n",r);else throw r}let n=await t.arrayBuffer();return await WebAssembly.instantiate(n,e)}else{let n=await WebAssembly.instantiate(t,e);return n instanceof WebAssembly.Instance?{instance:n,module:t}:n}}function ee(){let t={};return t.wbg={},t.wbg.__wbindgen_string_new=function(e,n){let r=M(e,n);return w(r)},t.wbg.__wbindgen_object_drop_ref=function(e){x(e)},t.wbg.__wbindgen_number_get=function(e,n){let r=f(n),a=typeof r=="number"?r:void 0;X()[e/8+1]=O(a)?0:a,_()[e/4+0]=!O(a)},t.wbg.__wbindgen_string_get=function(e,n){let r=f(n),a=typeof r=="string"?r:void 0;var i=O(a)?0:g(a,o.__wbindgen_malloc,o.__wbindgen_realloc),s=l;_()[e/4+1]=s,_()[e/4+0]=i},t.wbg.__wbindgen_object_clone_ref=function(e){let n=f(e);return w(n)},t.wbg.__wbg_new_abda76e883ba8a5f=function(){let e=new Error;return w(e)},t.wbg.__wbg_stack_658279fe44541cf6=function(e,n){let r=f(n).stack,a=g(r,o.__wbindgen_malloc,o.__wbindgen_realloc),i=l;_()[e/4+1]=i,_()[e/4+0]=a},t.wbg.__wbg_error_f851667af71bcfc6=function(e,n){let r,a;try{r=e,a=n,console.error(M(e,n))}finally{o.__wbindgen_free(r,a,1)}},t.wbg.__wbg_newwithu8clampedarrayandsh_d94fd1baabf57428=function(){return R(function(e,n,r,a){let i=new ImageData(Z(e,n),r>>>0,a>>>0);return w(i)},arguments)},t.wbg.__wbindgen_number_new=function(e){return w(e)},t.wbg.__wbg_call_53fc3abd42e24ec8=function(){return R(function(e,n,r){let a=f(e).call(f(n),f(r));return w(a)},arguments)},t.wbg.__wbg_getTime_ed6ee333b702f8fc=function(e){return f(e).getTime()},t.wbg.__wbg_getTimezoneOffset_5cb2b8973dd9f251=function(e){return f(e).getTimezoneOffset()},t.wbg.__wbg_new_a49511604c14761d=function(e){let n=new Date(f(e));return w(n)},t.wbg.__wbg_new0_ad75dd38f92424e2=function(){return w(new Date)},t.wbg.__wbindgen_throw=function(e,n){throw new Error(M(e,n))},t}function te(t,e){return o=t.exports,F.__wbindgen_wasm_module=e,h=null,A=null,p=null,k=null,o}async function F(t){if(o!==void 0)return o;typeof t=="undefined"&&(t=new URL("obsidian_typst_bg.wasm",re.url));let e=ee();(typeof t=="string"||typeof Request=="function"&&t instanceof Request||typeof URL=="function"&&t instanceof URL)&&(t=fetch(t));let{instance:n,module:r}=await $(await t,e);return te(n,r)}var q=F;var z=!1,oe=new TextDecoder,P,H,N=[],C=new XMLHttpRequest;function ae(t){try{if(!z){if(t.startsWith("@")){if(N.includes(t.slice(1)))return H+t.slice(1);throw 2}t="http://localhost/_capacitor_file_"+P+"/"+t,C.open("GET",t,!1);try{C.send()}catch(r){throw console.error(r),3}if(C.status==404)throw 2;return C.responseText}let e=new Int32Array(new SharedArrayBuffer(4,{maxByteLength:1e8}));e[0]=0,postMessage({buffer:e,path:t});let n=Atomics.wait(e,0,0);if(e[0]==0)return oe.decode(Uint8Array.from(e.slice(1)));throw e[0]}catch(e){throw typeof e!="number"?(console.error(e),1):e}}var I;onmessage=t=>{let e=t.data;switch(e.type){case"canUseSharedArrayBuffer":z=e.data;break;case"startup":q(e.data.wasm).then(n=>{I=new U("",ae),console.log("Typst web assembly loaded!")}),P=e.data.basePath,H=e.data.packagePath;break;case"fonts":e.data.forEach(n=>I.add_font(new Uint8Array(n)));break;case"compile":if(e.data.format=="image"){let n=e.data;postMessage(I.compile_image(n.source,n.path,n.pixel_per_pt,n.fill,n.size,n.display))}else e.data.format=="svg"&&postMessage(I.compile_svg(e.data.source,e.data.path));break;case"packages":N=e.data;break;default:throw e}};console.log("Typst compiler worker loaded!");\n']);
  let url = URL.createObjectURL(blob);
  let worker = new Worker(url);
  URL.revokeObjectURL(url);
  return worker;
}

// src/typst-render-element.ts
var _TypstRenderElement = class _TypstRenderElement extends HTMLElement {
  async connectedCallback() {
    if (!this.isConnected) {
      console.warn("Typst Renderer: Canvas element has been called before connection");
      return;
    }
    if (this.format == "image" && this.canvas == void 0) {
      this.canvas = this.appendChild(createEl("canvas", { attr: { height: _TypstRenderElement.prevHeight }, cls: "typst-doc" }));
    }
    this.num = _TypstRenderElement.nextId.toString();
    _TypstRenderElement.nextId += 1;
    this.id = "TypstRenderElement-" + this.num;
    this.abortController = new AbortController();
    if (this.display) {
      this.style.display = "block";
      this.resizeObserver = new ResizeObserver((entries) => {
        var _a2;
        if (((_a2 = entries[0]) == null ? void 0 : _a2.contentBoxSize[0].inlineSize) !== this.size) {
          this.draw();
        }
      });
      this.resizeObserver.observe(this);
    }
    await this.draw();
  }
  disconnectedCallback() {
    if (this.format == "image") {
      _TypstRenderElement.prevHeight = this.canvas.height;
    }
    if (this.display && this.resizeObserver != void 0) {
      this.resizeObserver.disconnect();
    }
  }
  async draw() {
    this.abortController.abort();
    this.abortController = new AbortController();
    try {
      await navigator.locks.request(this.id, { signal: this.abortController.signal }, async () => {
        let fontSize = parseFloat(getComputedStyle(this).fontSize);
        this.size = this.display ? this.clientWidth : parseFloat(getComputedStyle(this).lineHeight);
        if (!(this.size > 0)) {
          return;
        }
        try {
          let result = await _TypstRenderElement.compile(this.path, this.source, this.size, this.display, fontSize);
          if (result instanceof ImageData && this.format == "image") {
            this.drawToCanvas(result);
          } else if (typeof result == "string" && this.format == "svg") {
            this.innerHTML = result;
            let child = this.firstElementChild;
            child.setAttribute("width", child.getAttribute("width").replace("pt", ""));
            child.setAttribute("height", child.getAttribute("height").replace("pt", ""));
            child.setAttribute("width", `${this.firstElementChild.clientWidth / fontSize}em`);
            child.setAttribute("height", `${this.firstElementChild.clientHeight / fontSize}em`);
          }
        } catch (error) {
          error = error.slice(9);
          let pre = createEl("pre", {
            attr: {
              style: "white-space: pre;"
            }
          });
          pre.textContent = error;
          this.outerHTML = pre.outerHTML;
          return;
        }
      });
    } catch (error) {
      return;
    }
  }
  drawToCanvas(image) {
    let ctx = this.canvas.getContext("2d");
    this.canvas.width = image.width;
    this.canvas.height = image.height;
    ctx.imageSmoothingEnabled = true;
    ctx.imageSmoothingQuality = "high";
    ctx.putImageData(image, 0, 0);
  }
};
_TypstRenderElement.nextId = 0;
_TypstRenderElement.prevHeight = 0;
var TypstRenderElement = _TypstRenderElement;

// src/main.ts
var import_js_untar = __toESM(require_untar());

// node_modules/fflate/esm/browser.js
var u8 = Uint8Array;
var u16 = Uint16Array;
var i32 = Int32Array;
var fleb = new u8([
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  0,
  1,
  1,
  1,
  1,
  2,
  2,
  2,
  2,
  3,
  3,
  3,
  3,
  4,
  4,
  4,
  4,
  5,
  5,
  5,
  5,
  0,
  /* unused */
  0,
  0,
  /* impossible */
  0
]);
var fdeb = new u8([
  0,
  0,
  0,
  0,
  1,
  1,
  2,
  2,
  3,
  3,
  4,
  4,
  5,
  5,
  6,
  6,
  7,
  7,
  8,
  8,
  9,
  9,
  10,
  10,
  11,
  11,
  12,
  12,
  13,
  13,
  /* unused */
  0,
  0
]);
var clim = new u8([16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]);
var freb = function(eb, start) {
  var b = new u16(31);
  for (var i = 0; i < 31; ++i) {
    b[i] = start += 1 << eb[i - 1];
  }
  var r = new i32(b[30]);
  for (var i = 1; i < 30; ++i) {
    for (var j = b[i]; j < b[i + 1]; ++j) {
      r[j] = j - b[i] << 5 | i;
    }
  }
  return { b, r };
};
var _a = freb(fleb, 2);
var fl = _a.b;
var revfl = _a.r;
fl[28] = 258, revfl[258] = 28;
var _b = freb(fdeb, 0);
var fd = _b.b;
var revfd = _b.r;
var rev = new u16(32768);
for (i = 0; i < 32768; ++i) {
  x = (i & 43690) >> 1 | (i & 21845) << 1;
  x = (x & 52428) >> 2 | (x & 13107) << 2;
  x = (x & 61680) >> 4 | (x & 3855) << 4;
  rev[i] = ((x & 65280) >> 8 | (x & 255) << 8) >> 1;
}
var x;
var i;
var hMap = function(cd, mb, r) {
  var s = cd.length;
  var i = 0;
  var l = new u16(mb);
  for (; i < s; ++i) {
    if (cd[i])
      ++l[cd[i] - 1];
  }
  var le = new u16(mb);
  for (i = 1; i < mb; ++i) {
    le[i] = le[i - 1] + l[i - 1] << 1;
  }
  var co;
  if (r) {
    co = new u16(1 << mb);
    var rvb = 15 - mb;
    for (i = 0; i < s; ++i) {
      if (cd[i]) {
        var sv = i << 4 | cd[i];
        var r_1 = mb - cd[i];
        var v = le[cd[i] - 1]++ << r_1;
        for (var m = v | (1 << r_1) - 1; v <= m; ++v) {
          co[rev[v] >> rvb] = sv;
        }
      }
    }
  } else {
    co = new u16(s);
    for (i = 0; i < s; ++i) {
      if (cd[i]) {
        co[i] = rev[le[cd[i] - 1]++] >> 15 - cd[i];
      }
    }
  }
  return co;
};
var flt = new u8(288);
for (i = 0; i < 144; ++i)
  flt[i] = 8;
var i;
for (i = 144; i < 256; ++i)
  flt[i] = 9;
var i;
for (i = 256; i < 280; ++i)
  flt[i] = 7;
var i;
for (i = 280; i < 288; ++i)
  flt[i] = 8;
var i;
var fdt = new u8(32);
for (i = 0; i < 32; ++i)
  fdt[i] = 5;
var i;
var flrm = /* @__PURE__ */ hMap(flt, 9, 1);
var fdrm = /* @__PURE__ */ hMap(fdt, 5, 1);
var max = function(a) {
  var m = a[0];
  for (var i = 1; i < a.length; ++i) {
    if (a[i] > m)
      m = a[i];
  }
  return m;
};
var bits = function(d, p, m) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8) >> (p & 7) & m;
};
var bits16 = function(d, p) {
  var o = p / 8 | 0;
  return (d[o] | d[o + 1] << 8 | d[o + 2] << 16) >> (p & 7);
};
var shft = function(p) {
  return (p + 7) / 8 | 0;
};
var slc = function(v, s, e) {
  if (s == null || s < 0)
    s = 0;
  if (e == null || e > v.length)
    e = v.length;
  return new u8(v.subarray(s, e));
};
var ec = [
  "unexpected EOF",
  "invalid block type",
  "invalid length/literal",
  "invalid distance",
  "stream finished",
  "no stream handler",
  ,
  "no callback",
  "invalid UTF-8 data",
  "extra field too long",
  "date not in range 1980-2099",
  "filename too long",
  "stream finishing",
  "invalid zip data"
  // determined by unknown compression method
];
var err = function(ind, msg, nt) {
  var e = new Error(msg || ec[ind]);
  e.code = ind;
  if (Error.captureStackTrace)
    Error.captureStackTrace(e, err);
  if (!nt)
    throw e;
  return e;
};
var inflt = function(dat, st, buf, dict) {
  var sl = dat.length, dl = dict ? dict.length : 0;
  if (!sl || st.f && !st.l)
    return buf || new u8(0);
  var noBuf = !buf;
  var resize = noBuf || st.i != 2;
  var noSt = st.i;
  if (noBuf)
    buf = new u8(sl * 3);
  var cbuf = function(l2) {
    var bl = buf.length;
    if (l2 > bl) {
      var nbuf = new u8(Math.max(bl * 2, l2));
      nbuf.set(buf);
      buf = nbuf;
    }
  };
  var final = st.f || 0, pos = st.p || 0, bt = st.b || 0, lm = st.l, dm = st.d, lbt = st.m, dbt = st.n;
  var tbts = sl * 8;
  do {
    if (!lm) {
      final = bits(dat, pos, 1);
      var type = bits(dat, pos + 1, 3);
      pos += 3;
      if (!type) {
        var s = shft(pos) + 4, l = dat[s - 4] | dat[s - 3] << 8, t = s + l;
        if (t > sl) {
          if (noSt)
            err(0);
          break;
        }
        if (resize)
          cbuf(bt + l);
        buf.set(dat.subarray(s, t), bt);
        st.b = bt += l, st.p = pos = t * 8, st.f = final;
        continue;
      } else if (type == 1)
        lm = flrm, dm = fdrm, lbt = 9, dbt = 5;
      else if (type == 2) {
        var hLit = bits(dat, pos, 31) + 257, hcLen = bits(dat, pos + 10, 15) + 4;
        var tl = hLit + bits(dat, pos + 5, 31) + 1;
        pos += 14;
        var ldt = new u8(tl);
        var clt = new u8(19);
        for (var i = 0; i < hcLen; ++i) {
          clt[clim[i]] = bits(dat, pos + i * 3, 7);
        }
        pos += hcLen * 3;
        var clb = max(clt), clbmsk = (1 << clb) - 1;
        var clm = hMap(clt, clb, 1);
        for (var i = 0; i < tl; ) {
          var r = clm[bits(dat, pos, clbmsk)];
          pos += r & 15;
          var s = r >> 4;
          if (s < 16) {
            ldt[i++] = s;
          } else {
            var c = 0, n = 0;
            if (s == 16)
              n = 3 + bits(dat, pos, 3), pos += 2, c = ldt[i - 1];
            else if (s == 17)
              n = 3 + bits(dat, pos, 7), pos += 3;
            else if (s == 18)
              n = 11 + bits(dat, pos, 127), pos += 7;
            while (n--)
              ldt[i++] = c;
          }
        }
        var lt = ldt.subarray(0, hLit), dt = ldt.subarray(hLit);
        lbt = max(lt);
        dbt = max(dt);
        lm = hMap(lt, lbt, 1);
        dm = hMap(dt, dbt, 1);
      } else
        err(1);
      if (pos > tbts) {
        if (noSt)
          err(0);
        break;
      }
    }
    if (resize)
      cbuf(bt + 131072);
    var lms = (1 << lbt) - 1, dms = (1 << dbt) - 1;
    var lpos = pos;
    for (; ; lpos = pos) {
      var c = lm[bits16(dat, pos) & lms], sym = c >> 4;
      pos += c & 15;
      if (pos > tbts) {
        if (noSt)
          err(0);
        break;
      }
      if (!c)
        err(2);
      if (sym < 256)
        buf[bt++] = sym;
      else if (sym == 256) {
        lpos = pos, lm = null;
        break;
      } else {
        var add = sym - 254;
        if (sym > 264) {
          var i = sym - 257, b = fleb[i];
          add = bits(dat, pos, (1 << b) - 1) + fl[i];
          pos += b;
        }
        var d = dm[bits16(dat, pos) & dms], dsym = d >> 4;
        if (!d)
          err(3);
        pos += d & 15;
        var dt = fd[dsym];
        if (dsym > 3) {
          var b = fdeb[dsym];
          dt += bits16(dat, pos) & (1 << b) - 1, pos += b;
        }
        if (pos > tbts) {
          if (noSt)
            err(0);
          break;
        }
        if (resize)
          cbuf(bt + 131072);
        var end = bt + add;
        if (bt < dt) {
          var shift = dl - dt, dend = Math.min(dt, end);
          if (shift + bt < 0)
            err(3);
          for (; bt < dend; ++bt)
            buf[bt] = dict[shift + bt];
        }
        for (; bt < end; ++bt)
          buf[bt] = buf[bt - dt];
      }
    }
    st.l = lm, st.p = lpos, st.b = bt, st.f = final;
    if (lm)
      final = 1, st.m = lbt, st.d = dm, st.n = dbt;
  } while (!final);
  return bt != buf.length && noBuf ? slc(buf, 0, bt) : buf.subarray(0, bt);
};
var et = /* @__PURE__ */ new u8(0);
var gzs = function(d) {
  if (d[0] != 31 || d[1] != 139 || d[2] != 8)
    err(6, "invalid gzip data");
  var flg = d[3];
  var st = 10;
  if (flg & 4)
    st += (d[10] | d[11] << 8) + 2;
  for (var zs = (flg >> 3 & 1) + (flg >> 4 & 1); zs > 0; zs -= !d[st++])
    ;
  return st + (flg & 2);
};
var gzl = function(d) {
  var l = d.length;
  return (d[l - 4] | d[l - 3] << 8 | d[l - 2] << 16 | d[l - 1] << 24) >>> 0;
};
var zls = function(d, dict) {
  if ((d[0] & 15) != 8 || d[0] >> 4 > 7 || (d[0] << 8 | d[1]) % 31)
    err(6, "invalid zlib data");
  if ((d[1] >> 5 & 1) == +!dict)
    err(6, "invalid zlib data: " + (d[1] & 32 ? "need" : "unexpected") + " dictionary");
  return (d[1] >> 3 & 4) + 2;
};
function inflateSync(data, opts) {
  return inflt(data, { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
function gunzipSync(data, opts) {
  var st = gzs(data);
  if (st + 8 > data.length)
    err(6, "invalid gzip data");
  return inflt(data.subarray(st, -8), { i: 2 }, opts && opts.out || new u8(gzl(data)), opts && opts.dictionary);
}
function unzlibSync(data, opts) {
  return inflt(data.subarray(zls(data, opts && opts.dictionary), -4), { i: 2 }, opts && opts.out, opts && opts.dictionary);
}
function decompressSync(data, opts) {
  return data[0] == 31 && data[1] == 139 && data[2] == 8 ? gunzipSync(data, opts) : (data[0] & 15) != 8 || data[0] >> 4 > 7 || (data[0] << 8 | data[1]) % 31 ? inflateSync(data, opts) : unzlibSync(data, opts);
}
var td = typeof TextDecoder != "undefined" && /* @__PURE__ */ new TextDecoder();
var tds = 0;
try {
  td.decode(et, { stream: true });
  tds = 1;
} catch (e) {
}

// src/main.ts
var DEFAULT_SETTINGS = {
  format: "image",
  noFill: true,
  fill: "#ffffff",
  pixel_per_pt: 3,
  search_system: false,
  override_math: false,
  font_families: [],
  preamable: {
    shared: "#set text(fill: white, size: SIZE)\n#set page(width: WIDTH, height: HEIGHT)",
    math: "#set page(margin: 0pt)\n#set align(horizon)",
    code: "#set page(margin: (y: 1em, x: 0pt))"
  },
  plugin_version: "0.10.0",
  autoDownloadPackages: true
};
var TypstPlugin = class extends import_obsidian.Plugin {
  constructor() {
    super(...arguments);
    this.prevCanvasHeight = 0;
  }
  async onload() {
    console.log("loading Typst Renderer");
    this.textEncoder = new TextEncoder();
    await this.loadSettings();
    this.pluginPath = this.app.vault.configDir + "/plugins/typst/";
    this.packagePath = this.pluginPath + "packages/";
    this.wasmPath = this.pluginPath + "obsidian_typst_bg.wasm";
    this.compilerWorker = new inlineWorker();
    if (!await this.app.vault.adapter.exists(this.wasmPath) || this.settings.plugin_version != "0.10.0") {
      new import_obsidian.Notice("Typst Renderer: Downloading required web assembly component!", 5e3);
      try {
        await this.fetchWasm();
        new import_obsidian.Notice("Typst Renderer: Web assembly component downloaded!", 5e3);
      } catch (error) {
        new import_obsidian.Notice("Typst Renderer: Failed to fetch component: " + error, 0);
        console.error("Typst Renderer: Failed to fetch component: " + error);
      }
    }
    this.compilerWorker.postMessage({
      type: "startup",
      data: {
        wasm: URL.createObjectURL(
          new Blob(
            [await this.app.vault.adapter.readBinary(this.wasmPath)],
            { type: "application/wasm" }
          )
        ),
        //@ts-ignore
        basePath: this.app.vault.adapter.basePath,
        packagePath: this.packagePath
      }
    });
    if (import_obsidian.Platform.isDesktopApp) {
      this.compilerWorker.postMessage({ type: "canUseSharedArrayBuffer", data: true });
      this.fs = require("fs");
      let fonts = await Promise.all(
        //@ts-expect-error
        (await window.queryLocalFonts()).filter((font) => this.settings.font_families.contains(font.family.toLowerCase())).map(
          async (font) => await (await font.blob()).arrayBuffer()
        )
      );
      this.compilerWorker.postMessage({ type: "fonts", data: fonts }, fonts);
    } else {
      await this.app.vault.adapter.mkdir(this.packagePath);
      const packages = await this.getPackageList();
      this.compilerWorker.postMessage({ type: "packages", data: packages });
    }
    TypstRenderElement.compile = (a, b, c, d, e) => this.processThenCompileTypst(a, b, c, d, e);
    if (customElements.get("typst-renderer") == void 0) {
      customElements.define("typst-renderer", TypstRenderElement);
    }
    await (0, import_obsidian.loadMathJax)();
    (0, import_obsidian.renderMath)("", false);
    this.tex2chtml = MathJax.tex2chtml;
    this.overrideMathJax(this.settings.override_math);
    this.addCommand({
      id: "toggle-math-override",
      name: "Toggle math block override",
      callback: () => this.overrideMathJax(!this.settings.override_math)
    });
    this.addSettingTab(new TypstSettingTab(this.app, this));
    this.registerMarkdownCodeBlockProcessor("typst", async (source, el, ctx) => {
      el.appendChild(this.createTypstRenderElement("/" + ctx.sourcePath, `${this.settings.preamable.code}
${source}`, true, false));
    });
    console.log("loaded Typst Renderer");
  }
  async fetchWasm() {
    let response;
    let data;
    response = (0, import_obsidian.requestUrl)(`https://api.github.com/repos/fenjalien/obsidian-typst/releases/tags/${"0.10.0"}`);
    data = await response.json;
    let asset = data.assets.find((a) => a.name == "obsidian_typst_bg.wasm");
    if (asset == void 0) {
      throw "Could not find the correct file!";
    }
    response = (0, import_obsidian.requestUrl)({ url: asset.url, headers: { "Accept": "application/octet-stream" } });
    data = await response.arrayBuffer;
    await this.app.vault.adapter.writeBinary(
      this.wasmPath,
      data
    );
    this.settings.plugin_version = "0.10.0";
    await this.saveSettings();
  }
  async getPackageList() {
    let getFolders = async (f) => (await this.app.vault.adapter.list(f)).folders;
    let packages = [];
    for (const namespace of await getFolders(this.packagePath)) {
      for (const name of await getFolders(namespace)) {
        for (const version of await getFolders(name)) {
          packages.push(version.split("/").slice(-3).join("/"));
        }
      }
    }
    return packages;
  }
  async deletePackages(packages) {
    for (const folder of packages) {
      await this.app.vault.adapter.rmdir(this.packagePath + folder, true);
    }
  }
  async compileToTypst(path, source, size, display) {
    return await navigator.locks.request("typst renderer compiler", async (lock) => {
      let message;
      if (this.settings.format == "svg") {
        message = {
          type: "compile",
          data: {
            format: "svg",
            path,
            source
          }
        };
      } else if (this.settings.format == "image") {
        message = {
          type: "compile",
          data: {
            format: "image",
            source,
            path,
            pixel_per_pt: this.settings.pixel_per_pt,
            fill: `${this.settings.fill}${this.settings.noFill ? "00" : "ff"}`,
            size,
            display
          }
        };
      }
      this.compilerWorker.postMessage(message);
      while (true) {
        let result;
        try {
          result = await new Promise((resolve, reject) => {
            const listener = (ev) => {
              remove();
              resolve(ev.data);
            };
            const errorListener = (error) => {
              remove();
              reject(error.message);
            };
            const remove = () => {
              this.compilerWorker.removeEventListener("message", listener);
              this.compilerWorker.removeEventListener("error", errorListener);
            };
            this.compilerWorker.addEventListener("message", listener);
            this.compilerWorker.addEventListener("error", errorListener);
          });
        } catch (e) {
          if (import_obsidian.Platform.isMobileApp && e.startsWith("Uncaught Error: package not found (searched for")) {
            const spec = e.match(/"@preview\/.*?"/)[0].slice(2, -1).replace(":", "/");
            const [namespace, name, version] = spec.split("/");
            try {
              await this.fetchPackage(this.packagePath + spec + "/", name, version);
            } catch (error) {
              if (error == 2) {
                throw e;
              }
              throw error;
            }
            const packages = await this.getPackageList();
            this.compilerWorker.postMessage({ type: "packages", data: packages });
            this.compilerWorker.postMessage(message);
            continue;
          }
          throw e;
        }
        if (result instanceof ImageData || typeof result == "string") {
          return result;
        }
        await this.handleWorkerRequest(result);
      }
    });
  }
  async handleWorkerRequest({ buffer: wbuffer, path }) {
    try {
      const text = await (path.startsWith("@") ? this.preparePackage(path.slice(1)) : this.getFileString(path));
      if (text) {
        let buffer = Int32Array.from(this.textEncoder.encode(
          text
        ));
        if (wbuffer.byteLength < buffer.byteLength + 4) {
          wbuffer.buffer.grow(buffer.byteLength + 4);
        }
        wbuffer.set(buffer, 1);
        wbuffer[0] = 0;
      }
    } catch (error) {
      if (typeof error === "number") {
        wbuffer[0] = error;
      } else {
        wbuffer[0] = 1;
        console.error(error);
      }
    } finally {
      Atomics.notify(wbuffer, 0);
    }
  }
  async getFileString(path) {
    try {
      if (require("path").isAbsolute(path)) {
        return await this.fs.promises.readFile(path, { encoding: "utf8" });
      } else {
        return await this.app.vault.adapter.read((0, import_obsidian.normalizePath)(path));
      }
    } catch (e) {
      console.error(e);
      if (e.code == "ENOENT") {
        throw 2;
      }
      if (e.code == "EACCES") {
        throw 3;
      }
      if (e.code == "EISDIR") {
        throw 4;
      }
      throw 5;
    }
  }
  async preparePackage(spec) {
    if (import_obsidian.Platform.isDesktopApp) {
      let subdir = "/typst/packages/" + spec;
      let dir = require("path").normalize(this.getDataDir() + subdir);
      if (this.fs.existsSync(dir)) {
        return dir;
      }
      dir = require("path").normalize(this.getCacheDir() + subdir);
      if (this.fs.existsSync(dir)) {
        return dir;
      }
    }
    const folder = this.packagePath + spec + "/";
    if (await this.app.vault.adapter.exists(folder)) {
      return folder;
    }
    if (spec.startsWith("preview") && this.settings.autoDownloadPackages) {
      const [namespace, name, version] = spec.split("/");
      try {
        await this.fetchPackage(folder, name, version);
        return folder;
      } catch (e) {
        if (e == 2) {
          throw e;
        }
        console.error(e);
        throw 3;
      }
    }
    throw 2;
  }
  getDataDir() {
    if (import_obsidian.Platform.isLinux) {
      if ("XDG_DATA_HOME" in process.env) {
        return process.env["XDG_DATA_HOME"];
      } else {
        return process.env["HOME"] + "/.local/share";
      }
    } else if (import_obsidian.Platform.isWin) {
      return process.env["APPDATA"];
    } else if (import_obsidian.Platform.isMacOS) {
      return process.env["HOME"] + "/Library/Application Support";
    }
    throw "Cannot find data directory on an unknown platform";
  }
  getCacheDir() {
    if (import_obsidian.Platform.isLinux) {
      if ("XDG_CACHE_HOME" in process.env) {
        return process.env["XDG_DATA_HOME"];
      } else {
        return process.env["HOME"] + "/.cache";
      }
    } else if (import_obsidian.Platform.isWin) {
      return process.env["LOCALAPPDATA"];
    } else if (import_obsidian.Platform.isMacOS) {
      return process.env["HOME"] + "/Library/Caches";
    }
    throw "Cannot find cache directory on an unknown platform";
  }
  async fetchPackage(folder, name, version) {
    const url = `https://packages.typst.org/preview/${name}-${version}.tar.gz`;
    const response = await fetch(url);
    if (response.status == 404) {
      throw 2;
    }
    await this.app.vault.adapter.mkdir(folder);
    await (0, import_js_untar.default)(decompressSync(new Uint8Array(await response.arrayBuffer())).buffer).progress(async (file) => {
      if (file.type == "5" && file.name != ".") {
        await this.app.vault.adapter.mkdir(folder + file.name);
      }
      if (file.type === "0") {
        await this.app.vault.adapter.writeBinary(folder + file.name, file.buffer);
      }
    });
  }
  async processThenCompileTypst(path, source, size, display, fontSize) {
    const dpr = window.devicePixelRatio;
    const pxToPt = (px) => px.toString() + "pt";
    const sizing = `#let (WIDTH, HEIGHT, SIZE, THEME) = (${display ? pxToPt(size) : "auto"}, ${!display ? pxToPt(size) : "auto"}, ${pxToPt(fontSize)}, "${document.body.getCssPropertyValue("color-scheme")}")`;
    return this.compileToTypst(
      path,
      `${sizing}
${this.settings.preamable.shared}
${source}`,
      size,
      display
    );
  }
  createTypstRenderElement(path, source, display, math) {
    let renderer = new TypstRenderElement();
    renderer.format = this.settings.format;
    renderer.source = source;
    renderer.path = path;
    renderer.display = display;
    renderer.math = math;
    return renderer;
  }
  createTypstMath(source, r) {
    const display = r.display;
    source = `${this.settings.preamable.math}
${display ? `$ ${source} $` : `$${source}$`}`;
    return this.createTypstRenderElement("/586f8912-f3a8-4455-8a4a-3729469c2cc1.typ", source, display, true);
  }
  onunload() {
    MathJax.tex2chtml = this.tex2chtml;
    this.compilerWorker.terminate();
  }
  async overrideMathJax(value) {
    this.settings.override_math = value;
    await this.saveSettings();
    if (this.settings.override_math) {
      MathJax.tex2chtml = (e, r) => this.createTypstMath(e, r);
    } else {
      MathJax.tex2chtml = this.tex2chtml;
    }
  }
  async loadSettings() {
    this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
  }
  async saveSettings() {
    await this.saveData(this.settings);
  }
};
var TypstSettingTab = class extends import_obsidian.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.plugin = plugin;
  }
  async display() {
    const { containerEl } = this;
    containerEl.empty();
    new import_obsidian.Setting(containerEl).setName("Render Format").addDropdown((dropdown) => {
      dropdown.addOptions({
        svg: "SVG",
        image: "Image"
      }).setValue(this.plugin.settings.format).onChange(async (value) => {
        this.plugin.settings.format = value;
        await this.plugin.saveSettings();
        if (value == "svg") {
          no_fill.setDisabled(true);
          fill_color.setDisabled(true);
          pixel_per_pt.setDisabled(true);
        } else {
          no_fill.setDisabled(false);
          fill_color.setDisabled(this.plugin.settings.noFill);
          pixel_per_pt.setDisabled(false);
        }
      });
    });
    let no_fill = new import_obsidian.Setting(containerEl).setName("No Fill (Transparent)").setDisabled(this.plugin.settings.format == "svg").addToggle((toggle) => {
      toggle.setValue(this.plugin.settings.noFill).onChange(
        async (value) => {
          this.plugin.settings.noFill = value;
          await this.plugin.saveSettings();
          fill_color.setDisabled(value);
        }
      );
    });
    let fill_color = new import_obsidian.Setting(containerEl).setName("Fill Color").setDisabled(this.plugin.settings.noFill || this.plugin.settings.format == "svg").addColorPicker((picker) => {
      picker.setValue(this.plugin.settings.fill).onChange(
        async (value) => {
          this.plugin.settings.fill = value;
          await this.plugin.saveSettings();
        }
      );
    });
    let pixel_per_pt = new import_obsidian.Setting(containerEl).setName("Pixel Per Point").setDisabled(this.plugin.settings.format == "svg").addSlider(
      (slider) => slider.setValue(this.plugin.settings.pixel_per_pt).setLimits(1, 5, 1).onChange(
        async (value) => {
          this.plugin.settings.pixel_per_pt = value;
          await this.plugin.saveSettings();
        }
      ).setDynamicTooltip()
    );
    new import_obsidian.Setting(containerEl).setName("Override Math Blocks").addToggle((toggle) => {
      toggle.setValue(this.plugin.settings.override_math).onChange((value) => this.plugin.overrideMathJax(value));
    });
    new import_obsidian.Setting(containerEl).setName("Shared Preamble").addTextArea((c) => c.setValue(this.plugin.settings.preamable.shared).onChange(async (value) => {
      this.plugin.settings.preamable.shared = value;
      await this.plugin.saveSettings();
    }));
    new import_obsidian.Setting(containerEl).setName("Code Block Preamble").addTextArea((c) => c.setValue(this.plugin.settings.preamable.code).onChange(async (value) => {
      this.plugin.settings.preamable.code = value;
      await this.plugin.saveSettings();
    }));
    new import_obsidian.Setting(containerEl).setName("Math Block Preamble").addTextArea((c) => c.setValue(this.plugin.settings.preamable.math).onChange(async (value) => {
      this.plugin.settings.preamable.math = value;
      await this.plugin.saveSettings();
    }));
    if (!import_obsidian.Platform.isMobileApp) {
      const fontSettings = containerEl.createDiv({ cls: "setting-item font-settings" });
      fontSettings.createDiv({ text: "Fonts", cls: "setting-item-name" });
      fontSettings.createDiv({ text: "Font family names that should be loaded for Typst from your system. Requires a reload on change.", cls: "setting-item-description" });
      const addFontsDiv = fontSettings.createDiv({ cls: "add-fonts-div" });
      const fontsInput = addFontsDiv.createEl("input", { type: "text", placeholder: "Enter a font family", cls: "font-input" });
      const addFontBtn = addFontsDiv.createEl("button", { text: "Add" });
      const fontTagsDiv = fontSettings.createDiv({ cls: "font-tags-div" });
      const addFontTag = async () => {
        if (!this.plugin.settings.font_families.contains(fontsInput.value)) {
          this.plugin.settings.font_families.push(fontsInput.value.toLowerCase());
          await this.plugin.saveSettings();
        }
        fontsInput.value = "";
        this.renderFontTags(fontTagsDiv);
      };
      fontsInput.addEventListener("keydown", async (ev) => {
        if (ev.key == "Enter") {
          addFontTag();
        }
      });
      addFontBtn.addEventListener("click", async () => addFontTag());
      this.renderFontTags(fontTagsDiv);
      new import_obsidian.Setting(containerEl).setName("Download Missing Packages").setDesc("When on, if the compiler cannot find a package in the system it will attempt to download it. Packages downloaded this way will be stored within the vault in the plugin's folder. Always on for mobile.").addToggle((toggle) => toggle.setValue(this.plugin.settings.autoDownloadPackages).onChange(async (value) => {
        this.plugin.settings.autoDownloadPackages = value;
        await this.plugin.saveSettings();
      }));
    }
    const packageSettingsDiv = containerEl.createDiv({ cls: "setting-item package-settings" });
    packageSettingsDiv.createDiv({ text: "Downloaded Packages", cls: "setting-item-name" });
    packageSettingsDiv.createDiv({ text: "These are the currently downloaded packages. Select the packages you want to delete.", cls: "setting-item-description" });
    (await this.plugin.getPackageList()).forEach((pkg) => {
      const [namespace, name, version] = pkg.split("/");
      const packageItem = packageSettingsDiv.createDiv({ cls: "package-item" });
      packageItem.createEl("input", { type: "checkbox", cls: "package-checkbox", value: pkg, attr: { name: "package-checkbox" } });
      packageItem.createEl("p", { text: name });
      packageItem.createEl("p", { text: version, cls: "package-version" });
    });
    const deletePackagesBtn = packageSettingsDiv.createEl("button", { text: "Delete Selected Packages", cls: "delete-pkg-btn" });
    deletePackagesBtn.addEventListener("click", () => {
      const selectedPackageElements = packageSettingsDiv.querySelectorAll('input[name="package-checkbox"]:checked');
      let packagesToDelete = [];
      selectedPackageElements.forEach((pkgEl) => {
        packagesToDelete.push(pkgEl.getAttribute("value"));
        packageSettingsDiv.removeChild(pkgEl.parentNode);
      });
      this.plugin.deletePackages(packagesToDelete);
    });
  }
  renderFontTags(fontTagsDiv) {
    fontTagsDiv.innerHTML = "";
    this.plugin.settings.font_families.forEach((fontFamily) => {
      const fontTag = fontTagsDiv.createEl("span", { cls: "font-tag" });
      fontTag.createEl("span", { text: fontFamily, cls: "font-tag-text", attr: { style: `font-family: ${fontFamily};` } });
      const removeBtn = fontTag.createEl("span", { text: "x", cls: "tag-btn" });
      removeBtn.addEventListener("click", async () => {
        this.plugin.settings.font_families.remove(fontFamily);
        await this.plugin.saveSettings();
        this.renderFontTags(fontTagsDiv);
      });
    });
  }
};

/* nosourcemap */