@jant/core 0.6.10 → 0.6.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/dist/{app-CGHkOdme.js → app-CpmficmQ.js} +531 -204
  2. package/dist/app-DqKkZenB.js +6 -0
  3. package/dist/client/.vite/manifest.json +3 -3
  4. package/dist/client/_assets/client-BhHHVvSY.css +2 -0
  5. package/dist/client/_assets/{client-DYrWuaIk.js → client-Dd9U383b.js} +1 -1
  6. package/dist/client/_assets/{client-auth-B5Re0uCd.js → client-auth-DkpSdIDz.js} +80 -80
  7. package/dist/{export-DY1v5Iqu.js → export-Ba7NJImL.js} +92 -92
  8. package/dist/{github-sync-LefaslGJ.js → github-sync-BD4w2m8-.js} +2 -2
  9. package/dist/{github-sync-2_T7nbOv.js → github-sync-Cb4_6_i7.js} +1 -1
  10. package/dist/index.js +3 -3
  11. package/dist/node.js +4 -4
  12. package/package.json +1 -1
  13. package/src/client/components/__tests__/jant-compose-editor-rehost-notice.test.ts +62 -0
  14. package/src/client/components/compose-types.ts +4 -0
  15. package/src/client/components/jant-compose-editor.ts +111 -0
  16. package/src/client/compose-bridge.ts +25 -8
  17. package/src/client/tiptap/__tests__/inline-image-upload.test.ts +143 -0
  18. package/src/client/tiptap/__tests__/paste-rehost-e2e.test.ts +65 -0
  19. package/src/client/tiptap/__tests__/rehost-images.test.ts +139 -0
  20. package/src/client/tiptap/create-editor.ts +3 -0
  21. package/src/client/tiptap/extensions.ts +4 -0
  22. package/src/client/tiptap/inline-image-upload.ts +174 -50
  23. package/src/client/tiptap/rehost-images.ts +104 -0
  24. package/src/i18n/locales/public/en.po +10 -0
  25. package/src/i18n/locales/public/en.ts +1 -1
  26. package/src/i18n/locales/public/zh-Hans.po +10 -0
  27. package/src/i18n/locales/public/zh-Hans.ts +1 -1
  28. package/src/i18n/locales/public/zh-Hant.po +10 -0
  29. package/src/i18n/locales/public/zh-Hant.ts +1 -1
  30. package/src/lib/__tests__/upload-sideload.test.ts +78 -0
  31. package/src/lib/__tests__/url-fetch.test.ts +181 -0
  32. package/src/lib/upload.ts +111 -0
  33. package/src/lib/url-fetch.ts +263 -0
  34. package/src/routes/api/__tests__/uploads.test.ts +63 -1
  35. package/src/routes/api/uploads.ts +52 -0
  36. package/src/services/__tests__/media.test.ts +168 -1
  37. package/src/services/media.ts +111 -0
  38. package/src/styles/ui.css +1 -1
  39. package/src/ui/compose/ComposeDialog.tsx +16 -0
  40. package/src/ui/layouts/BaseLayout.tsx +12 -0
  41. package/dist/app-D24n0DoH.js +0 -6
  42. package/dist/client/_assets/client-xWDl78yi.css +0 -2
@@ -1,4 +1,4 @@
1
- import{a as e,n as t,o as n,t as r}from"./chunks/url-pLre2DM_.js";import{_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,y as C}from"./client-DYrWuaIk.js";var ee={maxShortSide:1920,maxLongSide:8192,quality:.85,mimeType:`image/webp`};function te(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function ne(e,t,n){if(Math.max(e,t)>n.maxLongSide)return{passthrough:!0,width:e,height:t};let r=Math.min(e,t);if(r<=n.maxShortSide)return{passthrough:!1,width:e,height:t};let i=n.maxShortSide/r;return{passthrough:!1,width:Math.round(e*i),height:Math.round(t*i)}}async function re(e,t,n){let r=await new Promise((r,i)=>{e.toBlob(e=>e?r(e):i(Error(`Failed to create blob`)),t,n)});return t!==`image/png`&&r.type===`image/png`?new Promise((t,r)=>{e.toBlob(e=>e?t(e):r(Error(`Failed to create blob`)),`image/jpeg`,n)}):r}async function ie(e,t={}){let n={...ee,...t},r=await te(e),i=ne(r.width,r.height,n);if(i.passthrough)return{blob:e,width:i.width,height:i.height,processed:!1};let a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`);if(!o)throw Error(`Failed to get canvas context`);return o.drawImage(r,0,0,i.width,i.height),{blob:await re(a,n.mimeType,n.quality),width:i.width,height:i.height,processed:!0}}async function ae(e,t={}){let n=await ie(e,t);if(!n.processed)return{file:e,width:n.width,height:n.height};let r={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.blob.type]??`png`,i=`${e.name.replace(/\.[^.]+$/,``)}.${r}`;return{file:new File([n.blob],i,{type:n.blob.type}),width:n.width,height:n.height}}var oe={process:ie,processToFile:ae},se={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function ce(e){let t=e.length*16,n=6+t,r=new ArrayBuffer(6+t),i=new DataView(r);i.setUint16(0,0,!0),i.setUint16(2,1,!0),i.setUint16(4,e.length,!0);let a=[];for(let t=0;t<e.length;t++){let r=e[t],o=6+t*16;i.setUint8(o+0,r.size<256?r.size:0),i.setUint8(o+1,r.size<256?r.size:0),i.setUint8(o+2,0),i.setUint8(o+3,0),i.setUint16(o+4,1,!0),i.setUint16(o+6,32,!0),i.setUint32(o+8,r.png.byteLength,!0),i.setUint32(o+12,n,!0),n+=r.png.byteLength,a.push(r.png)}return new Blob([r,...a],{type:`image/x-icon`})}function le(e){return typeof e==`object`&&!!e}function w(e,t){if(!le(e))return;let n=e[t];return typeof n==`string`?n:void 0}function ue(e,t){if(!le(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}function de(e,t){if(!le(e))return;let n=e[t];return typeof n==`number`?n:void 0}async function fe(e){let t=await e.text();if(!t.trim())return{};try{let e=JSON.parse(t);return le(e)?e:{}}catch{throw Error(`Expected JSON (HTTP ${e.status}) but got: ${ge(t.trim(),200)}`)}}async function pe(e,t){let n;try{n=await e.text()}catch{return t}return he(n,t)}function me(e,t){return he(e,t)}function he(e,t){let n=e.trim();if(!n)return t;try{let e=JSON.parse(n);if(le(e)){let t=w(e,`error`);if(t)return t}}catch{}return ge(n,200)}function ge(e,t){return e.length>t?`${e.slice(0,t)}…`:e}var _e=180;function ve(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function ye(e,t){let n=document.createElement(`canvas`);n.width=t,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let i=Math.max(t/e.width,t/e.height),a=t/i,o=t/i,s=(e.width-a)/2,c=(e.height-o)/2;return r.drawImage(e,s,c,a,o,0,0,t,t),new Promise((e,t)=>{n.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}function be(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=_e&&t.height>=_e}async function xe(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await ve(t),i=t,a=t.name;if(t.type!==`image/svg+xml`){let e=await ye(r,512);i=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),a=i.name}let s=be(t,r)?Promise.resolve(t):ye(r,se.APPLE_TOUCH),[c,l,u]=await Promise.all([ye(r,16),ye(r,32),s]),[d,f]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),p=ce([{size:16,png:d},{size:32,png:f}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let m=new FormData;m.append(`file`,i,a),m.append(`favicon`,p,`favicon.ico`),m.append(`appleTouch`,u,`apple-touch-icon.png`);let h=await fetch(o(`/settings/avatar`),{method:`POST`,headers:{Accept:`application/json`},body:m});if(!h.ok){let t=e.dataset.textError||`Upload failed. Please try again.`;try{let e=await fe(h);t=w(e,`error`)??w(e,`message`)??t}catch{}throw Error(t)}let g=await fe(h),_=w(g,`status`),v=w(g,`url`);if(_===`redirect`&&v){window.location.href=v;return}window.location.href=o(`/settings/avatar?saved`)}catch(t){n&&(n.textContent=r),a(t instanceof Error&&t.message?t.message:e.dataset.textError||`Upload failed. Please try again.`,`error`)}e.value=``}function Se(){document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-avatar-upload]`);t?.files?.[0]&&(e.stopPropagation(),xe(t,t.files[0]))})}Se();var Ce=`default`,we=class extends _{static properties={_open:{state:!0},_title:{state:!0},_message:{state:!0},_confirmLabel:{state:!0},_cancelLabel:{state:!0},_tone:{state:!0}};#e=[];#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=Ce}disconnectedCallback(){super.disconnectedCallback();let e=this.#t;this.#t=null,e?.resolve(!1);for(let e of this.#e.splice(0))e.resolve(!1)}async confirm(e){return await new Promise(t=>{this.#e.push({...e,tone:e.tone??Ce,resolve:t}),this.#t||this.#n()})}async#n(){if(this.#t||this.#e.length===0)return;let e=this.#e.shift();if(!e)return;this.#t=e,this._title=e.title??``,this._message=e.message,this._confirmLabel=e.confirmLabel,this._cancelLabel=e.cancelLabel,this._tone=e.tone??Ce,this._open=!0,await this.updateComplete;let t=this.querySelector(`.confirm-dialog`);t&&(t.open||t.showModal(),t.querySelector(`.confirm-dialog-panel`)?.focus())}#r(e){let t=this.#t;if(!t)return;this.#t=null;let n=this.querySelector(`.confirm-dialog`);n?.open&&n.close(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=Ce,t.resolve(e),queueMicrotask(()=>void this.#n())}#i=e=>{e.preventDefault(),this.#r(!1)};#a=e=>{e.target===e.currentTarget&&this.#r(!1)};#o=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.#r(!1);return}let t=e.target,n=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLAnchorElement;e.key===`Enter`&&!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!n&&(e.preventDefault(),this.#r(!0))};#s(){if(this._title)return{title:this._title,message:this._message};let e=this._message.match(/^(.+?[??])\s+(.+)$/u);return e?{title:e[1],message:e[2]}:{title:this._message,message:``}}render(){if(!this._open)return m;let{title:e,message:t}=this.#s(),n=this._tone===`danger`?`btn-destructive`:`btn`;return u`
1
+ import{a as e,n as t,o as n,t as r}from"./chunks/url-pLre2DM_.js";import{_ as i,a,b as o,c as s,d as c,f as l,g as u,h as d,i as f,l as p,m,n as h,o as g,p as _,r as v,s as y,t as b,u as x,v as S,y as C}from"./client-Dd9U383b.js";var ee={maxShortSide:1920,maxLongSide:8192,quality:.85,mimeType:`image/webp`};function te(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function ne(e,t,n){if(Math.max(e,t)>n.maxLongSide)return{passthrough:!0,width:e,height:t};let r=Math.min(e,t);if(r<=n.maxShortSide)return{passthrough:!1,width:e,height:t};let i=n.maxShortSide/r;return{passthrough:!1,width:Math.round(e*i),height:Math.round(t*i)}}async function re(e,t,n){let r=await new Promise((r,i)=>{e.toBlob(e=>e?r(e):i(Error(`Failed to create blob`)),t,n)});return t!==`image/png`&&r.type===`image/png`?new Promise((t,r)=>{e.toBlob(e=>e?t(e):r(Error(`Failed to create blob`)),`image/jpeg`,n)}):r}async function ie(e,t={}){let n={...ee,...t},r=await te(e),i=ne(r.width,r.height,n);if(i.passthrough)return{blob:e,width:i.width,height:i.height,processed:!1};let a=document.createElement(`canvas`);a.width=i.width,a.height=i.height;let o=a.getContext(`2d`);if(!o)throw Error(`Failed to get canvas context`);return o.drawImage(r,0,0,i.width,i.height),{blob:await re(a,n.mimeType,n.quality),width:i.width,height:i.height,processed:!0}}async function ae(e,t={}){let n=await ie(e,t);if(!n.processed)return{file:e,width:n.width,height:n.height};let r={"image/webp":`webp`,"image/jpeg":`jpg`,"image/png":`png`}[n.blob.type]??`png`,i=`${e.name.replace(/\.[^.]+$/,``)}.${r}`;return{file:new File([n.blob],i,{type:n.blob.type}),width:n.width,height:n.height}}var oe={process:ie,processToFile:ae},se={ICO_16:16,ICO_32:32,APPLE_TOUCH:512};function ce(e){let t=e.length*16,n=6+t,r=new ArrayBuffer(6+t),i=new DataView(r);i.setUint16(0,0,!0),i.setUint16(2,1,!0),i.setUint16(4,e.length,!0);let a=[];for(let t=0;t<e.length;t++){let r=e[t],o=6+t*16;i.setUint8(o+0,r.size<256?r.size:0),i.setUint8(o+1,r.size<256?r.size:0),i.setUint8(o+2,0),i.setUint8(o+3,0),i.setUint16(o+4,1,!0),i.setUint16(o+6,32,!0),i.setUint32(o+8,r.png.byteLength,!0),i.setUint32(o+12,n,!0),n+=r.png.byteLength,a.push(r.png)}return new Blob([r,...a],{type:`image/x-icon`})}function le(e){return typeof e==`object`&&!!e}function w(e,t){if(!le(e))return;let n=e[t];return typeof n==`string`?n:void 0}function ue(e,t){if(!le(e))return;let n=e[t];return typeof n==`boolean`?n:void 0}function de(e,t){if(!le(e))return;let n=e[t];return typeof n==`number`?n:void 0}async function fe(e){let t=await e.text();if(!t.trim())return{};try{let e=JSON.parse(t);return le(e)?e:{}}catch{throw Error(`Expected JSON (HTTP ${e.status}) but got: ${ge(t.trim(),200)}`)}}async function pe(e,t){let n;try{n=await e.text()}catch{return t}return he(n,t)}function me(e,t){return he(e,t)}function he(e,t){let n=e.trim();if(!n)return t;try{let e=JSON.parse(n);if(le(e)){let t=w(e,`error`);if(t)return t}}catch{}return ge(n,200)}function ge(e,t){return e.length>t?`${e.slice(0,t)}…`:e}var _e=180;function ve(e){return new Promise((t,n)=>{let r=new Image;r.onload=()=>{URL.revokeObjectURL(r.src),t(r)},r.onerror=()=>n(Error(`Failed to load image`)),r.src=URL.createObjectURL(e)})}function ye(e,t){let n=document.createElement(`canvas`);n.width=t,n.height=t;let r=n.getContext(`2d`);if(!r)throw Error(`Failed to get canvas context`);r.imageSmoothingEnabled=!0,r.imageSmoothingQuality=`high`;let i=Math.max(t/e.width,t/e.height),a=t/i,o=t/i,s=(e.width-a)/2,c=(e.height-o)/2;return r.drawImage(e,s,c,a,o,0,0,t,t),new Promise((e,t)=>{n.toBlob(n=>{n?e(n):t(Error(`Failed to create PNG blob`))},`image/png`)})}function be(e,t){return e.type===`image/png`&&t.width===t.height&&t.width>=_e&&t.height>=_e}async function xe(e,t){let n=e.closest(`form`)?.querySelector(`label`),r=n?.textContent??``;try{n&&(n.textContent=e.dataset.textProcessing||`Processing...`);let r=await ve(t),i=t,a=t.name;if(t.type!==`image/svg+xml`){let e=await ye(r,512);i=new File([e],t.name.replace(/\.[^.]+$/,`.png`),{type:`image/png`}),a=i.name}let s=be(t,r)?Promise.resolve(t):ye(r,se.APPLE_TOUCH),[c,l,u]=await Promise.all([ye(r,16),ye(r,32),s]),[d,f]=await Promise.all([c.arrayBuffer(),l.arrayBuffer()]),p=ce([{size:16,png:d},{size:32,png:f}]);n&&(n.textContent=e.dataset.textUploading||`Uploading...`);let m=new FormData;m.append(`file`,i,a),m.append(`favicon`,p,`favicon.ico`),m.append(`appleTouch`,u,`apple-touch-icon.png`);let h=await fetch(o(`/settings/avatar`),{method:`POST`,headers:{Accept:`application/json`},body:m});if(!h.ok){let t=e.dataset.textError||`Upload failed. Please try again.`;try{let e=await fe(h);t=w(e,`error`)??w(e,`message`)??t}catch{}throw Error(t)}let g=await fe(h),_=w(g,`status`),v=w(g,`url`);if(_===`redirect`&&v){window.location.href=v;return}window.location.href=o(`/settings/avatar?saved`)}catch(t){n&&(n.textContent=r),a(t instanceof Error&&t.message?t.message:e.dataset.textError||`Upload failed. Please try again.`,`error`)}e.value=``}function Se(){document.addEventListener(`change`,e=>{let t=e.target.closest(`[data-avatar-upload]`);t?.files?.[0]&&(e.stopPropagation(),xe(t,t.files[0]))})}Se();var Ce=`default`,we=class extends _{static properties={_open:{state:!0},_title:{state:!0},_message:{state:!0},_confirmLabel:{state:!0},_cancelLabel:{state:!0},_tone:{state:!0}};#e=[];#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=Ce}disconnectedCallback(){super.disconnectedCallback();let e=this.#t;this.#t=null,e?.resolve(!1);for(let e of this.#e.splice(0))e.resolve(!1)}async confirm(e){return await new Promise(t=>{this.#e.push({...e,tone:e.tone??Ce,resolve:t}),this.#t||this.#n()})}async#n(){if(this.#t||this.#e.length===0)return;let e=this.#e.shift();if(!e)return;this.#t=e,this._title=e.title??``,this._message=e.message,this._confirmLabel=e.confirmLabel,this._cancelLabel=e.cancelLabel,this._tone=e.tone??Ce,this._open=!0,await this.updateComplete;let t=this.querySelector(`.confirm-dialog`);t&&(t.open||t.showModal(),t.querySelector(`.confirm-dialog-panel`)?.focus())}#r(e){let t=this.#t;if(!t)return;this.#t=null;let n=this.querySelector(`.confirm-dialog`);n?.open&&n.close(),this._open=!1,this._title=``,this._message=``,this._confirmLabel=``,this._cancelLabel=``,this._tone=Ce,t.resolve(e),queueMicrotask(()=>void this.#n())}#i=e=>{e.preventDefault(),this.#r(!1)};#a=e=>{e.target===e.currentTarget&&this.#r(!1)};#o=e=>{if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.#r(!1);return}let t=e.target,n=t instanceof HTMLButtonElement||t instanceof HTMLInputElement||t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement||t instanceof HTMLAnchorElement;e.key===`Enter`&&!e.defaultPrevented&&!e.metaKey&&!e.ctrlKey&&!e.altKey&&!e.shiftKey&&!n&&(e.preventDefault(),this.#r(!0))};#s(){if(this._title)return{title:this._title,message:this._message};let e=this._message.match(/^(.+?[??])\s+(.+)$/u);return e?{title:e[1],message:e[2]}:{title:this._message,message:``}}render(){if(!this._open)return m;let{title:e,message:t}=this.#s(),n=this._tone===`danger`?`btn-destructive`:`btn`;return u`
2
2
  <dialog
3
3
  class="dialog confirm-dialog"
4
4
  @cancel=${this.#i}
@@ -297,15 +297,15 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
297
297
  </section>`}).join(``);pC.innerHTML=`<div class="tiptap-slash-menu-scroll">
298
298
  ${n}
299
299
  </div>
300
- ${EC(wC())}`,pC.querySelectorAll(`.tiptap-slash-item`).forEach(e=>{e.addEventListener(`mousedown`,n=>{n.preventDefault(),t(parseInt(e.dataset.index??`0`,10))}),e.addEventListener(`mouseenter`,()=>{mC=parseInt(e.dataset.index??`0`,10),CC()})});let r=bC();r&&(r.scrollTop=0)}function kC(){yC&&=(document.removeEventListener(`mousedown`,yC,!0),null),pC?.remove(),pC=null,mC=0,hC=[],gC=null,_C=null,vC=null}function AC(e,t){if(!pC)return;pC.style.maxHeight=``;let n=WS(null),r=t?WS(t):n,i=GS({anchorRect:{left:e.left,right:e.left,top:e.top,bottom:e.bottom},containerRect:n,floatingWidth:pC.offsetWidth,floatingHeight:pC.offsetHeight,preferredPlacement:`bottom`,fallbackPlacement:`top`,align:`start`,gap:6});pC.style.left=`${i.left-r.left}px`,pC.style.top=`${i.top-r.top}px`,pC.style.maxHeight=i.maxHeight===null?``:`${i.maxHeight}px`}function jC(){yC=e=>{if(!(!pC||pC.contains(e.target))&&_C&&vC){let{state:e,view:t}=_C;t.dispatch(e.tr.delete(vC.from,vC.to))}},document.addEventListener(`mousedown`,yC,!0)}var MC=new Pr(`jantSlashTyping`);function NC(){return new j({key:MC,state:{init:()=>({docChanged:!1}),apply:e=>({docChanged:e.docChanged})}})}function PC({state:e,range:t}){let n=e.doc.resolve(t.to),r=n.parent,i=t.to-n.start();if(i>=r.content.size)return!0;let a=r.textBetween(i,i+1,` `,` `);return a?/\s/.test(a):!0}function FC({state:e,range:t,isActive:n}){return PC({state:e,range:t})?n?!0:MC.getState(e)?.docChanged??!1:!1}var IC=N.create({name:`slashCommands`,addOptions(){return{suggestion:{char:`/`,startOfLine:!1,allow:FC,items:({query:e,editor:t})=>{let n=fC(t),r=Zx(e);return r?n.map((e,t)=>({item:e,index:t,rank:Xx([e.label,e.description,...e.keywords],r)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):n},render:()=>{function e(e){let t=e.options.element;return t instanceof globalThis.Element?t:null}return{onStart:t=>{pC=xC(),mC=0,gC=t.command,_C=t.editor,vC=t.range,OC(t.items,e=>t.command({index:e})),document.dispatchEvent(new CustomEvent(`jant:slash-command-discovered`,{bubbles:!0}));let n=e(t.editor)?.closest(`dialog`)??null;(n??document.body).appendChild(pC);let r=t.clientRect?.();r&&AC(r,n),jC()},onUpdate:t=>{gC=t.command,vC=t.range,OC(t.items,e=>t.command({index:e}));let n=t.clientRect?.();n&&AC(n,e(t.editor)?.closest(`dialog`)??null)},onKeyDown:e=>{let{event:t,view:n,range:r}=e;return t.key===`ArrowDown`?(t.preventDefault(),hC.length===0?!0:(mC=(mC+1)%hC.length,CC(),!0)):t.key===`ArrowUp`?(t.preventDefault(),hC.length===0?!0:(mC=(mC-1+hC.length)%hC.length,CC(),!0)):t.key===`Enter`?(t.preventDefault(),hC.length===0||gC?.({index:mC}),!0):t.key===`Escape`?(t.stopPropagation(),t.preventDefault(),n.dispatch(n.state.tr.delete(r.from,r.to)),!0):!1},onExit:()=>{kC()}}},command:({editor:e,range:t,props:n})=>{let r=hC[n.index];r&&r.command(e,t)}}}},addProseMirrorPlugins(){return[NC(),VS({editor:this.editor,...this.options.suggestion})]}}),LC=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~`.split(``),RC=(e,t)=>{var n=``;for(let r=1;r<=t;r++){let i=Math.floor(e)/83**(t-r)%83;n+=LC[Math.floor(i)]}return n},zC=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},BC=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(t*12.92*255+.5):Math.trunc((1.055*t**.4166666666666667-.055)*255+.5)},VC=e=>e<0?-1:1,HC=(e,t)=>VC(e)*Math.abs(e)**+t,UC=class extends Error{constructor(e){super(e),this.name=`ValidationError`,this.message=e}},WC=4,GC=(e,t,n,r)=>{let i=0,a=0,o=0,s=t*WC;for(let c=0;c<t;c++){let t=WC*c;for(let l=0;l<n;l++){let n=t+l*s,u=r(c,l);i+=u*zC(e[n]),a+=u*zC(e[n+1]),o+=u*zC(e[n+2])}}let c=1/(t*n);return[i*c,a*c,o*c]},KC=e=>{let t=BC(e[0]),n=BC(e[1]),r=BC(e[2]);return(t<<16)+(n<<8)+r},qC=(e,t)=>{let n=Math.floor(Math.max(0,Math.min(18,Math.floor(HC(e[0]/t,.5)*9+9.5)))),r=Math.floor(Math.max(0,Math.min(18,Math.floor(HC(e[1]/t,.5)*9+9.5)))),i=Math.floor(Math.max(0,Math.min(18,Math.floor(HC(e[2]/t,.5)*9+9.5))));return n*19*19+r*19+i},JC=(e,t,n,r,i)=>{if(r<1||r>9||i<1||i>9)throw new UC(`BlurHash must have between 1 and 9 components`);if(t*n*4!==e.length)throw new UC(`Width and height must match the pixels array`);let a=[];for(let o=0;o<i;o++)for(let i=0;i<r;i++){let r=i==0&&o==0?1:2,s=GC(e,t,n,(e,a)=>r*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*o*a/n));a.push(s)}let o=a[0],s=a.slice(1),c=``,l=r-1+(i-1)*9;c+=RC(l,1);let u;if(s.length>0){let e=Math.max(...s.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(e*166-.5))));u=(t+1)/166,c+=RC(t,1)}else u=1,c+=RC(0,1);return c+=RC(KC(o),4),s.forEach(e=>{c+=RC(qC(e,u),2)}),c};async function YC(e){let t=await $C(e),{width:n,height:r}=t,i=Math.min(32/n,32/r,1),a=Math.max(Math.round(n*i),1),o=Math.max(Math.round(r*i),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);return c.drawImage(t,0,0,a,o),{width:n,height:r,blurhash:JC(c.getImageData(0,0,a,o).data,a,o,4,3)}}async function XC(e){let t=URL.createObjectURL(e);try{let e=document.createElement(`video`);e.muted=!0,e.preload=`auto`;let{width:n,height:r,duration:i}=await new Promise((n,r)=>{e.onloadedmetadata=()=>n({width:e.videoWidth,height:e.videoHeight,duration:e.duration}),e.onerror=()=>r(Error(`Failed to load video metadata`)),e.src=t}),a,o;try{let t=Math.min(i*.1,1),s=await Promise.race([ew(e,n,r,t),tw(8e3)]);a=s.blurhash,o=s.poster}catch{}return{width:n,height:r,blurhash:a,poster:o}}finally{URL.revokeObjectURL(t)}}async function ZC(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function QC(e){try{if(e.type.startsWith(`image/`))return await YC(e);if(e.type.startsWith(`video/`)){let t=await XC(e);return{width:t.width,height:t.height,blurhash:t.blurhash,poster:t.poster}}if(e.type.startsWith(`audio/`))return{waveform:await ZC(e)}}catch{}return{}}function $C(e){return new Promise((t,n)=>{let r=new Image,i=URL.createObjectURL(e);r.onload=()=>{URL.revokeObjectURL(i),t(r)},r.onerror=()=>{URL.revokeObjectURL(i),n(Error(`Failed to load image`))},r.src=i})}function ew(e,t,n,r){return new Promise((i,a)=>{e.currentTime=r,e.onseeked=()=>{try{let r=Math.min(32/t,32/n,1),a=Math.max(Math.round(t*r),1),o=Math.max(Math.round(n*r),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);c.drawImage(e,0,0,a,o);let l=JC(c.getImageData(0,0,a,o).data,a,o,4,3),u=Math.min(640/t,1),d=Math.round(t*u),f=Math.round(n*u),p=document.createElement(`canvas`);p.width=d,p.height=f;let m=p.getContext(`2d`);if(!m){i({blurhash:l});return}m.drawImage(e,0,0,d,f),p.toBlob(e=>{i({blurhash:l,poster:e??void 0})},`image/webp`,.8)}catch(e){a(e)}},e.onerror=()=>a(Error(`Video seek failed`))})}function tw(e){return new Promise((t,n)=>setTimeout(()=>n(Error(`Timeout`)),e))}function nw(e){if(!le(e))return null;let t=w(e,`kind`),n=w(e,`method`),r=w(e,`url`);if(!t||n!==`PUT`||!r)return null;if(t===`relay`)return{kind:t,method:`PUT`,url:r};if(t===`multipartRelay`){let n=de(e,`partSize`);return n?{kind:t,method:`PUT`,url:r,partSize:n}:null}if(t===`put`){let n=de(e,`expiresAt`),i=e.headers;if(!n||!le(i))return null;let a={};for(let[e,t]of Object.entries(i))typeof t==`string`&&(a[e]=t);return{kind:t,method:`PUT`,url:r,headers:a,expiresAt:n}}return null}function rw(e,t,n,r){return new Promise((i,a)=>{let o=new globalThis.XMLHttpRequest;o.open(`PUT`,e);for(let[e,t]of Object.entries(n))o.setRequestHeader(e,t);o.upload.addEventListener(`progress`,e=>{e.lengthComputable&&r&&r(e.loaded/e.total)}),o.addEventListener(`load`,()=>{i({status:o.status,ok:o.status>=200&&o.status<300,text:o.responseText})}),o.addEventListener(`error`,()=>a(Error(`Network error`))),o.addEventListener(`abort`,()=>a(Error(`Upload aborted`))),o.send(t)})}function iw(e){try{let t=JSON.parse(e);return le(t)?t:null}catch{return null}}async function aw(e){let t=await fetch(o(`/api/uploads/init`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({filename:e.name,contentType:e.type||`application/octet-stream`,size:e.size})});if(!t.ok)throw Error(await pe(t,`Failed to start upload`));let n=await fe(t),r=w(n,`id`),i=nw(n.transport);if(!r||!i)throw Error(`Failed to start upload`);return{id:r,transport:i}}async function ow(e,t){let n=await fetch(o(`/api/uploads/${e}/poster`),{method:`PUT`,headers:{"Content-Type":t.type||`image/webp`},body:t});if(!n.ok)throw Error(await pe(n,`Failed to upload poster`))}async function sw(e){await fetch(o(`/api/uploads/${e}/abort`),{method:`POST`}).catch(()=>{})}async function cw(e,t){let n=await fetch(o(`/api/uploads/${e}/complete`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok)throw Error(await pe(n,`Failed to complete upload`));let r=await fe(n),i=w(r,`id`),a=w(r,`filename`),s=w(r,`url`),c=w(r,`mimeType`),l=de(r,`size`);if(!i||!a||!s||!c||l===void 0)throw Error(`Failed to complete upload`);return{id:i,filename:a,url:s,mimeType:c,size:l}}async function lw(e,t,n,r){let i=Math.ceil(n.size/t.partSize),a=[],s=0;for(let e=0;e<i;e+=1){let i=e*t.partSize,c=Math.min(i+t.partSize,n.size),l=e+1,u=n.slice(i,c),d=c-i,f=await rw(o(`${t.url}?partNumber=${l}`),u,{},e=>{r?.((s+d*e)/n.size)});if(!f.ok)throw Error(me(f.text,`Failed to upload part ${l}`));let p=iw(f.text),m=p?de(p,`partNumber`):null,h=p?w(p,`etag`):null;if(!m||!h)throw Error(`Failed to upload part ${l}`);a.push({partNumber:m,etag:h}),s+=d,r?.(s/n.size)}return a}async function uw(e,t,n){let{id:r,transport:i}=await aw(e);try{if(i.kind===`put`){let t=await rw(i.url,e,i.headers,n);if(!t.ok)throw Error(me(t.text,`Upload failed`));n?.(1)}else if(i.kind===`relay`){let t=await rw(o(i.url),e,{"Content-Type":e.type},n);if(!t.ok)throw Error(me(t.text,`Upload failed`));n?.(1)}let a=i.kind===`multipartRelay`?await lw(r,i,e,n):void 0;return t.poster&&await ow(r,t.poster),cw(r,{...t,parts:a})}catch(e){throw await sw(r),e}}async function dw(e){let{file:t,width:n,height:r}=await oe.processToFile(e),i;try{i=(await YC(t)).blurhash}catch{}let a=await uw(t,{width:n,height:r,blurhash:i});return{url:a.url,id:a.id}}var fw=new Map,pw=new Map;function mw(e,t,n){if(e.isDestroyed)return;let{doc:r}=e.state,i=!1;r.descendants((r,a)=>{i||r.type.name!==`image`||r.attrs.src!==t||(e.chain().command(({tr:e})=>(e.setNodeMarkup(a,void 0,{...r.attrs,src:n}),!0)).run(),i=!0)})}function hw(e,t){if(e.isDestroyed)return;let{doc:n}=e.state;n.descendants((n,r)=>{n.type.name===`image`&&n.attrs.src===t&&e.chain().command(({tr:e})=>(e.delete(r,r+n.nodeSize),!0)).run()})}async function gw(e,t,n=dw){let r=URL.createObjectURL(t);e.chain().focus().setImage({src:r}).run();let i=n(t).then(e=>e.url);fw.set(r,i);try{mw(e,r,await i)}catch{hw(e,r)}finally{fw.delete(r)&&URL.revokeObjectURL(r)}}function _w(e){let t=[],{doc:n}=e.state;return n.descendants(n=>{if(n.type.name!==`image`)return;let r=n.attrs.src;if(!r?.startsWith(`blob:`))return;let i=fw.get(r);if(!i)return;fw.delete(r),pw.set(r,i);let a=i.then(t=>mw(e,r,t),()=>hw(e,r)).finally(()=>{pw.delete(r),URL.revokeObjectURL(r)});t.push(a)}),t}async function vw(e){if(!e)return e;let t=new Map;if(yw(e,t),t.size===0)return e;let n=new Map;return await Promise.allSettled(Array.from(t.entries()).map(async([e,t])=>{let r=await t;n.set(e,r)})),bw(e,n)}function yw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=fw.get(e.attrs.src)??pw.get(e.attrs.src);n&&t.set(e.attrs.src,n)}if(e.content)for(let n of e.content)yw(n,t)}function bw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&e.attrs.src.startsWith(`blob:`)){let n=t.get(e.attrs.src);return n?{...e,attrs:{...e.attrs,src:n}}:{type:`__removed__`}}if(!e.content)return e;let n=e.content.map(e=>bw(e,t)).filter(e=>e.type!==`__removed__`);return n===e.content?e:{...e,content:n}}var xw=new Pr(`pasteMedia`);function Sw(e){return`${e.name}:${e.type}:${e.size}:${e.lastModified}`}function Cw(e){if(!e)return[];let t=Array.from(e.items??[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null),n=t.length>0?t:Array.from(e.files??[]),r=new Set;return n.filter(e=>{let t=Sw(e);return r.has(t)?!1:(r.add(t),!0)})}var ww=N.create({name:`pasteMedia`,addOptions(){return{shouldInsertInline:void 0,onPasteFiles:void 0}},addProseMirrorPlugins(){let e=this,t=t=>{let n=t.filter(t=>e.options.shouldInsertInline?.(t)===!0),r=t.filter(e=>!n.includes(e));if(n.length===0&&(r.length===0||e.options.onPasteFiles===void 0))return!1;for(let t of n){let n=e.options.uploadInlineImage;if(n){n(t);continue}gw(e.editor,t)}return r.length>0&&e.options.onPasteFiles!==void 0&&e.options.onPasteFiles(r),!0};return[new j({key:xw,props:{handlePaste(e,n){let r=Cw(n.clipboardData);return r.length===0||!t(r)?!1:(n.preventDefault(),!0)},handleDrop(e,n){let r=Cw(n.dataTransfer);return r.length===0||!t(r)?!1:(n.preventDefault(),!0)}}})]}}),Tw=new Pr(`linkToolbar`),Ew=`hidden`,Dw=!1;function Ow(){return Ew===`input`&&Dw}var kw=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>`;function Aw(e){let{selection:t}=e;if(!t.empty)return null;let n=t.$from,r=e.schema.marks.link;if(!r)return null;let i=n.marks().find(e=>e.type===r);if(!i)return null;let a=n.parent,o=n.start(),s=0,c=0,l=!1,u=0;for(let e=0;e<a.childCount;e++){let t=a.child(e),n=o+u,d=n+t.nodeSize;if(t.marks.some(e=>e.type===r&&e.attrs.href===i.attrs.href))l||=(s=n,!0),c=d;else if(l)break;u+=t.nodeSize}return l?{from:s,to:c,href:i.attrs.href}:null}var jw=N.create({name:`linkToolbar`,addProseMirrorPlugins(){let e=this.editor,t=null,n=null,r=null,i=0,a=0,o=!1,s=!1,c=null;function l(){t=document.createElement(`div`),t.className=`tiptap-link-input`,t.dataset.editorFloatingUi=`true`,t.style.display=`none`;let i=document.createElement(`div`);i.className=`tiptap-link-input-fields`,r=document.createElement(`input`),r.type=`text`,r.className=`tiptap-link-input-text`,r.placeholder=`Link text`,n=document.createElement(`input`),n.type=`url`,n.className=`tiptap-link-input-field`,n.placeholder=`https:// (empty to unlink)`,i.appendChild(r),i.appendChild(n);let a=document.createElement(`button`);a.type=`button`,a.className=`tiptap-link-input-confirm`,a.innerHTML=kw,a.title=`Apply link`,t.appendChild(i),t.appendChild(a);let o=t=>{t.key===`Enter`?(t.preventDefault(),t.stopPropagation(),m()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),s=!0,f(),e.commands.focus())};r.addEventListener(`keydown`,o),n.addEventListener(`keydown`,o);let c=()=>{Dw=!0},l=()=>{requestAnimationFrame(()=>{let e=document.activeElement;(!t||!t.contains(e))&&(Dw=!1)})};r.addEventListener(`focus`,c),n.addEventListener(`focus`,c),r.addEventListener(`blur`,l),n.addEventListener(`blur`,l),a.addEventListener(`mousedown`,e=>{e.preventDefault(),m()}),t.addEventListener(`mousedown`,e=>{e.stopPropagation()})}function u(e,t,n,r){e.style.display=`flex`;let i=t.dom.closest(`dialog`),a=t.coordsAtPos(n),o=t.coordsAtPos(r),s=e.getBoundingClientRect(),c=GS({anchorRect:{left:a.left,right:o.right,top:Math.min(a.top,o.top),bottom:Math.max(a.bottom,o.bottom)},containerRect:WS(i),floatingWidth:s.width,floatingHeight:s.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});e.style.left=`${c.left}px`,e.style.top=`${c.top}px`}function d(e,o){if(!(!t||!n||!r)){if(o.from!==void 0&&o.to!==void 0?(i=o.from,a=o.to):(i=e.state.selection.from,a=e.state.selection.to),Ew=`input`,n.value=o.href,r.value=o.text??e.state.doc.textBetween(i,a,``),u(t,e,i,a),o.focus){let e=r.value.length>0?n:r;requestAnimationFrame(()=>{e.focus(),e.select()})}p(),c=e=>{t&&!t.contains(e.target)&&(s=!0,f())},setTimeout(()=>{c&&document.addEventListener(`mousedown`,c,!0)},0)}}function f(){t&&(t.style.display=`none`),Ew=`hidden`,Dw=!1,p()}function p(){c&&=(document.removeEventListener(`mousedown`,c,!0),null)}function m(){if(!n||!r)return;let t=n.value.trim(),s=e.state.doc.textBetween(i,a,``),c=r.value,l=c.length>0?c:t;if(f(),!t){e.chain().focus().setTextSelection({from:i,to:a}).unsetLink().setTextSelection(a).run(),o=!0;return}let u=l!==s,d=i+l.length;u?e.chain().focus().command(({tr:e})=>(e.insertText(l,i,a),!0)).setTextSelection({from:i,to:d}).setLink({href:t}).setTextSelection(d).run():e.chain().focus().setTextSelection({from:i,to:a}).setLink({href:t}).setTextSelection(a).run(),o=!0}function h(e,t){if(t.button!==0)return;let n=t.target?.closest(`a`);if(!n||!e.dom.contains(n))return;let r=e.state.schema.marks.link;if(!r||!e.state.selection.empty)return;let i=e.state.selection.from,a=t=>e.state.doc.resolve(t).marks().some(e=>e.type===r),o=i;if(!a(i)){try{o=e.posAtDOM(n,0)+1}catch{return}if(o<0||o>e.state.doc.content.size||!a(o))return}s=!1,e.dispatch(e.state.tr.setSelection(k.create(e.state.doc,o)))}return[new j({key:Tw,props:{handleDOMEvents:{click:(e,t)=>(h(e,t),!1)}},view(e){l();let n=e.dom.closest(`dialog`);t&&(n??document.body).appendChild(t);let r=()=>{s=!1,o=!0,d(e,{href:``,focus:!0})};e.dom.addEventListener(`tiptap:open-link-input`,r);let c=e=>{e.key===`Escape`&&Ew===`input`&&(e.preventDefault(),e.stopPropagation(),s=!0,f())};return e.dom.addEventListener(`keydown`,c),{update(e){if(o){o=!1;return}let n=Aw(e.state);if(Ew===`input`&&Dw){t&&u(t,e,i,a);return}if(n){if(s)return;d(e,{href:n.href,from:n.from,to:n.to,focus:!1})}else s=!1,Ew===`input`&&f()},destroy(){e.dom.removeEventListener(`tiptap:open-link-input`,r),e.dom.removeEventListener(`keydown`,c),p(),t?.remove(),t=null,Ew=`hidden`,Dw=!1}}}})]}}),Mw=new Pr(`bubbleMenu`),Nw={bold:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H6V4h8a4 4 0 0 1 0 8"/></svg>`,italic:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>`,h1:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,blockquote:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,clear:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 22-1-4"/><path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1"/><path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z"/><path d="m8 22 1-4"/></svg>`};function Pw(e,t){let{to:n,empty:r}=e.state.selection;if(r){e.chain().focus().toggleMark(t).run();return}let i=e.schema.marks[t];e.chain().focus().toggleMark(t).setTextSelection(n).command(({tr:e})=>(i&&e.removeStoredMark(i),!0)).run()}function Fw(e,t){return t===`compose`?[{key:`bold`,icon:Nw.bold,title:`Bold`,action:()=>Pw(e,`bold`),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:Nw.italic,title:`Italic`,action:()=>Pw(e,`italic`),isActive:()=>e.isActive(`italic`)},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`link`,icon:Nw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)},{key:`clear`,icon:Nw.clear,title:`Clear formatting`,action:()=>{let{to:t}=e.state.selection;e.chain().focus().unsetAllMarks().clearNodes().setTextSelection(t).run()},isActive:()=>!1}]:[{key:`bold`,icon:Nw.bold,title:`Bold`,action:()=>Pw(e,`bold`),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:Nw.italic,title:`Italic`,action:()=>Pw(e,`italic`),isActive:()=>e.isActive(`italic`)},{key:`h1`,icon:Nw.h1,title:`Heading 1`,action:()=>e.chain().focus().toggleHeading({level:1}).run(),isActive:()=>e.isActive(`heading`,{level:1})},{key:`h2`,icon:Nw.h2,title:`Heading 2`,action:()=>e.chain().focus().toggleHeading({level:2}).run(),isActive:()=>e.isActive(`heading`,{level:2})},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`blockquote`,icon:Nw.blockquote,title:`Quote`,action:()=>e.chain().focus().toggleBlockquote().run(),isActive:()=>e.isActive(`blockquote`)},{key:`link`,icon:Nw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)}]}var Iw=N.create({name:`bubbleMenu`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=[],i=new Map;function a(){n=document.createElement(`div`),n.className=`tiptap-bubble-menu`,n.dataset.editorFloatingUi=`true`,n.style.position=`fixed`,n.style.display=`none`,r=Fw(e,t);for(let t of r){if(t.key===`sep`){let e=document.createElement(`span`);e.className=`tiptap-bubble-sep`,n.appendChild(e);continue}let r=document.createElement(`button`);r.type=`button`,r.innerHTML=t.icon,r.title=t.title,r.className=`tiptap-bubble-btn`,r.addEventListener(`mousedown`,n=>{n.preventDefault(),t.action(e.view)}),n.appendChild(r),i.set(t.key,r)}}function o(e){if(!n)return;n.style.display=`flex`;let{from:t,to:r}=e.state.selection,i=e.coordsAtPos(t),a=e.coordsAtPos(r),o=e.dom.closest(`dialog`),s=n.getBoundingClientRect(),l=GS({anchorRect:{left:i.left,right:a.right,top:Math.min(i.top,a.top),bottom:Math.max(i.bottom,a.bottom)},containerRect:WS(o),floatingWidth:s.width,floatingHeight:s.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});n.style.left=`${l.left}px`,n.style.top=`${l.top}px`,c()}function s(){n&&(n.style.display=`none`)}function c(){for(let t of r){if(t.key===`sep`)continue;let n=i.get(t.key);n&&n.classList.toggle(`is-active`,t.isActive(e.view))}}function l(e){let{state:t}=e,{selection:n}=t,{empty:r}=n;return!(r||!n.$from.parent.isTextblock||Ow())}return[new j({key:Mw,view(e){a();let t=e.dom.closest(`dialog`)??document.body;n&&t.appendChild(n);function r(t){let r=t.target;if(!r||e.dom.contains(r)||r.closest(`[data-editor-floating-ui]`)||n?.contains(r))return;let{state:i}=e,a=i.selection.from;e.dispatch(i.tr.setSelection(O.near(i.doc.resolve(a)))),e.dom.blur()}return t.addEventListener(`mousedown`,r),{update(e){l(e)?o(e):s()},destroy(){t.removeEventListener(`mousedown`,r),n?.remove(),n=null}}}})]}}),Lw=new Set([`bold`,`italic`,`strike`,`code`,`underline`]);function Rw(e){return e.filter(e=>Lw.has(e.type.name))}var zw=N.create({name:`exitableMarks`,addKeyboardShortcuts(){return{ArrowRight:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;if(!t.empty||n.pos!==n.end())return!1;let r=Rw(n.marks());if(!r.length)return!1;let{tr:i}=e.state;for(let e of r)i.removeStoredMark(e);return e.view.dispatch(i),!0},Enter:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;return!t.empty||n.parent.textContent.length>0||!Rw(e.state.storedMarks??n.marks()).length||requestAnimationFrame(()=>{let{tr:t}=e.state;t.setStoredMarks([]),e.view.dispatch(t)}),!1}}}}),Bw=` `,Vw=N.create({name:`tabIndent`,addKeyboardShortcuts(){return{Tab:({editor:e})=>{if(e.isActive(`listItem`))return e.commands.sinkListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a)return n(t.tr.insertText(Bw,i)),!0;let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
300
+ ${EC(wC())}`,pC.querySelectorAll(`.tiptap-slash-item`).forEach(e=>{e.addEventListener(`mousedown`,n=>{n.preventDefault(),t(parseInt(e.dataset.index??`0`,10))}),e.addEventListener(`mouseenter`,()=>{mC=parseInt(e.dataset.index??`0`,10),CC()})});let r=bC();r&&(r.scrollTop=0)}function kC(){yC&&=(document.removeEventListener(`mousedown`,yC,!0),null),pC?.remove(),pC=null,mC=0,hC=[],gC=null,_C=null,vC=null}function AC(e,t){if(!pC)return;pC.style.maxHeight=``;let n=WS(null),r=t?WS(t):n,i=GS({anchorRect:{left:e.left,right:e.left,top:e.top,bottom:e.bottom},containerRect:n,floatingWidth:pC.offsetWidth,floatingHeight:pC.offsetHeight,preferredPlacement:`bottom`,fallbackPlacement:`top`,align:`start`,gap:6});pC.style.left=`${i.left-r.left}px`,pC.style.top=`${i.top-r.top}px`,pC.style.maxHeight=i.maxHeight===null?``:`${i.maxHeight}px`}function jC(){yC=e=>{if(!(!pC||pC.contains(e.target))&&_C&&vC){let{state:e,view:t}=_C;t.dispatch(e.tr.delete(vC.from,vC.to))}},document.addEventListener(`mousedown`,yC,!0)}var MC=new Pr(`jantSlashTyping`);function NC(){return new j({key:MC,state:{init:()=>({docChanged:!1}),apply:e=>({docChanged:e.docChanged})}})}function PC({state:e,range:t}){let n=e.doc.resolve(t.to),r=n.parent,i=t.to-n.start();if(i>=r.content.size)return!0;let a=r.textBetween(i,i+1,` `,` `);return a?/\s/.test(a):!0}function FC({state:e,range:t,isActive:n}){return PC({state:e,range:t})?n?!0:MC.getState(e)?.docChanged??!1:!1}var IC=N.create({name:`slashCommands`,addOptions(){return{suggestion:{char:`/`,startOfLine:!1,allow:FC,items:({query:e,editor:t})=>{let n=fC(t),r=Zx(e);return r?n.map((e,t)=>({item:e,index:t,rank:Xx([e.label,e.description,...e.keywords],r)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item):n},render:()=>{function e(e){let t=e.options.element;return t instanceof globalThis.Element?t:null}return{onStart:t=>{pC=xC(),mC=0,gC=t.command,_C=t.editor,vC=t.range,OC(t.items,e=>t.command({index:e})),document.dispatchEvent(new CustomEvent(`jant:slash-command-discovered`,{bubbles:!0}));let n=e(t.editor)?.closest(`dialog`)??null;(n??document.body).appendChild(pC);let r=t.clientRect?.();r&&AC(r,n),jC()},onUpdate:t=>{gC=t.command,vC=t.range,OC(t.items,e=>t.command({index:e}));let n=t.clientRect?.();n&&AC(n,e(t.editor)?.closest(`dialog`)??null)},onKeyDown:e=>{let{event:t,view:n,range:r}=e;return t.key===`ArrowDown`?(t.preventDefault(),hC.length===0?!0:(mC=(mC+1)%hC.length,CC(),!0)):t.key===`ArrowUp`?(t.preventDefault(),hC.length===0?!0:(mC=(mC-1+hC.length)%hC.length,CC(),!0)):t.key===`Enter`?(t.preventDefault(),hC.length===0||gC?.({index:mC}),!0):t.key===`Escape`?(t.stopPropagation(),t.preventDefault(),n.dispatch(n.state.tr.delete(r.from,r.to)),!0):!1},onExit:()=>{kC()}}},command:({editor:e,range:t,props:n})=>{let r=hC[n.index];r&&r.command(e,t)}}}},addProseMirrorPlugins(){return[NC(),VS({editor:this.editor,...this.options.suggestion})]}}),LC=`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~`.split(``),RC=(e,t)=>{var n=``;for(let r=1;r<=t;r++){let i=Math.floor(e)/83**(t-r)%83;n+=LC[Math.floor(i)]}return n},zC=e=>{let t=e/255;return t<=.04045?t/12.92:((t+.055)/1.055)**2.4},BC=e=>{let t=Math.max(0,Math.min(1,e));return t<=.0031308?Math.trunc(t*12.92*255+.5):Math.trunc((1.055*t**.4166666666666667-.055)*255+.5)},VC=e=>e<0?-1:1,HC=(e,t)=>VC(e)*Math.abs(e)**+t,UC=class extends Error{constructor(e){super(e),this.name=`ValidationError`,this.message=e}},WC=4,GC=(e,t,n,r)=>{let i=0,a=0,o=0,s=t*WC;for(let c=0;c<t;c++){let t=WC*c;for(let l=0;l<n;l++){let n=t+l*s,u=r(c,l);i+=u*zC(e[n]),a+=u*zC(e[n+1]),o+=u*zC(e[n+2])}}let c=1/(t*n);return[i*c,a*c,o*c]},KC=e=>{let t=BC(e[0]),n=BC(e[1]),r=BC(e[2]);return(t<<16)+(n<<8)+r},qC=(e,t)=>{let n=Math.floor(Math.max(0,Math.min(18,Math.floor(HC(e[0]/t,.5)*9+9.5)))),r=Math.floor(Math.max(0,Math.min(18,Math.floor(HC(e[1]/t,.5)*9+9.5)))),i=Math.floor(Math.max(0,Math.min(18,Math.floor(HC(e[2]/t,.5)*9+9.5))));return n*19*19+r*19+i},JC=(e,t,n,r,i)=>{if(r<1||r>9||i<1||i>9)throw new UC(`BlurHash must have between 1 and 9 components`);if(t*n*4!==e.length)throw new UC(`Width and height must match the pixels array`);let a=[];for(let o=0;o<i;o++)for(let i=0;i<r;i++){let r=i==0&&o==0?1:2,s=GC(e,t,n,(e,a)=>r*Math.cos(Math.PI*i*e/t)*Math.cos(Math.PI*o*a/n));a.push(s)}let o=a[0],s=a.slice(1),c=``,l=r-1+(i-1)*9;c+=RC(l,1);let u;if(s.length>0){let e=Math.max(...s.map(e=>Math.max(...e))),t=Math.floor(Math.max(0,Math.min(82,Math.floor(e*166-.5))));u=(t+1)/166,c+=RC(t,1)}else u=1,c+=RC(0,1);return c+=RC(KC(o),4),s.forEach(e=>{c+=RC(qC(e,u),2)}),c};async function YC(e){let t=await $C(e),{width:n,height:r}=t,i=Math.min(32/n,32/r,1),a=Math.max(Math.round(n*i),1),o=Math.max(Math.round(r*i),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);return c.drawImage(t,0,0,a,o),{width:n,height:r,blurhash:JC(c.getImageData(0,0,a,o).data,a,o,4,3)}}async function XC(e){let t=URL.createObjectURL(e);try{let e=document.createElement(`video`);e.muted=!0,e.preload=`auto`;let{width:n,height:r,duration:i}=await new Promise((n,r)=>{e.onloadedmetadata=()=>n({width:e.videoWidth,height:e.videoHeight,duration:e.duration}),e.onerror=()=>r(Error(`Failed to load video metadata`)),e.src=t}),a,o;try{let t=Math.min(i*.1,1),s=await Promise.race([ew(e,n,r,t),tw(8e3)]);a=s.blurhash,o=s.poster}catch{}return{width:n,height:r,blurhash:a,poster:o}}finally{URL.revokeObjectURL(t)}}async function ZC(e){let t=await e.arrayBuffer(),n=new AudioContext;try{let e=(await n.decodeAudioData(t)).getChannelData(0),r=Math.max(1,Math.floor(e.length/100)),i=Array(100);for(let t=0;t<100;t++){let n=0,a=t*r,o=Math.min(a+r,e.length);for(let t=a;t<o;t++){let r=Math.abs(e[t]);r>n&&(n=r)}i[t]=n}let a=0;for(let e of i)e>a&&(a=e);if(a>0)for(let e=0;e<100;e++)i[e]=Math.round(i[e]/a*100)/100;return JSON.stringify(i)}finally{await n.close()}}async function QC(e){try{if(e.type.startsWith(`image/`))return await YC(e);if(e.type.startsWith(`video/`)){let t=await XC(e);return{width:t.width,height:t.height,blurhash:t.blurhash,poster:t.poster}}if(e.type.startsWith(`audio/`))return{waveform:await ZC(e)}}catch{}return{}}function $C(e){return new Promise((t,n)=>{let r=new Image,i=URL.createObjectURL(e);r.onload=()=>{URL.revokeObjectURL(i),t(r)},r.onerror=()=>{URL.revokeObjectURL(i),n(Error(`Failed to load image`))},r.src=i})}function ew(e,t,n,r){return new Promise((i,a)=>{e.currentTime=r,e.onseeked=()=>{try{let r=Math.min(32/t,32/n,1),a=Math.max(Math.round(t*r),1),o=Math.max(Math.round(n*r),1),s=document.createElement(`canvas`);s.width=a,s.height=o;let c=s.getContext(`2d`);if(!c)throw Error(`Failed to get canvas context`);c.drawImage(e,0,0,a,o);let l=JC(c.getImageData(0,0,a,o).data,a,o,4,3),u=Math.min(640/t,1),d=Math.round(t*u),f=Math.round(n*u),p=document.createElement(`canvas`);p.width=d,p.height=f;let m=p.getContext(`2d`);if(!m){i({blurhash:l});return}m.drawImage(e,0,0,d,f),p.toBlob(e=>{i({blurhash:l,poster:e??void 0})},`image/webp`,.8)}catch(e){a(e)}},e.onerror=()=>a(Error(`Video seek failed`))})}function tw(e){return new Promise((t,n)=>setTimeout(()=>n(Error(`Timeout`)),e))}function nw(e){if(!le(e))return null;let t=w(e,`kind`),n=w(e,`method`),r=w(e,`url`);if(!t||n!==`PUT`||!r)return null;if(t===`relay`)return{kind:t,method:`PUT`,url:r};if(t===`multipartRelay`){let n=de(e,`partSize`);return n?{kind:t,method:`PUT`,url:r,partSize:n}:null}if(t===`put`){let n=de(e,`expiresAt`),i=e.headers;if(!n||!le(i))return null;let a={};for(let[e,t]of Object.entries(i))typeof t==`string`&&(a[e]=t);return{kind:t,method:`PUT`,url:r,headers:a,expiresAt:n}}return null}function rw(e,t,n,r){return new Promise((i,a)=>{let o=new globalThis.XMLHttpRequest;o.open(`PUT`,e);for(let[e,t]of Object.entries(n))o.setRequestHeader(e,t);o.upload.addEventListener(`progress`,e=>{e.lengthComputable&&r&&r(e.loaded/e.total)}),o.addEventListener(`load`,()=>{i({status:o.status,ok:o.status>=200&&o.status<300,text:o.responseText})}),o.addEventListener(`error`,()=>a(Error(`Network error`))),o.addEventListener(`abort`,()=>a(Error(`Upload aborted`))),o.send(t)})}function iw(e){try{let t=JSON.parse(e);return le(t)?t:null}catch{return null}}async function aw(e){let t=await fetch(o(`/api/uploads/init`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({filename:e.name,contentType:e.type||`application/octet-stream`,size:e.size})});if(!t.ok)throw Error(await pe(t,`Failed to start upload`));let n=await fe(t),r=w(n,`id`),i=nw(n.transport);if(!r||!i)throw Error(`Failed to start upload`);return{id:r,transport:i}}async function ow(e,t){let n=await fetch(o(`/api/uploads/${e}/poster`),{method:`PUT`,headers:{"Content-Type":t.type||`image/webp`},body:t});if(!n.ok)throw Error(await pe(n,`Failed to upload poster`))}async function sw(e){await fetch(o(`/api/uploads/${e}/abort`),{method:`POST`}).catch(()=>{})}async function cw(e,t){let n=await fetch(o(`/api/uploads/${e}/complete`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok)throw Error(await pe(n,`Failed to complete upload`));let r=await fe(n),i=w(r,`id`),a=w(r,`filename`),s=w(r,`url`),c=w(r,`mimeType`),l=de(r,`size`);if(!i||!a||!s||!c||l===void 0)throw Error(`Failed to complete upload`);return{id:i,filename:a,url:s,mimeType:c,size:l}}async function lw(e,t,n,r){let i=Math.ceil(n.size/t.partSize),a=[],s=0;for(let e=0;e<i;e+=1){let i=e*t.partSize,c=Math.min(i+t.partSize,n.size),l=e+1,u=n.slice(i,c),d=c-i,f=await rw(o(`${t.url}?partNumber=${l}`),u,{},e=>{r?.((s+d*e)/n.size)});if(!f.ok)throw Error(me(f.text,`Failed to upload part ${l}`));let p=iw(f.text),m=p?de(p,`partNumber`):null,h=p?w(p,`etag`):null;if(!m||!h)throw Error(`Failed to upload part ${l}`);a.push({partNumber:m,etag:h}),s+=d,r?.(s/n.size)}return a}async function uw(e,t,n){let{id:r,transport:i}=await aw(e);try{if(i.kind===`put`){let t=await rw(i.url,e,i.headers,n);if(!t.ok)throw Error(me(t.text,`Upload failed`));n?.(1)}else if(i.kind===`relay`){let t=await rw(o(i.url),e,{"Content-Type":e.type},n);if(!t.ok)throw Error(me(t.text,`Upload failed`));n?.(1)}let a=i.kind===`multipartRelay`?await lw(r,i,e,n):void 0;return t.poster&&await ow(r,t.poster),cw(r,{...t,parts:a})}catch(e){throw await sw(r),e}}async function dw(e){let{file:t,width:n,height:r}=await oe.processToFile(e),i;try{i=(await YC(t)).blurhash}catch{}let a=await uw(t,{width:n,height:r,blurhash:i});return{url:a.url,id:a.id}}var fw=new Map,pw=new Map;function mw(e,t,n){if(e.isDestroyed)return;let{doc:r}=e.state;r.descendants((r,i)=>{r.type.name!==`image`||r.attrs.src!==t||e.chain().command(({tr:e})=>(e.setNodeMarkup(i,void 0,{...r.attrs,src:n}),!0)).run()})}function hw(e,t){if(e.isDestroyed)return;let{doc:n}=e.state;n.descendants((n,r)=>{n.type.name===`image`&&n.attrs.src===t&&e.chain().command(({tr:e})=>(e.delete(r,r+n.nodeSize),!0)).run()})}function gw(e,t,n){n?mw(e,t,n):t.startsWith(`blob:`)&&hw(e,t)}async function _w(e,t,n=dw){let r=URL.createObjectURL(t);e.chain().focus().setImage({src:r}).run();let i=n(t).then(e=>e.url);fw.set(r,i);try{gw(e,r,await i)}catch{gw(e,r,null)}finally{fw.delete(r)&&URL.revokeObjectURL(r)}}async function vw(e,t){let n=await fetch(o(`/api/uploads/sideload`),{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({url:e,alt:t})});if(!n.ok)throw Error(`Sideload failed: HTTP ${n.status}`);return await n.json()}async function yw(e,t,n){let r=n();fw.set(t,r);try{gw(e,t,await r)}catch{gw(e,t,null)}finally{fw.delete(t)}}function bw(e){let t=[],{doc:n}=e.state;return n.descendants(n=>{if(n.type.name!==`image`)return;let r=n.attrs.src;if(typeof r!=`string`)return;let i=fw.get(r);if(!i)return;fw.delete(r),pw.set(r,i);let a=r.startsWith(`blob:`),o=i.then(t=>mw(e,r,t),()=>gw(e,r,null)).finally(()=>{pw.delete(r),a&&URL.revokeObjectURL(r)});t.push(o)}),t}async function xw(e){if(!e)return e;let t=new Map;if(Cw(e,t),t.size===0)return e;let n=new Map;return await Promise.allSettled(Array.from(t.entries()).map(async([e,t])=>{try{n.set(e,await t)}catch{n.set(e,null)}})),ww(e,n)}function Sw(e){if(!e)return!1;let t=new Map;return Cw(e,t),t.size>0}function Cw(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`){let n=e.attrs.src,r=fw.get(n)??pw.get(n);r&&t.set(n,r)}if(e.content)for(let n of e.content)Cw(n,t)}function ww(e,t){if(e.type===`image`&&typeof e.attrs?.src==`string`&&t.has(e.attrs.src)){let n=e.attrs.src,r=t.get(n);return r?{...e,attrs:{...e.attrs,src:r}}:n.startsWith(`blob:`)?{type:`__removed__`}:e}if(!e.content)return e;let n=e.content.map(e=>ww(e,t)).filter(e=>e.type!==`__removed__`);return n===e.content?e:{...e,content:n}}var Tw=new Pr(`pasteMedia`);function Ew(e){return`${e.name}:${e.type}:${e.size}:${e.lastModified}`}function Dw(e){if(!e)return[];let t=Array.from(e.items??[]).filter(e=>e.kind===`file`).map(e=>e.getAsFile()).filter(e=>e!==null),n=t.length>0?t:Array.from(e.files??[]),r=new Set;return n.filter(e=>{let t=Ew(e);return r.has(t)?!1:(r.add(t),!0)})}var Ow=N.create({name:`pasteMedia`,addOptions(){return{shouldInsertInline:void 0,onPasteFiles:void 0}},addProseMirrorPlugins(){let e=this,t=t=>{let n=t.filter(t=>e.options.shouldInsertInline?.(t)===!0),r=t.filter(e=>!n.includes(e));if(n.length===0&&(r.length===0||e.options.onPasteFiles===void 0))return!1;for(let t of n){let n=e.options.uploadInlineImage;if(n){n(t);continue}_w(e.editor,t)}return r.length>0&&e.options.onPasteFiles!==void 0&&e.options.onPasteFiles(r),!0};return[new j({key:Tw,props:{handlePaste(e,n){let r=Dw(n.clipboardData);return r.length===0||!t(r)?!1:(n.preventDefault(),!0)},handleDrop(e,n){let r=Dw(n.dataTransfer);return r.length===0||!t(r)?!1:(n.preventDefault(),!0)}}})]}}),kw=new Pr(`linkToolbar`),Aw=`hidden`,jw=!1;function Mw(){return Aw===`input`&&jw}var Nw=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 10 4 15 9 20"/><path d="M20 4v7a4 4 0 0 1-4 4H4"/></svg>`;function Pw(e){let{selection:t}=e;if(!t.empty)return null;let n=t.$from,r=e.schema.marks.link;if(!r)return null;let i=n.marks().find(e=>e.type===r);if(!i)return null;let a=n.parent,o=n.start(),s=0,c=0,l=!1,u=0;for(let e=0;e<a.childCount;e++){let t=a.child(e),n=o+u,d=n+t.nodeSize;if(t.marks.some(e=>e.type===r&&e.attrs.href===i.attrs.href))l||=(s=n,!0),c=d;else if(l)break;u+=t.nodeSize}return l?{from:s,to:c,href:i.attrs.href}:null}var Fw=N.create({name:`linkToolbar`,addProseMirrorPlugins(){let e=this.editor,t=null,n=null,r=null,i=0,a=0,o=!1,s=!1,c=null;function l(){t=document.createElement(`div`),t.className=`tiptap-link-input`,t.dataset.editorFloatingUi=`true`,t.style.display=`none`;let i=document.createElement(`div`);i.className=`tiptap-link-input-fields`,r=document.createElement(`input`),r.type=`text`,r.className=`tiptap-link-input-text`,r.placeholder=`Link text`,n=document.createElement(`input`),n.type=`url`,n.className=`tiptap-link-input-field`,n.placeholder=`https:// (empty to unlink)`,i.appendChild(r),i.appendChild(n);let a=document.createElement(`button`);a.type=`button`,a.className=`tiptap-link-input-confirm`,a.innerHTML=Nw,a.title=`Apply link`,t.appendChild(i),t.appendChild(a);let o=t=>{t.key===`Enter`?(t.preventDefault(),t.stopPropagation(),m()):t.key===`Escape`&&(t.preventDefault(),t.stopPropagation(),s=!0,f(),e.commands.focus())};r.addEventListener(`keydown`,o),n.addEventListener(`keydown`,o);let c=()=>{jw=!0},l=()=>{requestAnimationFrame(()=>{let e=document.activeElement;(!t||!t.contains(e))&&(jw=!1)})};r.addEventListener(`focus`,c),n.addEventListener(`focus`,c),r.addEventListener(`blur`,l),n.addEventListener(`blur`,l),a.addEventListener(`mousedown`,e=>{e.preventDefault(),m()}),t.addEventListener(`mousedown`,e=>{e.stopPropagation()})}function u(e,t,n,r){e.style.display=`flex`;let i=t.dom.closest(`dialog`),a=t.coordsAtPos(n),o=t.coordsAtPos(r),s=e.getBoundingClientRect(),c=GS({anchorRect:{left:a.left,right:o.right,top:Math.min(a.top,o.top),bottom:Math.max(a.bottom,o.bottom)},containerRect:WS(i),floatingWidth:s.width,floatingHeight:s.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});e.style.left=`${c.left}px`,e.style.top=`${c.top}px`}function d(e,o){if(!(!t||!n||!r)){if(o.from!==void 0&&o.to!==void 0?(i=o.from,a=o.to):(i=e.state.selection.from,a=e.state.selection.to),Aw=`input`,n.value=o.href,r.value=o.text??e.state.doc.textBetween(i,a,``),u(t,e,i,a),o.focus){let e=r.value.length>0?n:r;requestAnimationFrame(()=>{e.focus(),e.select()})}p(),c=e=>{t&&!t.contains(e.target)&&(s=!0,f())},setTimeout(()=>{c&&document.addEventListener(`mousedown`,c,!0)},0)}}function f(){t&&(t.style.display=`none`),Aw=`hidden`,jw=!1,p()}function p(){c&&=(document.removeEventListener(`mousedown`,c,!0),null)}function m(){if(!n||!r)return;let t=n.value.trim(),s=e.state.doc.textBetween(i,a,``),c=r.value,l=c.length>0?c:t;if(f(),!t){e.chain().focus().setTextSelection({from:i,to:a}).unsetLink().setTextSelection(a).run(),o=!0;return}let u=l!==s,d=i+l.length;u?e.chain().focus().command(({tr:e})=>(e.insertText(l,i,a),!0)).setTextSelection({from:i,to:d}).setLink({href:t}).setTextSelection(d).run():e.chain().focus().setTextSelection({from:i,to:a}).setLink({href:t}).setTextSelection(a).run(),o=!0}function h(e,t){if(t.button!==0)return;let n=t.target?.closest(`a`);if(!n||!e.dom.contains(n))return;let r=e.state.schema.marks.link;if(!r||!e.state.selection.empty)return;let i=e.state.selection.from,a=t=>e.state.doc.resolve(t).marks().some(e=>e.type===r),o=i;if(!a(i)){try{o=e.posAtDOM(n,0)+1}catch{return}if(o<0||o>e.state.doc.content.size||!a(o))return}s=!1,e.dispatch(e.state.tr.setSelection(k.create(e.state.doc,o)))}return[new j({key:kw,props:{handleDOMEvents:{click:(e,t)=>(h(e,t),!1)}},view(e){l();let n=e.dom.closest(`dialog`);t&&(n??document.body).appendChild(t);let r=()=>{s=!1,o=!0,d(e,{href:``,focus:!0})};e.dom.addEventListener(`tiptap:open-link-input`,r);let c=e=>{e.key===`Escape`&&Aw===`input`&&(e.preventDefault(),e.stopPropagation(),s=!0,f())};return e.dom.addEventListener(`keydown`,c),{update(e){if(o){o=!1;return}let n=Pw(e.state);if(Aw===`input`&&jw){t&&u(t,e,i,a);return}if(n){if(s)return;d(e,{href:n.href,from:n.from,to:n.to,focus:!1})}else s=!1,Aw===`input`&&f()},destroy(){e.dom.removeEventListener(`tiptap:open-link-input`,r),e.dom.removeEventListener(`keydown`,c),p(),t?.remove(),t=null,Aw=`hidden`,jw=!1}}}})]}}),Iw=new Pr(`bubbleMenu`),Lw={bold:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6 12h9a4 4 0 0 1 0 8H6V4h8a4 4 0 0 1 0 8"/></svg>`,italic:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="19" y1="4" x2="10" y2="4"/><line x1="14" y1="20" x2="5" y2="20"/><line x1="15" y1="4" x2="9" y2="20"/></svg>`,h1:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M17 12l3-2v10"/></svg>`,h2:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 12h8"/><path d="M4 18V6"/><path d="M12 18V6"/><path d="M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1"/></svg>`,blockquote:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21c3 0 7-1 7-8V5c0-1.25-.756-2.017-2-2H4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2 1 0 1 0 1 1v1c0 1-1 2-2 2s-1 .008-1 1.031V20c0 1 0 1 1 1z"/><path d="M15 21c3 0 7-1 7-8V5c0-1.25-.757-2.017-2-2h-4c-1.25 0-2 .75-2 1.972V11c0 1.25.75 2 2 2h.75c0 2.25.25 4-2.75 4v3c0 1 0 1 1 1z"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,clear:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="m16 22-1-4"/><path d="M19 14a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2h-3a1 1 0 0 1-1-1V4a2 2 0 0 0-4 0v5a1 1 0 0 1-1 1H6a2 2 0 0 0-2 2v1a1 1 0 0 0 1 1"/><path d="M19 14H5l-1.973 6.767A1 1 0 0 0 4 22h16a1 1 0 0 0 .973-1.233z"/><path d="m8 22 1-4"/></svg>`};function Rw(e,t){let{to:n,empty:r}=e.state.selection;if(r){e.chain().focus().toggleMark(t).run();return}let i=e.schema.marks[t];e.chain().focus().toggleMark(t).setTextSelection(n).command(({tr:e})=>(i&&e.removeStoredMark(i),!0)).run()}function zw(e,t){return t===`compose`?[{key:`bold`,icon:Lw.bold,title:`Bold`,action:()=>Rw(e,`bold`),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:Lw.italic,title:`Italic`,action:()=>Rw(e,`italic`),isActive:()=>e.isActive(`italic`)},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`link`,icon:Lw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)},{key:`clear`,icon:Lw.clear,title:`Clear formatting`,action:()=>{let{to:t}=e.state.selection;e.chain().focus().unsetAllMarks().clearNodes().setTextSelection(t).run()},isActive:()=>!1}]:[{key:`bold`,icon:Lw.bold,title:`Bold`,action:()=>Rw(e,`bold`),isActive:()=>e.isActive(`bold`)},{key:`italic`,icon:Lw.italic,title:`Italic`,action:()=>Rw(e,`italic`),isActive:()=>e.isActive(`italic`)},{key:`h1`,icon:Lw.h1,title:`Heading 1`,action:()=>e.chain().focus().toggleHeading({level:1}).run(),isActive:()=>e.isActive(`heading`,{level:1})},{key:`h2`,icon:Lw.h2,title:`Heading 2`,action:()=>e.chain().focus().toggleHeading({level:2}).run(),isActive:()=>e.isActive(`heading`,{level:2})},{key:`sep`,icon:``,title:``,action:()=>{},isActive:()=>!1},{key:`blockquote`,icon:Lw.blockquote,title:`Quote`,action:()=>e.chain().focus().toggleBlockquote().run(),isActive:()=>e.isActive(`blockquote`)},{key:`link`,icon:Lw.link,title:`Link`,action:t=>{e.isActive(`link`)?e.chain().focus().unsetLink().run():t.dom.dispatchEvent(new CustomEvent(`tiptap:open-link-input`))},isActive:()=>e.isActive(`link`)}]}var Bw=N.create({name:`bubbleMenu`,addOptions(){return{toolbarMode:`default`}},addProseMirrorPlugins(){let e=this.editor,t=this.options.toolbarMode,n=null,r=[],i=new Map;function a(){n=document.createElement(`div`),n.className=`tiptap-bubble-menu`,n.dataset.editorFloatingUi=`true`,n.style.position=`fixed`,n.style.display=`none`,r=zw(e,t);for(let t of r){if(t.key===`sep`){let e=document.createElement(`span`);e.className=`tiptap-bubble-sep`,n.appendChild(e);continue}let r=document.createElement(`button`);r.type=`button`,r.innerHTML=t.icon,r.title=t.title,r.className=`tiptap-bubble-btn`,r.addEventListener(`mousedown`,n=>{n.preventDefault(),t.action(e.view)}),n.appendChild(r),i.set(t.key,r)}}function o(e){if(!n)return;n.style.display=`flex`;let{from:t,to:r}=e.state.selection,i=e.coordsAtPos(t),a=e.coordsAtPos(r),o=e.dom.closest(`dialog`),s=n.getBoundingClientRect(),l=GS({anchorRect:{left:i.left,right:a.right,top:Math.min(i.top,a.top),bottom:Math.max(i.bottom,a.bottom)},containerRect:WS(o),floatingWidth:s.width,floatingHeight:s.height,preferredPlacement:`top`,fallbackPlacement:`bottom`,align:`center`});n.style.left=`${l.left}px`,n.style.top=`${l.top}px`,c()}function s(){n&&(n.style.display=`none`)}function c(){for(let t of r){if(t.key===`sep`)continue;let n=i.get(t.key);n&&n.classList.toggle(`is-active`,t.isActive(e.view))}}function l(e){let{state:t}=e,{selection:n}=t,{empty:r}=n;return!(r||!n.$from.parent.isTextblock||Mw())}return[new j({key:Iw,view(e){a();let t=e.dom.closest(`dialog`)??document.body;n&&t.appendChild(n);function r(t){let r=t.target;if(!r||e.dom.contains(r)||r.closest(`[data-editor-floating-ui]`)||n?.contains(r))return;let{state:i}=e,a=i.selection.from;e.dispatch(i.tr.setSelection(O.near(i.doc.resolve(a)))),e.dom.blur()}return t.addEventListener(`mousedown`,r),{update(e){l(e)?o(e):s()},destroy(){t.removeEventListener(`mousedown`,r),n?.remove(),n=null}}}})]}}),Vw=new Set([`bold`,`italic`,`strike`,`code`,`underline`]);function Hw(e){return e.filter(e=>Vw.has(e.type.name))}var Uw=N.create({name:`exitableMarks`,addKeyboardShortcuts(){return{ArrowRight:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;if(!t.empty||n.pos!==n.end())return!1;let r=Hw(n.marks());if(!r.length)return!1;let{tr:i}=e.state;for(let e of r)i.removeStoredMark(e);return e.view.dispatch(i),!0},Enter:({editor:e})=>{let{selection:t}=e.state,{$from:n}=t;return!t.empty||n.parent.textContent.length>0||!Hw(e.state.storedMarks??n.marks()).length||requestAnimationFrame(()=>{let{tr:t}=e.state;t.setStoredMarks([]),e.view.dispatch(t)}),!1}}}}),Ww=` `,Gw=N.create({name:`tabIndent`,addKeyboardShortcuts(){return{Tab:({editor:e})=>{if(e.isActive(`listItem`))return e.commands.sinkListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a)return n(t.tr.insertText(Ww,i)),!0;let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
301
301
  `,u-1)+1;f.push(p);let m=p;for(;;){let e=l.indexOf(`
302
- `,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0;for(let e of f)h=h.insertText(Bw,c+e+g),g+=2;let _=i+2,v=a+g;return h.setSelection(k.create(h.doc,_,v)),n(h),!0}return!1},"Shift-Tab":({editor:e})=>{if(e.isActive(`listItem`))return e.commands.liftListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a){let e=i-c,r=l.lastIndexOf(`
303
- `,e-1)+1,a=l.slice(r),o=a.startsWith(Bw)?2:a.startsWith(` `)?1:0;return o===0||n(t.tr.delete(c+r,c+r+o)),!0}let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
302
+ `,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0;for(let e of f)h=h.insertText(Ww,c+e+g),g+=2;let _=i+2,v=a+g;return h.setSelection(k.create(h.doc,_,v)),n(h),!0}return!1},"Shift-Tab":({editor:e})=>{if(e.isActive(`listItem`))return e.commands.liftListItem(`listItem`);if(e.isActive(`codeBlock`)){let{state:t,dispatch:n}=e.view,{selection:r}=t,{from:i,to:a}=r,o=t.doc.resolve(i),s=o.parent;if(s.type.name!==`codeBlock`)return!1;let c=o.start(),l=s.textContent;if(i===a){let e=i-c,r=l.lastIndexOf(`
303
+ `,e-1)+1,a=l.slice(r),o=a.startsWith(Ww)?2:a.startsWith(` `)?1:0;return o===0||n(t.tr.delete(c+r,c+r+o)),!0}let u=i-c,d=a-c,f=[],p=l.lastIndexOf(`
304
304
  `,u-1)+1;f.push(p);let m=p;for(;;){let e=l.indexOf(`
305
- `,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0,_=0;for(let e=0;e<f.length;e++){let t=f[e],n=l.slice(t),r=n.startsWith(Bw)?2:n.startsWith(` `)?1:0;if(r>0){let n=c+t+g;h=h.delete(n,n+r),g-=r,e===0&&(_=r)}}if(g<0){let e=Math.max(i-_,c),t=a+g;h.setSelection(k.create(h.doc,e,Math.max(t,e)))}return n(h),!0}return!1}}}}),Hw=/\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/,Uw=RegExp(Hw.source+`$`),Ww=RegExp(Hw.source+`\\s$`),Gw=/((?:https?:\/\/|mailto:)[^\s<]+)\s$/,Kw=N.create({name:`linkInputRules`,addInputRules(){let e=this.editor.schema.marks.link;if(!e)return[];function n(n,r,i,a){let o=i[1]?.trim(),s=t(i[2]??``);if(!o||!s)return null;let c=a?o+a:o;n.tr.insertText(c,r.from,r.to),n.tr.addMark(r.from,r.from+o.length,e.create({href:s})),n.tr.removeStoredMark(e)}return[new qd({find:Gw,handler:({state:n,range:r,match:i})=>{let a=t(i[1]??``);if(!a)return null;let o=r.from+a.length;if(n.doc.rangeHasMark(r.from,o,e))return null;n.tr.addMark(r.from,o,e.create({href:a})),n.tr.removeStoredMark(e)}}),new qd({find:Uw,handler:({state:e,range:t,match:r})=>{n(e,t,r,``)}}),new qd({find:Ww,handler:({state:e,range:t,match:r})=>{n(e,t,r,` `)}})]}});function qw(e){return new qd({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Pu(e.getAttributes,void 0,r)||{},a=t.tr.delete(n.from,n.to),o=a.doc.resolve(n.from).blockRange(),s=o&&On(o,e.type,i);if(!s)return null;a.wrap(o,s)}})}var Jw=N.create({name:`wrappingInputRules`,priority:1e3,addInputRules(){let{schema:e}=this.editor,t=[],n=e.nodes.blockquote;n&&t.push(qw({find:/^\s*>\s$/,type:n}));let r=e.nodes.bulletList;r&&t.push(qw({find:/^\s*([-+*])\s$/,type:r}));let i=e.nodes.orderedList;return i&&t.push(qw({find:/^(\d+)\.\s$/,type:i,getAttributes:e=>({start:Number(e[1])})})),t}});function Yw(e,t){let{state:n}=e,r=n.schema.nodes.paragraph;if(!r)return!1;let{selection:i}=n,{$from:a,$to:o}=i,s;s=a.depth===0?t===`above`?i.from:i.to:t===`above`?a.before(1):o.after(1);let c=n.tr.insert(s,r.create());return c.setSelection(k.create(c.doc,s+1)),e.view.dispatch(c.scrollIntoView()),!0}var Xw=N.create({name:`insertParagraphAround`,addKeyboardShortcuts(){let e=({editor:e})=>{let{state:t}=e,{selection:n}=t;if(!n.empty)return!1;let{$from:r}=n;if(r.depth<1||r.pos!==r.depth)return!1;let i=t.doc.firstChild;return!i||i.type.name===`paragraph`?!1:Yw(e,`above`)};return{ArrowUp:e,ArrowLeft:e,"Mod-Shift-Enter":({editor:e})=>Yw(e,`above`),"Mod-Alt-Enter":({editor:e})=>Yw(e,`below`)}}}),Zw=/\[\^([^\]\n]+)\]([ \t.,!?;)]$)/,Qw=/^\[\^([^\]\n]+)\]: $/,$w=/\[\^([^\]\n]+)\]$/;function eT(e){let t=new Set;return e.descendants(e=>{if(e.type.name!==`footnoteReference`&&e.type.name!==`footnoteDefinition`)return!0;let n=ax(e.attrs.label);return n&&t.add(ox(n)),!0}),t}function tT(e){let t=eT(e),n=1;for(;t.has(String(n));)n+=1;return String(n)}function nT(e){let t=e.content.size;return e.forEach((e,n)=>{e.type.name===`footnoteDefinition`&&(t=n+e.nodeSize)}),t}function rT(e,t){let n=ox(t),r=null;return e.forEach((e,t)=>{r===null&&e.type.name===`footnoteDefinition`&&ox(e.attrs.label)===n&&(r=t)}),r}function iT(e,t){let n=ox(t),r=null;return e.forEach((e,t)=>{r===null&&e.type.name===`footnoteDefinition`&&ox(e.attrs.label)===n&&(r={from:t,to:t+e.nodeSize})}),r}function aT(e,t){let n=ox(t),r=[];return e.descendants((e,t)=>(e.type.name===`footnoteReference`&&ox(e.attrs.label)===n&&r.push({from:t,to:t+e.nodeSize}),!0)),r}function oT(e,t){let n=e.schema.nodes.footnoteReference;return n?n.create({label:t}):null}function sT(e,t){let n=e.schema.nodes.footnoteDefinition,r=e.schema.nodes.paragraph;return!n||!r?null:n.create({label:t},[r.create()])}function cT(e,t){let n=Math.min(t+2,e.doc.content.size);e.setSelection(k.near(e.doc.resolve(n),1))}function lT(e,t){let n=null,r=null;e.doc.forEach((e,i)=>{i===t&&e.type.name===`paragraph`&&e.content.size===0&&(n=i,r=i+e.nodeSize)}),n!==null&&r!==null&&e.delete(n,r)}function uT(e,t,n){let r=rT(t.doc,n);if(r!==null)return r;let i=sT(e,n);if(!i)return null;let a=nT(t.doc);return t.insert(a,i),lT(t,a+i.nodeSize),a}function dT(e,t){if(t.doc.childCount>0)return;let n=e.schema.nodes.paragraph;n&&t.insert(0,n.create())}function fT(e,t){if(!t||e.doc.childCount<2)return;let n=e.doc.lastChild,r=e.doc.child(e.doc.childCount-2);n?.type.name===`paragraph`&&n.content.size===0&&r.type.name!==`footnoteDefinition`&&e.delete(e.doc.content.size-n.nodeSize,e.doc.content.size)}function pT(e,t){let n=Math.min(Math.max(t,0),e.doc.content.size);e.setSelection(k.near(e.doc.resolve(n),-1))}function mT(e,t){let n=[...t].sort((e,t)=>t.from-e.from);for(let t of n)e.delete(t.from,t.to)}function hT(e,t){let n=iT(e.doc,t),r=[...aT(e.doc,t),...n?[n]:[]];if(r.length===0)return null;let i=e.tr;return mT(i,r),dT(e,i),fT(i,n),pT(i,r[0]?.from??0),i.scrollIntoView(),i}function gT(e,t){let n=e.doc.nodeAt(t.from);if(!n||n.type.name!==`footnoteReference`)return null;let r=ax(n.attrs.label);if(!r)return null;let i=aT(e.doc,r),a=iT(e.doc,r),o=i.length<=1?[t,...a?[a]:[]]:[t],s=e.tr;return mT(s,o),dT(e,s),fT(s,i.length<=1?a:null),pT(s,t.from),s.scrollIntoView(),s}function _T(e,t){let{selection:n}=e;if(n instanceof A)return n.node.type.name===`footnoteReference`?{from:n.from,to:n.to}:null;if(!n.empty)return null;let{$from:r}=n,i=t===`backward`?r.nodeBefore:r.nodeAfter;if(!i||i.type.name!==`footnoteReference`)return null;let a=t===`backward`?n.from-i.nodeSize:n.from;return{from:a,to:a+i.nodeSize}}function vT(e){let{selection:t}=e;if(t instanceof A)return t.node.type.name===`footnoteDefinition`?ax(t.node.attrs.label):null;if(!t.empty)return null;let{$from:n}=t,r=-1;for(let e=n.depth;e>0;--e)if(n.node(e).type.name===`footnoteDefinition`){r=e;break}return r===-1||!(n.parent.type.name===`paragraph`&&n.parentOffset===0&&n.index(r)===0)?null:ax(n.node(r).attrs.label)}function yT(e,t,n,r,i){let a=oT(e,t);if(!a)return!1;let o=[a];n&&o.push(e.schema.text(n));let s=e.tr;return s.replaceWith(r,i,E.fromArray(o)),uT(e,s,t)!==null}function bT(e,t){let n=sT(e,t);if(!n)return!1;let{$from:r}=e.selection;if(r.depth!==1||r.parent.type.name!==`paragraph`)return!1;let i=e.tr.replaceWith(r.before(),r.after(),n);return lT(i,r.before()+n.nodeSize),cT(i,r.before()),i.scrollIntoView(),!0}function xT(e,t){let n=sT(e,t);if(!n)return!1;let{$from:r}=e.selection;if(r.parent.type.name!==`paragraph`||r.depth<2||r.node(r.depth-1).type.name!==`footnoteDefinition`)return!1;let i=r.depth,a=r.before(i),o=r.after(i),s=i-1,c=r.node(s),l=r.after(s),u=e.tr;c.childCount===1?u.delete(a+1,o-1):u.delete(a,o);let d=u.mapping.map(l);return u.insert(d,n),lT(u,d+n.nodeSize),cT(u,d),u.scrollIntoView(),!0}function ST(e){let{$from:t}=e.selection;for(let e=t.depth;e>0;--e)if(t.node(e).type.name===`footnoteDefinition`)return!0;return!1}function CT(e){let{selection:t}=e,{$from:n}=t;if(!t.empty||ST(e)||!n.parent.inlineContent||n.parent.type.name!==`paragraph`||n.parentOffset!==n.parent.content.size)return null;let r=n.parent.textBetween(0,n.parentOffset,void 0,``).match($w),i=ax(r?.[1]);return!r||!i?null:{label:i,from:t.from-r[0].length,to:t.from}}function wT(e){let t=CT(e);if(t){let n=oT(e,t.label);if(!n)return null;let r=e.tr.replaceWith(t.from,t.to,n),i=uT(e,r,t.label);return i===null?null:(cT(r,i),r.scrollIntoView(),r)}return null}function TT(){return[new qd({find:Qw,handler:({state:e,match:t})=>{let n=ax(t[1]);if(!n)return null;let{$from:r}=e.selection;return r.depth!==1||r.parent.type.name!==`paragraph`?xT(e,n)?void 0:null:bT(e,n)?void 0:null}}),new qd({find:Zw,handler:({state:e,range:t,match:n})=>{let r=ax(n[1]),i=n[2]??``;return!r||!i||!e.selection.$from.parent.inlineContent?null:yT(e,r,i,t.from,t.to)?void 0:null}})]}var ET=N.create({name:`footnotes`,addCommands(){return{insertFootnote:()=>({state:e,dispatch:t})=>{if(!e.selection.$from.parent.inlineContent)return!1;let n=tT(e.doc),r=oT(e,n),i=sT(e,n);if(!r||!i)return!1;let a=nT(e.doc),o=e.tr.replaceSelectionWith(r,!1),s=o.mapping.map(a);return o.insert(s,i),lT(o,s+i.nodeSize),cT(o,s),t&&t(o.scrollIntoView()),!0}}},addInputRules(){return TT()},addKeyboardShortcuts(){return{Enter:({editor:e})=>{let t=wT(e.state);return t?(e.view.dispatch(t),!0):!1},Backspace:({editor:e})=>{let t=vT(e.state);if(t){let n=hT(e.state,t);return n?(e.view.dispatch(n),!0):!1}let n=_T(e.state,`backward`);if(!n)return!1;let r=gT(e.state,n);return r?(e.view.dispatch(r),!0):!1},Delete:({editor:e})=>{let t=_T(e.state,`forward`);if(!t)return!1;let n=gT(e.state,t);return n?(e.view.dispatch(n),!0):!1}}}});function DT(e,t,n=`paragraph`){let{$to:r}=e.selection,i=r.end();if(r.nodeAfter)r.nodeAfter.isTextblock?e.setSelection(k.create(e.doc,r.pos+1)):r.nodeAfter.isBlock?e.setSelection(A.create(e.doc,r.pos)):e.setSelection(k.create(e.doc,r.pos));else{let a=(t.nodes[n]??r.parent.type.contentMatch.defaultType)?.create();a&&(e.insert(i,a),e.setSelection(k.create(e.doc,i+1)))}e.scrollIntoView()}var OT={regular:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="3" y="3" width="10" height="10" rx="1.5"/></svg>`,wide:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="1.5" y="4" width="13" height="8" rx="1.5"/></svg>`,full:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="0.75" y="3" width="14.5" height="10" rx="1"/><path d="M4 8h8M4 6l-1.5 2L4 10M12 6l1.5 2L12 10"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,replace:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>`,expand:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6"/><path d="M9 21H3v-6"/><path d="M21 3l-7 7"/><path d="M3 21l7-7"/></svg>`},kT=class{dom;img;figcaption;captionInput;altBtn;toolbar;captionBar;layoutBtns=new Map;node;view;getPos;editor;editingAlt=!1;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`figure`);i.className=`tiptap-image-figure`,i.dataset.selected=`false`,i.dataset.layout=String(e.attrs.layout||`regular`),this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-image-container`,i.appendChild(a);let o=document.createElement(`img`);o.src=String(e.attrs.src??``),o.alt=String(e.attrs.alt??``),e.attrs.title&&(o.title=String(e.attrs.title)),o.draggable=!1,a.appendChild(o),this.img=o;let s=document.createElement(`div`);s.className=`tiptap-image-toolbar`,a.appendChild(s),this.toolbar=s;let c=[[`regular`,OT.regular,`Content width`],[`wide`,OT.wide,`Wide — max 1200px`],[`full`,OT.full,`Full width — edge to edge`]];for(let[t,n,r]of c){this.layoutBtns.size>0&&s.appendChild(this.sep());let i=document.createElement(`button`);i.type=`button`,i.innerHTML=n,i.title=r,i.dataset.layout=t,t===(e.attrs.layout||`regular`)&&(i.className=`is-active`),i.addEventListener(`mousedown`,e=>{e.preventDefault(),this.updateAttrs({layout:t})}),s.appendChild(i),this.layoutBtns.set(t,i)}s.appendChild(this.sep());let l=this.iconBtn(OT.link,`Add link`);l.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleLink()}),s.appendChild(l),s.appendChild(this.sep());let u=this.iconBtn(OT.replace,`Replace image`);u.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleReplace()}),s.appendChild(u),s.appendChild(this.sep());let d=this.iconBtn(OT.expand,`Preview fullscreen`);d.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleExpand()}),s.appendChild(d);let f=document.createElement(`div`);f.className=`tiptap-image-caption-bar`,i.appendChild(f),this.captionBar=f;let p=document.createElement(`input`);p.type=`text`,p.placeholder=`Add a caption…`,p.value=String(e.attrs.caption??``),p.addEventListener(`input`,()=>{this.editingAlt?this.updateAttrs({alt:p.value}):this.updateAttrs({caption:p.value})}),p.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.view.focus())}),f.appendChild(p),this.captionInput=p;let m=document.createElement(`button`);m.type=`button`,m.className=`tiptap-image-alt-btn`,m.textContent=`Alt`,m.addEventListener(`mousedown`,e=>{e.preventDefault(),this.toggleAltMode()}),f.appendChild(m),this.altBtn=m;let h=document.createElement(`figcaption`);h.className=`tiptap-image-figcaption`,h.textContent=String(e.attrs.caption??``),i.appendChild(h),this.figcaption=h}update(e){if(e.type!==this.node.type)return!1;this.node=e,this.img.src=String(e.attrs.src??``),this.img.alt=String(e.attrs.alt??``),this.img.title=String(e.attrs.title??``),this.dom.dataset.layout=String(e.attrs.layout||`regular`),this.layoutBtns.forEach((t,n)=>{t.classList.toggle(`is-active`,n===(e.attrs.layout||`regular`))});let t=String(e.attrs.caption??``);return this.figcaption.textContent=t,document.activeElement!==this.captionInput&&(this.editingAlt?this.captionInput.value=String(e.attrs.alt??``):this.captionInput.value=t),!0}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`,this.editingAlt=!1,this.altBtn.classList.remove(`is-active`),this.captionInput.placeholder=`Add a caption…`,this.captionInput.value=String(this.node.attrs.caption??``)}stopEvent(e){let t=e.target;return!!(t.closest(`.tiptap-image-toolbar`)||t.closest(`.tiptap-image-caption-bar`))}ignoreMutation(){return!0}destroy(){}sep(){let e=document.createElement(`span`);return e.className=`tiptap-toolbar-sep`,e}iconBtn(e,t){let n=document.createElement(`button`);return n.type=`button`,n.innerHTML=e,n.title=t,n}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}handleLink(){if(String(this.node.attrs.href??``))this.updateAttrs({href:``});else{let e=globalThis.prompt(`Enter URL`);e&&this.updateAttrs({href:e})}}handleReplace(){let e=document.createElement(`input`);e.type=`file`,e.accept=`image/*`,e.addEventListener(`change`,async()=>{let t=e.files?.[0];if(t)try{let e=await dw(t);this.updateAttrs({src:e.url})}catch{}}),e.click()}handleExpand(){let e=document.querySelector(`jant-media-lightbox`);e&&e.open([{url:String(this.node.attrs.src??``),alt:String(this.node.attrs.alt??``)}],0)}toggleAltMode(){this.editingAlt=!this.editingAlt,this.altBtn.classList.toggle(`is-active`,this.editingAlt),this.editingAlt?(this.captionInput.placeholder=`Add alt text…`,this.captionInput.value=String(this.node.attrs.alt??``)):(this.captionInput.placeholder=`Add a caption…`,this.captionInput.value=String(this.node.attrs.caption??``)),this.captionInput.focus()}},AT=Wf.create({name:`image`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{src:{default:``},alt:{default:``},title:{default:``},caption:{default:``},href:{default:``},layout:{default:`regular`}}},parseHTML(){return[{tag:`figure[data-image]`,getAttrs(e){let t=e,n=t.querySelector(`img`),r=t.querySelector(`figcaption`),i=t.querySelector(`a`);return{src:n?.getAttribute(`src`)??``,alt:n?.getAttribute(`alt`)??``,title:n?.getAttribute(`title`)??``,caption:r?.textContent??``,href:i?.getAttribute(`href`)??``,layout:t.dataset.layout??`regular`}}},{tag:`figure`,getAttrs(e){let t=e,n=t.querySelector(`img`);if(!n)return!1;let r=t.querySelector(`figcaption`),i=t.querySelector(`a`);return{src:n.getAttribute(`src`)??``,alt:n.getAttribute(`alt`)??``,title:n.getAttribute(`title`)??``,caption:r?.textContent??``,href:i?.getAttribute(`href`)??``,layout:t.dataset.layout??`regular`}}},{tag:`img[src]`,getAttrs(e){let t=e;return{src:t.getAttribute(`src`)??``,alt:t.getAttribute(`alt`)??``,title:t.getAttribute(`title`)??``}}}]},renderHTML({node:e}){let t={};e.attrs.layout&&e.attrs.layout!==`regular`&&(t[`data-layout`]=e.attrs.layout),t[`data-image`]=``;let n={src:e.attrs.src};e.attrs.alt&&(n.alt=e.attrs.alt),e.attrs.title&&(n.title=e.attrs.title);let r=[`img`,n],i=[];return e.attrs.href?i.push([`a`,{href:e.attrs.href},r]):i.push(r),e.attrs.caption&&i.push([`figcaption`,{},e.attrs.caption]),[`figure`,t,...i]},parseMarkdown:(e,t)=>t.createNode(`image`,{src:e.href,title:e.title??``,alt:e.text??``}),renderMarkdown:e=>yx(e.attrs??{}),addCommands(){return{setImage:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let{$to:r}=n.selection,i=t();return vd(n.selection)?i.insertContentAt(r.pos,{type:this.name,attrs:e}):i.insertContent({type:this.name,attrs:e}),i.command(({state:e,tr:t,dispatch:n})=>(n&&DT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new kT(e,t,n,r)}}),jT=`<!--more-->`,MT=Wf.create({name:`moreBreak`,group:`block`,atom:!0,selectable:!0,draggable:!1,parseHTML(){return[{tag:`div[data-more-break]`}]},renderHTML(){return[`div`,{"data-more-break":``,class:`tiptap-more-break`},`Read More ↓`]},renderText(){return jT},parseMarkdown:(e,t)=>t.createNode(`moreBreak`),renderMarkdown:()=>jT,markdownTokenizer:Px(),addCommands(){return{insertMoreBreak:()=>({chain:e,state:t})=>{if(!Af(t,t.schema.nodes[this.name]))return!1;let{$to:n}=t.selection,r=e();return vd(t.selection)?r.insertContentAt(n.pos,{type:this.name}):r.insertContent({type:this.name}),r.command(({state:e,tr:t,dispatch:n})=>(n&&DT(t,e.schema),!0)).run()}}}}),NT=class{dom;node;view;getPos;editor;providerLabel;urlLink;captionInput;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`div`);i.className=`tiptap-embed-card`,i.dataset.selected=`false`,this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-embed-card-header`,i.appendChild(a);let o=document.createElement(`span`);o.className=`tiptap-embed-card-provider`,a.appendChild(o),this.providerLabel=o;let s=document.createElement(`span`);s.className=`tiptap-embed-card-actions`,a.appendChild(s);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Edit`,c.className=`tiptap-embed-card-btn`,c.addEventListener(`mousedown`,e=>{e.preventDefault(),this.requestEdit()}),s.appendChild(c);let l=document.createElement(`a`);l.className=`tiptap-embed-card-url`,l.target=`_blank`,l.rel=`noopener noreferrer`,i.appendChild(l),this.urlLink=l;let u=document.createElement(`input`);u.type=`text`,u.placeholder=`Add a caption…`,u.className=`tiptap-embed-card-caption`,u.value=String(e.attrs.caption??``),u.addEventListener(`input`,()=>{this.updateAttrs({caption:u.value})}),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.view.focus())}),i.appendChild(u),this.captionInput=u,this.refresh()}update(e){return e.type===this.node.type?(this.node=e,document.activeElement!==this.captionInput&&(this.captionInput.value=String(e.attrs.caption??``)),this.refresh(),!0):!1}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`}stopEvent(e){let t=e.target;return!!(t.closest(`.tiptap-embed-card-header`)||t.closest(`.tiptap-embed-card-caption`))}ignoreMutation(){return!0}destroy(){}refresh(){let e=String(this.node.attrs.url??``),t=String(this.node.attrs.providerName??``)||PT(e);this.providerLabel.textContent=t,this.urlLink.href=e,this.urlLink.textContent=e}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}requestEdit(){iC({initialUrl:String(this.node.attrs.url??``),initialCaption:String(this.node.attrs.caption??``)}).then(e=>{if(!e)return;let t=this.getPos();if(t===void 0)return;if(e.kind===`link`){let n=t,r=t+this.node.nodeSize;this.editor.chain().focus().insertContentAt({from:n,to:r},{type:`paragraph`,content:[{type:`text`,text:e.url,marks:[{type:`link`,attrs:{href:e.url}}]}]}).run();return}if(e.kind!==`embed`)return;let n=nC(e.url),r=n?{url:n.url||e.url,provider:n.provider,providerName:n.providerName,src:n.src,orientation:n.orientation,heightPx:n.heightPx??null,sandbox:n.sandbox,allow:n.allow??``,caption:e.caption??``}:{...this.node.attrs,url:e.url,caption:e.caption??``},i=this.view.state.tr.setNodeMarkup(t,void 0,r);this.view.dispatch(i)})}};function PT(e){if(!e)return`Embed`;try{return new URL(e.startsWith(`http`)?e:`https://${e}`).hostname}catch{return`Embed`}}var FT=Wf.create({name:`embed`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{url:{default:``},provider:{default:``},providerName:{default:``},src:{default:``},orientation:{default:`landscape`},heightPx:{default:null},sandbox:{default:``},allow:{default:``},caption:{default:``}}},parseHTML(){return[{tag:`figure[data-jant-node="embed"]`,getAttrs(e){let t=e;return{url:t.getAttribute(`data-url`)??``,provider:t.getAttribute(`data-provider`)??``,providerName:t.getAttribute(`data-provider-name`)??``,src:t.getAttribute(`data-src`)??``,orientation:t.getAttribute(`data-orientation`)??`landscape`}}}]},renderHTML({node:e}){let t={"data-jant-node":`embed`};return e.attrs.provider&&(t[`data-provider`]=String(e.attrs.provider)),e.attrs.providerName&&(t[`data-provider-name`]=String(e.attrs.providerName)),e.attrs.url&&(t[`data-url`]=String(e.attrs.url)),e.attrs.src&&(t[`data-src`]=String(e.attrs.src)),e.attrs.orientation&&(t[`data-orientation`]=String(e.attrs.orientation)),[`figure`,t]},parseMarkdown:(e,t)=>{let n=typeof e.url==`string`?e.url:``,r=e.attrs&&typeof e.attrs==`object`?e.attrs:{};return t.createNode(`embed`,{url:n,caption:r.caption??``})},renderMarkdown:e=>{let t=e.attrs??{},n=typeof t.url==`string`?t.url.trim():``;if(!n)return``;let r=[n],i=typeof t.caption==`string`?t.caption.trim():``;return i&&r.push(`caption=${i}`),["```jant-embed",...r,"```"].join(`
306
- `)},markdownTokenizer:Mx(),addCommands(){return{setEmbed:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r=nC(e.url),i=r?{url:r.url||e.url,provider:r.provider,providerName:r.providerName,src:r.src,orientation:r.orientation,heightPx:r.heightPx??null,sandbox:r.sandbox,allow:r.allow??``,caption:e.caption??``}:{url:e.url,caption:e.caption??``},{$to:a}=n.selection,o=t();return vd(n.selection)?o.insertContentAt(a.pos,{type:this.name,attrs:i}):o.insertContent({type:this.name,attrs:i}),o.command(({state:e,tr:t,dispatch:n})=>(n&&DT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new NT(e,t,n,r)}}),IT=class{dom;node;view;getPos;editor;textarea;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`div`);i.className=`tiptap-html-block-card`,i.dataset.selected=`false`,this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-html-block-header`,a.textContent=`Raw HTML`,i.appendChild(a);let o=document.createElement(`textarea`);o.className=`tiptap-html-block-textarea`,o.spellcheck=!1,o.value=String(e.attrs.html??``),o.rows=Math.max(3,o.value.split(`
307
- `).length),o.addEventListener(`input`,()=>{this.updateAttrs({html:o.value}),this.autoGrow()}),i.appendChild(o),this.textarea=o;let s=document.createElement(`p`);s.className=`tiptap-html-block-hint`,s.textContent=`Renders on the published page only.`,i.appendChild(s),queueMicrotask(()=>this.autoGrow())}update(e){return e.type===this.node.type?(this.node=e,document.activeElement!==this.textarea&&(this.textarea.value=String(e.attrs.html??``),this.autoGrow()),!0):!1}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`}stopEvent(e){return e.target.closest(`.tiptap-html-block-textarea`)!==null}ignoreMutation(){return!0}destroy(){}autoGrow(){this.textarea.style.height=`auto`,this.textarea.style.height=`${this.textarea.scrollHeight}px`}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}},LT=Wf.create({name:`htmlBlock`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{html:{default:``}}},parseHTML(){return[{tag:`div[data-jant-node="html-block"]`,getAttrs(e){return{html:e.textContent??``}}}]},renderHTML({node:e}){return[`div`,{"data-jant-node":`html-block`},String(e.attrs.html??``)]},parseMarkdown:(e,t)=>{let n=typeof e.html==`string`?e.html:``;return t.createNode(`htmlBlock`,{html:n})},renderMarkdown:e=>["```jant-html",typeof e.attrs?.html==`string`?e.attrs.html:``,"```"].join(`
308
- `),markdownTokenizer:Nx(),addCommands(){return{setHtmlBlock:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r={html:e.html},{$to:i}=n.selection,a=t();return vd(n.selection)?a.insertContentAt(i.pos,{type:this.name,attrs:r}):a.insertContent({type:this.name,attrs:r}),a.command(({state:e,tr:t,dispatch:n})=>(n&&DT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new IT(e,t,n,r)}}),RT=/^https?:\/\/\S+$/i,zT=new Pr(`jantEmbedPaste`),BT=N.create({name:`embedPaste`,addProseMirrorPlugins(){let e=this.editor;return[new j({key:zT,props:{handlePaste(t,n){let r=n.clipboardData;if(!r)return!1;let i=r.getData(`text/plain`)?.trim()??``;if(!i||!RT.test(i))return!1;let{selection:a}=t.state;if(!a.empty)return!1;let o=a.$from,s=o.parent;if(s.type.name!==`paragraph`||s.content.size>0||!rC(i)||!nC(i))return!1;n.preventDefault();let c=t.state.schema.marks.link,l=o.pos,u=t.state.tr.insertText(i,l);return c&&u.addMark(l,l+i.length,c.create({href:i})),t.dispatch(u),queueMicrotask(()=>{let n=l,r=l+i.length,a=Fv(t.state.tr).delete(n,r);t.dispatch(a),e.commands.setEmbed({url:i})}),!0}}})]}});function VT(e){return e instanceof E?e:e.content}function HT(e){if(/data-vscode-/i.test(e))return!0;let t=e.match(/^[^<]*(?:<(?:meta|html|head|body)\b[^>]*>\s*)*<(?:div|pre)\b[^>]*style="([^"]*)"/i);if(t){let e=t[1]??``,n=/font-family:[^;"]*\b(?:monospace|Menlo|Monaco|Consolas|Courier|JetBrains Mono|Fira Code|Source Code Pro)\b/i.test(e),r=/white-space:\s*pre\b/i.test(e);if(n&&r)return!0}return!1}var UT=N.create({name:`markdownClipboard`,addProseMirrorPlugins(){return[new j({props:{handlePaste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`)??``;if(!n||!HT(n))return!1;let r=t.clipboardData?.getData(`text/plain`)?.trim()??``;if(!r||!this.editor.markdown)return!1;let i=this.editor.markdown.parse(r);if(i.type!==`doc`||!i.content)return!1;let a=ql(i,e.state.schema,{slice:!1}),o=D.maxOpen(VT(a));return t.preventDefault(),e.dispatch(e.state.tr.replaceSelection(o).scrollIntoView()),!0},clipboardTextParser:(e,t,n,r)=>{if(!e.trim()||!this.editor.markdown)return D.empty;let i=this.editor.markdown.parse(e);if(i.type!==`doc`||!i.content)return D.empty;if(i.content.length===1&&i.content[0]?.type===`paragraph`){let e=i.content[0];if(!e?.content)return D.empty;let t=ql(e.content,r.state.schema,{slice:!0});return D.maxOpen(VT(t))}let a=ql(i,r.state.schema,{slice:!1});return D.maxOpen(VT(a))}}})]}}),WT=N.create({name:`reclaimModEnter`,priority:1e3,addKeyboardShortcuts(){return{"Mod-Enter":()=>!0}}});function GT(e={}){return[...Vx(),Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??``}),WT,Kw,Jw,UT,zw,Xw,Iw.configure({toolbarMode:`compose`}),jw]}function KT(e={}){return[...Vx({imageExtension:AT,moreBreakExtension:MT,embedExtension:FT,htmlBlockExtension:LT}),WT,Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??`Write something…`}),ET,Kw,Jw,UT,IC,BT,ww.configure(e.pasteMedia??{}),Iw.configure({toolbarMode:e.toolbarMode??`default`}),jw,zw,Xw,Vw]}function qT(e){try{let t=JSON.parse(e);return t.type===`doc`?Jx(t).trimEnd():``}catch{return``}}function JT(e){return new Tf({element:e.element,extensions:KT({placeholder:e.placeholder,toolbarMode:e.toolbarMode,pasteMedia:e.pasteMedia}),content:e.content??void 0,editorProps:{scrollMargin:{top:5,right:5,bottom:80,left:5},scrollThreshold:{top:5,right:5,bottom:80,left:5}},onUpdate:({editor:t})=>{e.onUpdate?.(fx(t.getJSON()))},onFocus:()=>{e.onFocus?.()},onSelectionUpdate:({editor:t})=>{e.onSelectionUpdate?.({from:t.state.selection.from,to:t.state.selection.to})}})}function YT(e){return qT(JSON.stringify(e))}function XT(e){let t=e.content?qx(e.content):void 0;return new Tf({element:e.element,extensions:GT({placeholder:e.placeholder}),content:t,onUpdate:({editor:t})=>{e.onUpdate?.(YT(t.getJSON()))}})}var ZT=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),QT=`[data-editor-floating-ui]`,$T=`(max-width: 700px), (max-height: 760px), (hover: none) and (pointer: coarse)`,eE={drafts:`
305
+ `,m);if(e===-1||e>=d)break;f.push(e+1),m=e+1}let h=t.tr,g=0,_=0;for(let e=0;e<f.length;e++){let t=f[e],n=l.slice(t),r=n.startsWith(Ww)?2:n.startsWith(` `)?1:0;if(r>0){let n=c+t+g;h=h.delete(n,n+r),g-=r,e===0&&(_=r)}}if(g<0){let e=Math.max(i-_,c),t=a+g;h.setSelection(k.create(h.doc,e,Math.max(t,e)))}return n(h),!0}return!1}}}}),Kw=/\[([^\]]+)\]\(((?:[^()\s]|\([^()\s]*\))+)\)/,qw=RegExp(Kw.source+`$`),Jw=RegExp(Kw.source+`\\s$`),Yw=/((?:https?:\/\/|mailto:)[^\s<]+)\s$/,Xw=N.create({name:`linkInputRules`,addInputRules(){let e=this.editor.schema.marks.link;if(!e)return[];function n(n,r,i,a){let o=i[1]?.trim(),s=t(i[2]??``);if(!o||!s)return null;let c=a?o+a:o;n.tr.insertText(c,r.from,r.to),n.tr.addMark(r.from,r.from+o.length,e.create({href:s})),n.tr.removeStoredMark(e)}return[new qd({find:Yw,handler:({state:n,range:r,match:i})=>{let a=t(i[1]??``);if(!a)return null;let o=r.from+a.length;if(n.doc.rangeHasMark(r.from,o,e))return null;n.tr.addMark(r.from,o,e.create({href:a})),n.tr.removeStoredMark(e)}}),new qd({find:qw,handler:({state:e,range:t,match:r})=>{n(e,t,r,``)}}),new qd({find:Jw,handler:({state:e,range:t,match:r})=>{n(e,t,r,` `)}})]}});function Zw(e){return new qd({find:e.find,handler:({state:t,range:n,match:r})=>{let i=Pu(e.getAttributes,void 0,r)||{},a=t.tr.delete(n.from,n.to),o=a.doc.resolve(n.from).blockRange(),s=o&&On(o,e.type,i);if(!s)return null;a.wrap(o,s)}})}var Qw=N.create({name:`wrappingInputRules`,priority:1e3,addInputRules(){let{schema:e}=this.editor,t=[],n=e.nodes.blockquote;n&&t.push(Zw({find:/^\s*>\s$/,type:n}));let r=e.nodes.bulletList;r&&t.push(Zw({find:/^\s*([-+*])\s$/,type:r}));let i=e.nodes.orderedList;return i&&t.push(Zw({find:/^(\d+)\.\s$/,type:i,getAttributes:e=>({start:Number(e[1])})})),t}});function $w(e,t){let{state:n}=e,r=n.schema.nodes.paragraph;if(!r)return!1;let{selection:i}=n,{$from:a,$to:o}=i,s;s=a.depth===0?t===`above`?i.from:i.to:t===`above`?a.before(1):o.after(1);let c=n.tr.insert(s,r.create());return c.setSelection(k.create(c.doc,s+1)),e.view.dispatch(c.scrollIntoView()),!0}var eT=N.create({name:`insertParagraphAround`,addKeyboardShortcuts(){let e=({editor:e})=>{let{state:t}=e,{selection:n}=t;if(!n.empty)return!1;let{$from:r}=n;if(r.depth<1||r.pos!==r.depth)return!1;let i=t.doc.firstChild;return!i||i.type.name===`paragraph`?!1:$w(e,`above`)};return{ArrowUp:e,ArrowLeft:e,"Mod-Shift-Enter":({editor:e})=>$w(e,`above`),"Mod-Alt-Enter":({editor:e})=>$w(e,`below`)}}}),tT=/\[\^([^\]\n]+)\]([ \t.,!?;)]$)/,nT=/^\[\^([^\]\n]+)\]: $/,rT=/\[\^([^\]\n]+)\]$/;function iT(e){let t=new Set;return e.descendants(e=>{if(e.type.name!==`footnoteReference`&&e.type.name!==`footnoteDefinition`)return!0;let n=ax(e.attrs.label);return n&&t.add(ox(n)),!0}),t}function aT(e){let t=iT(e),n=1;for(;t.has(String(n));)n+=1;return String(n)}function oT(e){let t=e.content.size;return e.forEach((e,n)=>{e.type.name===`footnoteDefinition`&&(t=n+e.nodeSize)}),t}function sT(e,t){let n=ox(t),r=null;return e.forEach((e,t)=>{r===null&&e.type.name===`footnoteDefinition`&&ox(e.attrs.label)===n&&(r=t)}),r}function cT(e,t){let n=ox(t),r=null;return e.forEach((e,t)=>{r===null&&e.type.name===`footnoteDefinition`&&ox(e.attrs.label)===n&&(r={from:t,to:t+e.nodeSize})}),r}function lT(e,t){let n=ox(t),r=[];return e.descendants((e,t)=>(e.type.name===`footnoteReference`&&ox(e.attrs.label)===n&&r.push({from:t,to:t+e.nodeSize}),!0)),r}function uT(e,t){let n=e.schema.nodes.footnoteReference;return n?n.create({label:t}):null}function dT(e,t){let n=e.schema.nodes.footnoteDefinition,r=e.schema.nodes.paragraph;return!n||!r?null:n.create({label:t},[r.create()])}function fT(e,t){let n=Math.min(t+2,e.doc.content.size);e.setSelection(k.near(e.doc.resolve(n),1))}function pT(e,t){let n=null,r=null;e.doc.forEach((e,i)=>{i===t&&e.type.name===`paragraph`&&e.content.size===0&&(n=i,r=i+e.nodeSize)}),n!==null&&r!==null&&e.delete(n,r)}function mT(e,t,n){let r=sT(t.doc,n);if(r!==null)return r;let i=dT(e,n);if(!i)return null;let a=oT(t.doc);return t.insert(a,i),pT(t,a+i.nodeSize),a}function hT(e,t){if(t.doc.childCount>0)return;let n=e.schema.nodes.paragraph;n&&t.insert(0,n.create())}function gT(e,t){if(!t||e.doc.childCount<2)return;let n=e.doc.lastChild,r=e.doc.child(e.doc.childCount-2);n?.type.name===`paragraph`&&n.content.size===0&&r.type.name!==`footnoteDefinition`&&e.delete(e.doc.content.size-n.nodeSize,e.doc.content.size)}function _T(e,t){let n=Math.min(Math.max(t,0),e.doc.content.size);e.setSelection(k.near(e.doc.resolve(n),-1))}function vT(e,t){let n=[...t].sort((e,t)=>t.from-e.from);for(let t of n)e.delete(t.from,t.to)}function yT(e,t){let n=cT(e.doc,t),r=[...lT(e.doc,t),...n?[n]:[]];if(r.length===0)return null;let i=e.tr;return vT(i,r),hT(e,i),gT(i,n),_T(i,r[0]?.from??0),i.scrollIntoView(),i}function bT(e,t){let n=e.doc.nodeAt(t.from);if(!n||n.type.name!==`footnoteReference`)return null;let r=ax(n.attrs.label);if(!r)return null;let i=lT(e.doc,r),a=cT(e.doc,r),o=i.length<=1?[t,...a?[a]:[]]:[t],s=e.tr;return vT(s,o),hT(e,s),gT(s,i.length<=1?a:null),_T(s,t.from),s.scrollIntoView(),s}function xT(e,t){let{selection:n}=e;if(n instanceof A)return n.node.type.name===`footnoteReference`?{from:n.from,to:n.to}:null;if(!n.empty)return null;let{$from:r}=n,i=t===`backward`?r.nodeBefore:r.nodeAfter;if(!i||i.type.name!==`footnoteReference`)return null;let a=t===`backward`?n.from-i.nodeSize:n.from;return{from:a,to:a+i.nodeSize}}function ST(e){let{selection:t}=e;if(t instanceof A)return t.node.type.name===`footnoteDefinition`?ax(t.node.attrs.label):null;if(!t.empty)return null;let{$from:n}=t,r=-1;for(let e=n.depth;e>0;--e)if(n.node(e).type.name===`footnoteDefinition`){r=e;break}return r===-1||!(n.parent.type.name===`paragraph`&&n.parentOffset===0&&n.index(r)===0)?null:ax(n.node(r).attrs.label)}function CT(e,t,n,r,i){let a=uT(e,t);if(!a)return!1;let o=[a];n&&o.push(e.schema.text(n));let s=e.tr;return s.replaceWith(r,i,E.fromArray(o)),mT(e,s,t)!==null}function wT(e,t){let n=dT(e,t);if(!n)return!1;let{$from:r}=e.selection;if(r.depth!==1||r.parent.type.name!==`paragraph`)return!1;let i=e.tr.replaceWith(r.before(),r.after(),n);return pT(i,r.before()+n.nodeSize),fT(i,r.before()),i.scrollIntoView(),!0}function TT(e,t){let n=dT(e,t);if(!n)return!1;let{$from:r}=e.selection;if(r.parent.type.name!==`paragraph`||r.depth<2||r.node(r.depth-1).type.name!==`footnoteDefinition`)return!1;let i=r.depth,a=r.before(i),o=r.after(i),s=i-1,c=r.node(s),l=r.after(s),u=e.tr;c.childCount===1?u.delete(a+1,o-1):u.delete(a,o);let d=u.mapping.map(l);return u.insert(d,n),pT(u,d+n.nodeSize),fT(u,d),u.scrollIntoView(),!0}function ET(e){let{$from:t}=e.selection;for(let e=t.depth;e>0;--e)if(t.node(e).type.name===`footnoteDefinition`)return!0;return!1}function DT(e){let{selection:t}=e,{$from:n}=t;if(!t.empty||ET(e)||!n.parent.inlineContent||n.parent.type.name!==`paragraph`||n.parentOffset!==n.parent.content.size)return null;let r=n.parent.textBetween(0,n.parentOffset,void 0,``).match(rT),i=ax(r?.[1]);return!r||!i?null:{label:i,from:t.from-r[0].length,to:t.from}}function OT(e){let t=DT(e);if(t){let n=uT(e,t.label);if(!n)return null;let r=e.tr.replaceWith(t.from,t.to,n),i=mT(e,r,t.label);return i===null?null:(fT(r,i),r.scrollIntoView(),r)}return null}function kT(){return[new qd({find:nT,handler:({state:e,match:t})=>{let n=ax(t[1]);if(!n)return null;let{$from:r}=e.selection;return r.depth!==1||r.parent.type.name!==`paragraph`?TT(e,n)?void 0:null:wT(e,n)?void 0:null}}),new qd({find:tT,handler:({state:e,range:t,match:n})=>{let r=ax(n[1]),i=n[2]??``;return!r||!i||!e.selection.$from.parent.inlineContent?null:CT(e,r,i,t.from,t.to)?void 0:null}})]}var AT=N.create({name:`footnotes`,addCommands(){return{insertFootnote:()=>({state:e,dispatch:t})=>{if(!e.selection.$from.parent.inlineContent)return!1;let n=aT(e.doc),r=uT(e,n),i=dT(e,n);if(!r||!i)return!1;let a=oT(e.doc),o=e.tr.replaceSelectionWith(r,!1),s=o.mapping.map(a);return o.insert(s,i),pT(o,s+i.nodeSize),fT(o,s),t&&t(o.scrollIntoView()),!0}}},addInputRules(){return kT()},addKeyboardShortcuts(){return{Enter:({editor:e})=>{let t=OT(e.state);return t?(e.view.dispatch(t),!0):!1},Backspace:({editor:e})=>{let t=ST(e.state);if(t){let n=yT(e.state,t);return n?(e.view.dispatch(n),!0):!1}let n=xT(e.state,`backward`);if(!n)return!1;let r=bT(e.state,n);return r?(e.view.dispatch(r),!0):!1},Delete:({editor:e})=>{let t=xT(e.state,`forward`);if(!t)return!1;let n=bT(e.state,t);return n?(e.view.dispatch(n),!0):!1}}}});function jT(e,t,n=`paragraph`){let{$to:r}=e.selection,i=r.end();if(r.nodeAfter)r.nodeAfter.isTextblock?e.setSelection(k.create(e.doc,r.pos+1)):r.nodeAfter.isBlock?e.setSelection(A.create(e.doc,r.pos)):e.setSelection(k.create(e.doc,r.pos));else{let a=(t.nodes[n]??r.parent.type.contentMatch.defaultType)?.create();a&&(e.insert(i,a),e.setSelection(k.create(e.doc,i+1)))}e.scrollIntoView()}var MT={regular:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="3" y="3" width="10" height="10" rx="1.5"/></svg>`,wide:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="1.5" y="4" width="13" height="8" rx="1.5"/></svg>`,full:`<svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round"><rect x="0.75" y="3" width="14.5" height="10" rx="1"/><path d="M4 8h8M4 6l-1.5 2L4 10M12 6l1.5 2L12 10"/></svg>`,link:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"/><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"/></svg>`,replace:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16"/><path d="M16 16h5v5"/></svg>`,expand:`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M15 3h6v6"/><path d="M9 21H3v-6"/><path d="M21 3l-7 7"/><path d="M3 21l7-7"/></svg>`},NT=class{dom;img;figcaption;captionInput;altBtn;toolbar;captionBar;layoutBtns=new Map;node;view;getPos;editor;editingAlt=!1;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`figure`);i.className=`tiptap-image-figure`,i.dataset.selected=`false`,i.dataset.layout=String(e.attrs.layout||`regular`),this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-image-container`,i.appendChild(a);let o=document.createElement(`img`);o.src=String(e.attrs.src??``),o.alt=String(e.attrs.alt??``),e.attrs.title&&(o.title=String(e.attrs.title)),o.draggable=!1,a.appendChild(o),this.img=o;let s=document.createElement(`div`);s.className=`tiptap-image-toolbar`,a.appendChild(s),this.toolbar=s;let c=[[`regular`,MT.regular,`Content width`],[`wide`,MT.wide,`Wide — max 1200px`],[`full`,MT.full,`Full width — edge to edge`]];for(let[t,n,r]of c){this.layoutBtns.size>0&&s.appendChild(this.sep());let i=document.createElement(`button`);i.type=`button`,i.innerHTML=n,i.title=r,i.dataset.layout=t,t===(e.attrs.layout||`regular`)&&(i.className=`is-active`),i.addEventListener(`mousedown`,e=>{e.preventDefault(),this.updateAttrs({layout:t})}),s.appendChild(i),this.layoutBtns.set(t,i)}s.appendChild(this.sep());let l=this.iconBtn(MT.link,`Add link`);l.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleLink()}),s.appendChild(l),s.appendChild(this.sep());let u=this.iconBtn(MT.replace,`Replace image`);u.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleReplace()}),s.appendChild(u),s.appendChild(this.sep());let d=this.iconBtn(MT.expand,`Preview fullscreen`);d.addEventListener(`mousedown`,e=>{e.preventDefault(),this.handleExpand()}),s.appendChild(d);let f=document.createElement(`div`);f.className=`tiptap-image-caption-bar`,i.appendChild(f),this.captionBar=f;let p=document.createElement(`input`);p.type=`text`,p.placeholder=`Add a caption…`,p.value=String(e.attrs.caption??``),p.addEventListener(`input`,()=>{this.editingAlt?this.updateAttrs({alt:p.value}):this.updateAttrs({caption:p.value})}),p.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.view.focus())}),f.appendChild(p),this.captionInput=p;let m=document.createElement(`button`);m.type=`button`,m.className=`tiptap-image-alt-btn`,m.textContent=`Alt`,m.addEventListener(`mousedown`,e=>{e.preventDefault(),this.toggleAltMode()}),f.appendChild(m),this.altBtn=m;let h=document.createElement(`figcaption`);h.className=`tiptap-image-figcaption`,h.textContent=String(e.attrs.caption??``),i.appendChild(h),this.figcaption=h}update(e){if(e.type!==this.node.type)return!1;this.node=e,this.img.src=String(e.attrs.src??``),this.img.alt=String(e.attrs.alt??``),this.img.title=String(e.attrs.title??``),this.dom.dataset.layout=String(e.attrs.layout||`regular`),this.layoutBtns.forEach((t,n)=>{t.classList.toggle(`is-active`,n===(e.attrs.layout||`regular`))});let t=String(e.attrs.caption??``);return this.figcaption.textContent=t,document.activeElement!==this.captionInput&&(this.editingAlt?this.captionInput.value=String(e.attrs.alt??``):this.captionInput.value=t),!0}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`,this.editingAlt=!1,this.altBtn.classList.remove(`is-active`),this.captionInput.placeholder=`Add a caption…`,this.captionInput.value=String(this.node.attrs.caption??``)}stopEvent(e){let t=e.target;return!!(t.closest(`.tiptap-image-toolbar`)||t.closest(`.tiptap-image-caption-bar`))}ignoreMutation(){return!0}destroy(){}sep(){let e=document.createElement(`span`);return e.className=`tiptap-toolbar-sep`,e}iconBtn(e,t){let n=document.createElement(`button`);return n.type=`button`,n.innerHTML=e,n.title=t,n}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}handleLink(){if(String(this.node.attrs.href??``))this.updateAttrs({href:``});else{let e=globalThis.prompt(`Enter URL`);e&&this.updateAttrs({href:e})}}handleReplace(){let e=document.createElement(`input`);e.type=`file`,e.accept=`image/*`,e.addEventListener(`change`,async()=>{let t=e.files?.[0];if(t)try{let e=await dw(t);this.updateAttrs({src:e.url})}catch{}}),e.click()}handleExpand(){let e=document.querySelector(`jant-media-lightbox`);e&&e.open([{url:String(this.node.attrs.src??``),alt:String(this.node.attrs.alt??``)}],0)}toggleAltMode(){this.editingAlt=!this.editingAlt,this.altBtn.classList.toggle(`is-active`,this.editingAlt),this.editingAlt?(this.captionInput.placeholder=`Add alt text…`,this.captionInput.value=String(this.node.attrs.alt??``)):(this.captionInput.placeholder=`Add a caption…`,this.captionInput.value=String(this.node.attrs.caption??``)),this.captionInput.focus()}},PT=Wf.create({name:`image`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{src:{default:``},alt:{default:``},title:{default:``},caption:{default:``},href:{default:``},layout:{default:`regular`}}},parseHTML(){return[{tag:`figure[data-image]`,getAttrs(e){let t=e,n=t.querySelector(`img`),r=t.querySelector(`figcaption`),i=t.querySelector(`a`);return{src:n?.getAttribute(`src`)??``,alt:n?.getAttribute(`alt`)??``,title:n?.getAttribute(`title`)??``,caption:r?.textContent??``,href:i?.getAttribute(`href`)??``,layout:t.dataset.layout??`regular`}}},{tag:`figure`,getAttrs(e){let t=e,n=t.querySelector(`img`);if(!n)return!1;let r=t.querySelector(`figcaption`),i=t.querySelector(`a`);return{src:n.getAttribute(`src`)??``,alt:n.getAttribute(`alt`)??``,title:n.getAttribute(`title`)??``,caption:r?.textContent??``,href:i?.getAttribute(`href`)??``,layout:t.dataset.layout??`regular`}}},{tag:`img[src]`,getAttrs(e){let t=e;return{src:t.getAttribute(`src`)??``,alt:t.getAttribute(`alt`)??``,title:t.getAttribute(`title`)??``}}}]},renderHTML({node:e}){let t={};e.attrs.layout&&e.attrs.layout!==`regular`&&(t[`data-layout`]=e.attrs.layout),t[`data-image`]=``;let n={src:e.attrs.src};e.attrs.alt&&(n.alt=e.attrs.alt),e.attrs.title&&(n.title=e.attrs.title);let r=[`img`,n],i=[];return e.attrs.href?i.push([`a`,{href:e.attrs.href},r]):i.push(r),e.attrs.caption&&i.push([`figcaption`,{},e.attrs.caption]),[`figure`,t,...i]},parseMarkdown:(e,t)=>t.createNode(`image`,{src:e.href,title:e.title??``,alt:e.text??``}),renderMarkdown:e=>yx(e.attrs??{}),addCommands(){return{setImage:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let{$to:r}=n.selection,i=t();return vd(n.selection)?i.insertContentAt(r.pos,{type:this.name,attrs:e}):i.insertContent({type:this.name,attrs:e}),i.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new NT(e,t,n,r)}}),FT=`<!--more-->`,IT=Wf.create({name:`moreBreak`,group:`block`,atom:!0,selectable:!0,draggable:!1,parseHTML(){return[{tag:`div[data-more-break]`}]},renderHTML(){return[`div`,{"data-more-break":``,class:`tiptap-more-break`},`Read More ↓`]},renderText(){return FT},parseMarkdown:(e,t)=>t.createNode(`moreBreak`),renderMarkdown:()=>FT,markdownTokenizer:Px(),addCommands(){return{insertMoreBreak:()=>({chain:e,state:t})=>{if(!Af(t,t.schema.nodes[this.name]))return!1;let{$to:n}=t.selection,r=e();return vd(t.selection)?r.insertContentAt(n.pos,{type:this.name}):r.insertContent({type:this.name}),r.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}}}),LT=class{dom;node;view;getPos;editor;providerLabel;urlLink;captionInput;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`div`);i.className=`tiptap-embed-card`,i.dataset.selected=`false`,this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-embed-card-header`,i.appendChild(a);let o=document.createElement(`span`);o.className=`tiptap-embed-card-provider`,a.appendChild(o),this.providerLabel=o;let s=document.createElement(`span`);s.className=`tiptap-embed-card-actions`,a.appendChild(s);let c=document.createElement(`button`);c.type=`button`,c.textContent=`Edit`,c.className=`tiptap-embed-card-btn`,c.addEventListener(`mousedown`,e=>{e.preventDefault(),this.requestEdit()}),s.appendChild(c);let l=document.createElement(`a`);l.className=`tiptap-embed-card-url`,l.target=`_blank`,l.rel=`noopener noreferrer`,i.appendChild(l),this.urlLink=l;let u=document.createElement(`input`);u.type=`text`,u.placeholder=`Add a caption…`,u.className=`tiptap-embed-card-caption`,u.value=String(e.attrs.caption??``),u.addEventListener(`input`,()=>{this.updateAttrs({caption:u.value})}),u.addEventListener(`keydown`,e=>{e.key===`Enter`&&(e.preventDefault(),this.view.focus())}),i.appendChild(u),this.captionInput=u,this.refresh()}update(e){return e.type===this.node.type?(this.node=e,document.activeElement!==this.captionInput&&(this.captionInput.value=String(e.attrs.caption??``)),this.refresh(),!0):!1}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`}stopEvent(e){let t=e.target;return!!(t.closest(`.tiptap-embed-card-header`)||t.closest(`.tiptap-embed-card-caption`))}ignoreMutation(){return!0}destroy(){}refresh(){let e=String(this.node.attrs.url??``),t=String(this.node.attrs.providerName??``)||RT(e);this.providerLabel.textContent=t,this.urlLink.href=e,this.urlLink.textContent=e}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}requestEdit(){iC({initialUrl:String(this.node.attrs.url??``),initialCaption:String(this.node.attrs.caption??``)}).then(e=>{if(!e)return;let t=this.getPos();if(t===void 0)return;if(e.kind===`link`){let n=t,r=t+this.node.nodeSize;this.editor.chain().focus().insertContentAt({from:n,to:r},{type:`paragraph`,content:[{type:`text`,text:e.url,marks:[{type:`link`,attrs:{href:e.url}}]}]}).run();return}if(e.kind!==`embed`)return;let n=nC(e.url),r=n?{url:n.url||e.url,provider:n.provider,providerName:n.providerName,src:n.src,orientation:n.orientation,heightPx:n.heightPx??null,sandbox:n.sandbox,allow:n.allow??``,caption:e.caption??``}:{...this.node.attrs,url:e.url,caption:e.caption??``},i=this.view.state.tr.setNodeMarkup(t,void 0,r);this.view.dispatch(i)})}};function RT(e){if(!e)return`Embed`;try{return new URL(e.startsWith(`http`)?e:`https://${e}`).hostname}catch{return`Embed`}}var zT=Wf.create({name:`embed`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{url:{default:``},provider:{default:``},providerName:{default:``},src:{default:``},orientation:{default:`landscape`},heightPx:{default:null},sandbox:{default:``},allow:{default:``},caption:{default:``}}},parseHTML(){return[{tag:`figure[data-jant-node="embed"]`,getAttrs(e){let t=e;return{url:t.getAttribute(`data-url`)??``,provider:t.getAttribute(`data-provider`)??``,providerName:t.getAttribute(`data-provider-name`)??``,src:t.getAttribute(`data-src`)??``,orientation:t.getAttribute(`data-orientation`)??`landscape`}}}]},renderHTML({node:e}){let t={"data-jant-node":`embed`};return e.attrs.provider&&(t[`data-provider`]=String(e.attrs.provider)),e.attrs.providerName&&(t[`data-provider-name`]=String(e.attrs.providerName)),e.attrs.url&&(t[`data-url`]=String(e.attrs.url)),e.attrs.src&&(t[`data-src`]=String(e.attrs.src)),e.attrs.orientation&&(t[`data-orientation`]=String(e.attrs.orientation)),[`figure`,t]},parseMarkdown:(e,t)=>{let n=typeof e.url==`string`?e.url:``,r=e.attrs&&typeof e.attrs==`object`?e.attrs:{};return t.createNode(`embed`,{url:n,caption:r.caption??``})},renderMarkdown:e=>{let t=e.attrs??{},n=typeof t.url==`string`?t.url.trim():``;if(!n)return``;let r=[n],i=typeof t.caption==`string`?t.caption.trim():``;return i&&r.push(`caption=${i}`),["```jant-embed",...r,"```"].join(`
306
+ `)},markdownTokenizer:Mx(),addCommands(){return{setEmbed:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r=nC(e.url),i=r?{url:r.url||e.url,provider:r.provider,providerName:r.providerName,src:r.src,orientation:r.orientation,heightPx:r.heightPx??null,sandbox:r.sandbox,allow:r.allow??``,caption:e.caption??``}:{url:e.url,caption:e.caption??``},{$to:a}=n.selection,o=t();return vd(n.selection)?o.insertContentAt(a.pos,{type:this.name,attrs:i}):o.insertContent({type:this.name,attrs:i}),o.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new LT(e,t,n,r)}}),BT=class{dom;node;view;getPos;editor;textarea;constructor(e,t,n,r){this.node=e,this.view=t,this.getPos=n,this.editor=r;let i=document.createElement(`div`);i.className=`tiptap-html-block-card`,i.dataset.selected=`false`,this.dom=i;let a=document.createElement(`div`);a.className=`tiptap-html-block-header`,a.textContent=`Raw HTML`,i.appendChild(a);let o=document.createElement(`textarea`);o.className=`tiptap-html-block-textarea`,o.spellcheck=!1,o.value=String(e.attrs.html??``),o.rows=Math.max(3,o.value.split(`
307
+ `).length),o.addEventListener(`input`,()=>{this.updateAttrs({html:o.value}),this.autoGrow()}),i.appendChild(o),this.textarea=o;let s=document.createElement(`p`);s.className=`tiptap-html-block-hint`,s.textContent=`Renders on the published page only.`,i.appendChild(s),queueMicrotask(()=>this.autoGrow())}update(e){return e.type===this.node.type?(this.node=e,document.activeElement!==this.textarea&&(this.textarea.value=String(e.attrs.html??``),this.autoGrow()),!0):!1}selectNode(){this.dom.dataset.selected=`true`}deselectNode(){this.dom.dataset.selected=`false`}stopEvent(e){return e.target.closest(`.tiptap-html-block-textarea`)!==null}ignoreMutation(){return!0}destroy(){}autoGrow(){this.textarea.style.height=`auto`,this.textarea.style.height=`${this.textarea.scrollHeight}px`}updateAttrs(e){let t=this.getPos();if(t===void 0)return;let n=this.view.state.tr.setNodeMarkup(t,void 0,{...this.node.attrs,...e});this.view.dispatch(n)}},VT=Wf.create({name:`htmlBlock`,group:`block`,atom:!0,selectable:!0,draggable:!0,addAttributes(){return{html:{default:``}}},parseHTML(){return[{tag:`div[data-jant-node="html-block"]`,getAttrs(e){return{html:e.textContent??``}}}]},renderHTML({node:e}){return[`div`,{"data-jant-node":`html-block`},String(e.attrs.html??``)]},parseMarkdown:(e,t)=>{let n=typeof e.html==`string`?e.html:``;return t.createNode(`htmlBlock`,{html:n})},renderMarkdown:e=>["```jant-html",typeof e.attrs?.html==`string`?e.attrs.html:``,"```"].join(`
308
+ `),markdownTokenizer:Nx(),addCommands(){return{setHtmlBlock:e=>({chain:t,state:n})=>{if(!Af(n,n.schema.nodes[this.name]))return!1;let r={html:e.html},{$to:i}=n.selection,a=t();return vd(n.selection)?a.insertContentAt(i.pos,{type:this.name,attrs:r}):a.insertContent({type:this.name,attrs:r}),a.command(({state:e,tr:t,dispatch:n})=>(n&&jT(t,e.schema),!0)).run()}}},addNodeView(){return({node:e,view:t,getPos:n,editor:r})=>new BT(e,t,n,r)}}),HT=/^https?:\/\/\S+$/i,UT=new Pr(`jantEmbedPaste`),WT=N.create({name:`embedPaste`,addProseMirrorPlugins(){let e=this.editor;return[new j({key:UT,props:{handlePaste(t,n){let r=n.clipboardData;if(!r)return!1;let i=r.getData(`text/plain`)?.trim()??``;if(!i||!HT.test(i))return!1;let{selection:a}=t.state;if(!a.empty)return!1;let o=a.$from,s=o.parent;if(s.type.name!==`paragraph`||s.content.size>0||!rC(i)||!nC(i))return!1;n.preventDefault();let c=t.state.schema.marks.link,l=o.pos,u=t.state.tr.insertText(i,l);return c&&u.addMark(l,l+i.length,c.create({href:i})),t.dispatch(u),queueMicrotask(()=>{let n=l,r=l+i.length,a=Fv(t.state.tr).delete(n,r);t.dispatch(a),e.commands.setEmbed({url:i})}),!0}}})]}}),GT=50,KT=new Pr(`jantRehostImages`),qT=new Set;function JT(e){qT.delete(e)}var YT=N.create({name:`rehostImages`,addOptions(){return{shouldRehost:void 0,rehost:void 0}},addProseMirrorPlugins(){let e=this.options;return[new j({key:KT,appendTransaction(t,n,r){if(!t.some(e=>e.docChanged))return null;let{shouldRehost:i,rehost:a}=e;if(!i||!a)return null;let o=[],s=new Set;if(r.doc.descendants(e=>{if(e.type.name!==`image`)return;let t=e.attrs.src;typeof t!=`string`||!t||s.has(t)||qT.has(t)||i(t)&&(s.add(t),o.push(t))}),o.length===0)return null;let c=o.slice(0,GT),l=o.length-c.length;l>0&&console.warn(`[jant] ${l} pasted image(s) left as external links — per-paste rehost cap of ${GT} reached.`);for(let e of c)qT.add(e),queueMicrotask(()=>a(e));return null}})]}});function XT(e){return e instanceof E?e:e.content}function ZT(e){if(/data-vscode-/i.test(e))return!0;let t=e.match(/^[^<]*(?:<(?:meta|html|head|body)\b[^>]*>\s*)*<(?:div|pre)\b[^>]*style="([^"]*)"/i);if(t){let e=t[1]??``,n=/font-family:[^;"]*\b(?:monospace|Menlo|Monaco|Consolas|Courier|JetBrains Mono|Fira Code|Source Code Pro)\b/i.test(e),r=/white-space:\s*pre\b/i.test(e);if(n&&r)return!0}return!1}var QT=N.create({name:`markdownClipboard`,addProseMirrorPlugins(){return[new j({props:{handlePaste:(e,t)=>{let n=t.clipboardData?.getData(`text/html`)??``;if(!n||!ZT(n))return!1;let r=t.clipboardData?.getData(`text/plain`)?.trim()??``;if(!r||!this.editor.markdown)return!1;let i=this.editor.markdown.parse(r);if(i.type!==`doc`||!i.content)return!1;let a=ql(i,e.state.schema,{slice:!1}),o=D.maxOpen(XT(a));return t.preventDefault(),e.dispatch(e.state.tr.replaceSelection(o).scrollIntoView()),!0},clipboardTextParser:(e,t,n,r)=>{if(!e.trim()||!this.editor.markdown)return D.empty;let i=this.editor.markdown.parse(e);if(i.type!==`doc`||!i.content)return D.empty;if(i.content.length===1&&i.content[0]?.type===`paragraph`){let e=i.content[0];if(!e?.content)return D.empty;let t=ql(e.content,r.state.schema,{slice:!0});return D.maxOpen(XT(t))}let a=ql(i,r.state.schema,{slice:!1});return D.maxOpen(XT(a))}}})]}}),$T=N.create({name:`reclaimModEnter`,priority:1e3,addKeyboardShortcuts(){return{"Mod-Enter":()=>!0}}});function eE(e={}){return[...Vx(),Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??``}),$T,Xw,Qw,QT,Uw,eT,Bw.configure({toolbarMode:`compose`}),Fw]}function tE(e={}){return[...Vx({imageExtension:PT,moreBreakExtension:IT,embedExtension:zT,htmlBlockExtension:VT}),$T,Pm.configure({markedOptions:bx}),IS.configure({placeholder:e.placeholder??`Write something…`}),AT,Xw,Qw,QT,IC,WT,Ow.configure(e.pasteMedia??{}),YT.configure(e.rehostImages??{}),Bw.configure({toolbarMode:e.toolbarMode??`default`}),Fw,Uw,eT,Gw]}function nE(e){try{let t=JSON.parse(e);return t.type===`doc`?Jx(t).trimEnd():``}catch{return``}}function rE(e){return new Tf({element:e.element,extensions:tE({placeholder:e.placeholder,toolbarMode:e.toolbarMode,pasteMedia:e.pasteMedia,rehostImages:e.rehostImages}),content:e.content??void 0,editorProps:{scrollMargin:{top:5,right:5,bottom:80,left:5},scrollThreshold:{top:5,right:5,bottom:80,left:5}},onUpdate:({editor:t})=>{e.onUpdate?.(fx(t.getJSON()))},onFocus:()=>{e.onFocus?.()},onSelectionUpdate:({editor:t})=>{e.onSelectionUpdate?.({from:t.state.selection.from,to:t.state.selection.to})}})}function iE(e){return nE(JSON.stringify(e))}function aE(e){let t=e.content?qx(e.content):void 0;return new Tf({element:e.element,extensions:eE({placeholder:e.placeholder}),content:t,onUpdate:({editor:t})=>{e.onUpdate?.(iE(t.getJSON()))}})}var oE=()=>typeof crypto<`u`&&typeof crypto.randomUUID==`function`?crypto.randomUUID():`xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx`.replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e===`x`?t:t&3|8).toString(16)}),sE=`[data-editor-floating-ui]`,cE=`(max-width: 700px), (max-height: 760px), (hover: none) and (pointer: coarse)`,lE={drafts:`
309
309
  <rect x="3.85" y="3.45" width="7.85" height="8.35" rx="2.35" />
310
310
  <rect
311
311
  x="6.15"
@@ -320,7 +320,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
320
320
  <path d="M8.55 8.55h3.2" stroke-width="1.2" />
321
321
  <path d="M8.55 10.8h3.95" stroke-width="1.2" />
322
322
  <path d="M8.55 13.05h2.45" stroke-width="1.2" />
323
- `},tE={public:`
323
+ `},uE={public:`
324
324
  <circle cx="8" cy="8" r="5.15" />
325
325
  <path d="M3.85 8h8.3" />
326
326
  <path d="M8 2.85c1.22 1.32 1.95 3.08 1.95 5.15S9.22 11.83 8 13.15" />
@@ -333,11 +333,11 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
333
333
  `,private:`
334
334
  <rect x="4.05" y="7.05" width="7.9" height="5.4" rx="1.75" />
335
335
  <path d="M5.95 7.05V5.9A2.05 2.05 0 0 1 8 3.85a2.05 2.05 0 0 1 2.05 2.05v1.15" />
336
- `},nE={check:`
336
+ `},dE={check:`
337
337
  <path d="M4.35 8.2 6.9 10.7 11.65 5.95" />
338
338
  `,chevron:`
339
339
  <path d="M5.1 6.45 8 9.3l2.9-2.85" />
340
- `},rE={collection:`
340
+ `},fE={collection:`
341
341
  <rect x="3" y="5.05" width="10" height="8.15" rx="2.2" />
342
342
  <path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85" />
343
343
  `,search:`
@@ -352,7 +352,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
352
352
  <path d="M5.55 8h4.9" />
353
353
  `,chevron:`
354
354
  <path d="M5.1 6.45 8 9.3l2.9-2.85" />
355
- `};function iE(e){return u`<svg
355
+ `};function pE(e){return u`<svg
356
356
  class="compose-dialog-header-icon"
357
357
  width="24"
358
358
  height="24"
@@ -365,7 +365,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
365
365
  aria-hidden="true"
366
366
  >
367
367
  ${ke(e)}
368
- </svg>`}function aE(e,t){return u`<span class=${t} aria-hidden="true">
368
+ </svg>`}function mE(e,t){return u`<span class=${t} aria-hidden="true">
369
369
  <svg
370
370
  class="compose-publish-visibility-svg"
371
371
  width="16"
@@ -379,7 +379,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
379
379
  >
380
380
  ${ke(e)}
381
381
  </svg>
382
- </span>`}function oE(e,t){return u`<svg
382
+ </span>`}function hE(e,t){return u`<svg
383
383
  class=${t}
384
384
  width="16"
385
385
  height="16"
@@ -392,7 +392,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
392
392
  aria-hidden="true"
393
393
  >
394
394
  ${ke(e)}
395
- </svg>`}function sE(e,t){return u`<svg
395
+ </svg>`}function gE(e,t){return u`<svg
396
396
  class=${t}
397
397
  width="14"
398
398
  height="14"
@@ -405,7 +405,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
405
405
  aria-hidden="true"
406
406
  >
407
407
  ${ke(e)}
408
- </svg>`}function cE(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`),r=Reflect.get(e,`slug`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n,slug:typeof r==`string`?r:``}]}):[]}function lE(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function uE(e){return e?lE(e)?null:e:null}function dE(e){return String(e).padStart(2,`0`)}function fE(e){let t=new Date(e*1e3);return`${t.getFullYear()}-${dE(t.getMonth()+1)}-${dE(t.getDate())}`}function pE(e){let t=e.trim();if(!t)return null;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);return Number.isNaN(o.getTime())||o.getFullYear()!==r||o.getMonth()!==i-1||o.getDate()!==a?null:{year:r,monthIndex:i-1,day:a}}function mE(e){let t=new Date(e*1e3);return t.getHours()*60+t.getMinutes()}function hE(e,t){let n=pE(e);if(!n)return null;let r=Math.min(Math.max(t,0),1439),i=Math.floor(r/60),a=r%60;return Math.floor(new Date(n.year,n.monthIndex,n.day,i,a,0,0).getTime()/1e3)}async function gE(e){let t=e.filter(e=>e.type===`media`),n=e.filter(e=>e.type===`text`);return{media:t.map(e=>({id:e.id,previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,alt:e.alt,mimeType:e.mimeType,originalName:e.originalName,summary:e.summary,chars:e.chars})),textAttachments:await Promise.all(n.map(async e=>{try{let t=await fetch(e.contentUrl);if(t.ok){let n=await t.json(),r=n.contentFormat===`markdown`&&n.content?n.content:``,i=r?qx(r):null;if(i)return{bodyJson:JSON.stringify(i),bodyHtml:``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:JSON.stringify({type:`doc`,content:[{type:`paragraph`}]}),bodyHtml:``,summary:e.summary??``,mediaId:e.id}})),attachmentOrder:e.map(e=>e.id)}}var _E=class e extends _{static _lastNewPostVisibility=`public`;_sourceCollectionId=null;static _collectionVisibilityKey(e){return`jant:collection-visibility:${e}`}static _getCollectionVisibility(t){try{let n=globalThis.localStorage.getItem(e._collectionVisibilityKey(t));if(n===`public`||n===`latest_hidden`||n===`private`)return n}catch{}return null}static _setCollectionVisibility(t,n){try{globalThis.localStorage.setItem(e._collectionVisibilityKey(t),n)}catch{}}static properties={collections:{type:Array},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},slashCommandDiscovered:{type:Boolean,attribute:`slash-command-discovered`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_openingEdit:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyExpanded:{state:!0},_threadItems:{state:!0},_focusedThreadIndex:{state:!0},_slug:{state:!0},_publishedAtInput:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_publishPanelFullscreen:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0},_quietReply:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_publishedAtTimeMinutes=null;_originalPublishedAt=null;_initialPublishedAtTimeMinutes=null;_initialPublishedAtInput=``;_initialSlug=``;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_mousedownOnBackdrop=!1;_mousedownPos=null;_filePickerActive=!1;_ignoreNextEscapeClose=!1;_openEditRequestId=0;_collectionPickerOrder=[];_suppressCollectionOptionClickUntil=0;_suppressedCollectionOptionId=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.labels={},this.uploadMaxFileSize=1024,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this.slashCommandDiscovered=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._publishPanelFullscreen=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1,this._quietReply=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),e.has(`_showCollection`)&&this._showCollection&&this._scheduleCollectionPickerAutofocus(),(e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_publishedAtInput`)||e.has(`_visibility`))&&(this._draftSourceId||this._scheduleDraftSave()),this._showPublishPanel&&this._updatePublishPanelLayout(),this._showCollection&&this._updateCollectionPopoverSide()}reset(){this._openEditRequestId+=1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._closeCollectionPicker(),this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._quietReply=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=cE(t.collections),!0):!1}catch{return!1}}async openEdit(e){this.reset();let t=++this._openEditRequestId;this._openingEdit=!0,this._editPostId=e;let n=this.closest(`dialog`);n&&!n.open&&n.showModal(),await this.updateComplete,this._focusDialogShell();try{let n=await fetch(`/api/posts/${e}`);if(!n.ok)throw Error(`Failed to load post`);let r=await n.json();if(t!==this._openEditRequestId||(this._format=r.format,this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAt?fE(r.publishedAt):``,this._publishedAtTimeMinutes=r.publishedAt?mE(r.publishedAt):null,this._originalPublishedAt=r.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=r.visibility??`public`,this._visibilityLocked=!!r.replyToId,r.replyToId&&(this._replyToId=r.replyToId,await this._fetchReplyContext(r.replyToId),t!==this._openEditRequestId)))return;r.collectionIds?.length&&(this._collectionIds=r.collectionIds);let{media:i,textAttachments:a,attachmentOrder:o}=await gE(r.attachments??[]);if(t!==this._openEditRequestId||(this._openingEdit=!1,await this.updateComplete,t!==this._openEditRequestId))return;this._restoreEditDraftIfAvailable(e)||this._editor?.populate({format:r.format,title:r.format===`quote`?void 0:r.title??void 0,bodyJson:r.body??void 0,url:r.format===`quote`?r.sourceUrl??void 0:r.url??void 0,quoteText:r.quoteText??void 0,quoteAuthor:r.format===`quote`?r.sourceName??void 0:void 0,rating:r.rating??void 0,media:i,textAttachments:a,attachmentOrder:o}),globalThis.requestAnimationFrame(()=>{t===this._openEditRequestId&&(this._focusDialogShell(),this._captureInitialSnapshot())})}catch{if(t!==this._openEditRequestId)return;this._openingEdit=!1,this._closeDialog(),this.reset(),a(this.labels.loadPostFailed,`error`)}}async openNew(t){if(this.reset(),t?.restoreDraft!==!1&&await this.restoreLocalDraft(),t?.initialFormat&&(this._format=t.initialFormat),t?.collectionId&&!this._collectionIds.includes(t.collectionId)&&(this._collectionIds=[t.collectionId,...this._collectionIds]),t?.collectionId){this._sourceCollectionId=t.collectionId;let n=e._getCollectionVisibility(t.collectionId);n&&(this._visibility=n)}this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openReply(e,t,n,r,i){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._visibilityLocked=!0,this._format=i?.initialFormat??`note`,i?.restoreDraft!==!1&&await this.restoreLocalDraft({expectedReplyToId:e}),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``,i=(n.attachments??[]).filter(e=>e.type===`media`).map(e=>({url:e.url??e.previewUrl,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,width:e.width,height:e.height}));this._replyToData={contentHtml:n.bodyHtml??``,dateText:r,media:i.length>0?i:void 0}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||o(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){if(this._threadItems.length>0){let e=this.querySelector(`jant-compose-editor`);if(!e)return!1;let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.attachments.length>0}let e=this._editor;if(!e)return!1;let t=e.getData();return!!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.attachedTexts.length>0||t.rating>0||t.attachments.length>0)}_buildSnapshot(){let e=this._editor;if(!e)return null;let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,i=t.rating>0?e._showRating:!1;return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showTitle:r,showRating:i,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&this._closeCollectionPicker(),this._showPublishPanel&&=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}if(this._editPostId){this._hasUnsavedChanges()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset());return}this._hasContent()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){if(this._confirmForAttachedText)this._confirmPanelOpen=!1,this._discardAttachedPanel();else if(this._confirmForDrafts){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()}else this._discardAndClose()}_buildEditorPostDetail(e,t,n,r){let i=e.getData(),a=new Map((i.attachments??[]).map(e=>[e.clientId,e])),o=new Map(i.attachedTexts.map(e=>[e.clientId,e])),s=[];for(let e of i.attachmentOrder){let t=a.get(e);if(t){s.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:uE(n.originalBodyJson??null)})}let c=n===0;return{format:t,title:i.title,body:i.body,url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,status:r,slug:c&&this._slug.trim()||void 0,publishedAt:c?this._getPublishedAtSubmitValue(r):void 0,visibility:c?this._visibilityLocked?void 0:this._visibility:void 0,rating:i.rating,collectionIds:c?[...this._collectionIds]:[],attachments:s,replyToId:c?this._replyToId??void 0:void 0,replyThreadRootId:c?this._replyThreadRootId??void 0:void 0,replyRefreshKind:c?this._replyRefreshKind??void 0:void 0,replyRefreshId:c?this._replyRefreshId??void 0:void 0}}_buildSubmitDetail(e){let t=this._editor;if(!t)return null;let n=t.getData(),r=new Map((n.attachments??[]).map(e=>[e.clientId,e])),i=new Map(n.attachedTexts.map(e=>[e.clientId,e])),a=[];for(let e of n.attachmentOrder){let t=r.get(e);if(t){a.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=i.get(e);n?.bodyJson&&a.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:uE(n.originalBodyJson??null)})}return{format:this._format,title:n.title,body:n.body,url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug.trim()||void 0,publishedAt:this._getPublishedAtSubmitValue(e),status:e,visibility:this._visibilityLocked?void 0:this._visibility,rating:n.rating,collectionIds:[...this._collectionIds],attachments:a,editPostId:this._editPostId??this._draftSourceId??void 0,replyToId:this._replyToId??void 0,quietReply:this._quietReply||void 0,replyThreadRootId:this._replyThreadRootId??void 0,replyRefreshKind:this._replyRefreshKind??void 0,replyRefreshId:this._replyRefreshId??void 0}}_focusBlockedSubmitField(e){if(e===`published`&&this._getPublishedAtValidationMessage()!==null)return this._revealPublishedAtField(),!0;if(this._getSlugValidationMessage())return this._revealSlugField(),!0;if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<this._threadItems.length;t++){let n=this._threadItems[t],r=e[t];if(r){if(r.getUrlValidationMessage())return r.revealUrlValidation(),r.focusUrlInput(`end`),!0;if(r.getLinkTitleValidationMessage())return r.revealLinkTitleValidation(),r.focusLinkTitleInput(`end`),!0;if(n.format===`quote`&&!r._quoteText.trim())return r.focusInput(`end`),!0}}return!1}let t=this._editor;return t?t.getUrlValidationMessage()?(t.revealUrlValidation(),t.focusUrlInput(`end`),!0):t.getLinkTitleValidationMessage()?(t.revealLinkTitleValidation(),t.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!t._quoteText.trim()?(t.focusInput(`end`),!0):!1:!1}_dispatchSubmit(e){if(this._loading||this._focusBlockedSubmitField(e))return!1;if(this._draftSourceId||(this._cancelDraftSaveTimer(),this._saveDraftToStorage()),this._threadItems.length>0){if(this._threadItems.length>20)return a(this._getThreadLimitMessage(),`error`),!1;let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(t.length!==this._threadItems.length)return!1;let n=[],r=[];for(let i=0;i<this._threadItems.length;i++){let a=this._threadItems[i],o=t[i];if(!o)return!1;n.push(this._buildEditorPostDetail(o,a.format,i,e)),r.push(...(o._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`))}return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n[0],editPostId:this._editPostId??this._draftSourceId??void 0,threadPosts:n,pendingAttachments:r}})),!0}let t=this._editor;if(!t)return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_saveDraftAndOpenDrafts(){this._finishDraftSaveAndOpenDrafts()}_finishDraftSaveAndOpenDrafts(){if(!this._dispatchSubmit(`draft`))return;this.reset();let e=()=>{clearTimeout(t),this.isConnected&&this._openDraftsPanel()},t=globalThis.setTimeout(()=>{document.removeEventListener(`jant:compose-submit-complete`,e)},1e4);document.addEventListener(`jant:compose-submit-complete`,e,{once:!0})}_finishSubmit(e){if(this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_submit(e){this._showPublishPanel=!1,this._finishSubmit(e)}_toggleCollection(e){this._collectionIds.includes(e)?this._collectionIds=this._collectionIds.filter(t=>t!==e):this._collectionIds=[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);if(!n)return``;if(t.length===1)return n.title;if(t.length===2){let r=e.find(e=>e.id===t[1]);return r?`${n.title}, ${r.title}`:n.title}return this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1))}_prepareCollectionPickerOrder(){this._collectionPickerOrder=$x(this.collections??[],this._collectionIds)}_focusCollectionPickerInitialTarget(){this.querySelector(`.compose-collection-search-input, .compose-collection-option, .compose-collection-add-action`)?.focus()}_focusCollectionSearchInput(){let e=this.querySelector(`.compose-collection-search-input`);if(!e)return!1;e.focus();let t=e.value.length;return e.setSelectionRange(t,t),!0}_closeCollectionPicker(e){if(this._showCollection=!1,this._collectionSearch=``,this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,e?.restoreFocus===`trigger`){this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()});return}e?.restoreFocus===`editor`&&this._restorePageEditorFocus()}_suppressNextCollectionOptionClick(e){this._suppressedCollectionOptionId=e,this._suppressCollectionOptionClickUntil=Date.now()+250}_isTouchViewport(){return globalThis.matchMedia?.(`(hover: none) and (pointer: coarse)`)?.matches??!1}_shouldAutofocusCollectionPicker(){return!this._isTouchViewport()}_shouldAutofocusFormatInput(){return!this._isTouchViewport()}_scheduleCollectionPickerAutofocus(){this._shouldAutofocusCollectionPicker()&&globalThis.requestAnimationFrame(()=>{this._showCollection&&this._focusCollectionPickerInitialTarget()})}_scheduleCollectionSearchFocus(){globalThis.requestAnimationFrame(()=>{this._showCollection&&(this._focusCollectionSearchInput()||this._focusCollectionPickerInitialTarget())})}_isPrintableCollectionSearchKey(e){return e.length===1&&e.trim().length>0}_handleCollectionTriggerKeydown=e=>{if(!(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)){if(e.key===`ArrowDown`){e.preventDefault(),this._scheduleCollectionSearchFocus();return}!this._showCollection||!this._isPrintableCollectionSearchKey(e.key)||(e.preventDefault(),this._collectionSearch+=e.key,this._scheduleCollectionSearchFocus())}};_getCollectionOptionElements(){return Array.from(this.querySelectorAll(`.compose-collection-option`))}_handleCollectionSearchKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this._closeCollectionPicker({restoreFocus:`trigger`});return}if(e.key!==`ArrowDown`)return;let[t]=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-add-action`),r=t??n;r&&(e.preventDefault(),r.focus())};_handleCollectionOptionKeydown=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this._getCollectionOptionElements(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`.compose-collection-add-action`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.compose-collection-search-input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._toggleCollection(t);return}e.key===`Enter`&&(e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._closeCollectionPicker({restoreFocus:`trigger`}))};_handleCollectionOptionClick=e=>{if(this._suppressedCollectionOptionId===e&&Date.now()<=this._suppressCollectionOptionClickUntil){this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0;return}this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,this._toggleCollection(e)};_handleCollectionAddActionKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-search-input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};_updateCollectionPopoverSide(){let e=this.querySelector(`.compose-collection-trigger`),t=this.querySelector(`.compose-collection-popover[data-popover]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=Math.max(0,i-12-a.bottom-4),s=Math.max(0,a.top-r-12-4);t.dataset.side=o>=s?`bottom`:`top`}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(!this._showPublishPanel||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||!this._showPublishPanel)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(){if(!this._hasManualSlug()){this._slugTaken=!1,this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getSlugSyncValidationMessage()){this._slugTaken=!1,this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let e=this._slug.trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(e)},250)}async _checkSlugAvailability(e){this._slugCheckTimer=null;let t=++this._slugCheckRequestId,n=new URLSearchParams({mode:`check`,slug:e}),r=this._currentSlugOwnerId();r&&n.set(`postId`,r);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugCheckRequestId||this._slug.trim()!==e)return;this._slugTaken=i.available===!1}catch{}finally{t===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(){this._slug=``,this._slugTaken=!1,this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this._syncPublishPanelPresentation(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),window.addEventListener(`resize`,this._handleViewportChange),window.addEventListener(`scroll`,this._handleViewportChange,{passive:!0}),globalThis.visualViewport?.addEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.addEventListener(`scroll`,this._handleViewportChange),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),window.removeEventListener(`resize`,this._handleViewportChange),window.removeEventListener(`scroll`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`scroll`,this._handleViewportChange),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_syncPublishPanelPresentation(){let e=globalThis.matchMedia?.($T)?.matches??!1;e!==this._publishPanelFullscreen&&(this._publishPanelFullscreen=e)}_handleViewportChange=()=>{this._syncPublishPanelPresentation(),this._showPublishPanel&&this.updateComplete.then(()=>this._updatePublishPanelLayout()),this._showCollection&&this.updateComplete.then(()=>this._updateCollectionPopoverSide())};_handleDialogCancel=e=>{e.preventDefault();let t=e;t.isComposing||t.keyCode===229||this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay()||this.requestClose()};_pointInOpenPopover(e,t){for(let n of document.querySelectorAll(`:popover-open`)){let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom)return!0}return!1}_handleDialogMousedown=e=>{let t=e;this._mousedownOnBackdrop=e.target===this._dialogEl&&!this._pointInOpenPopover(t.clientX,t.clientY),this._mousedownPos=this._mousedownOnBackdrop?{x:t.clientX,y:t.clientY}:null};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl||!this._mousedownOnBackdrop)return;let t=e;if(this._mousedownPos){let e=t.clientX-this._mousedownPos.x,n=t.clientY-this._mousedownPos.y;if(e*e+n*n>16)return}let n=document.getSelection();if(n&&!n.isCollapsed||this._pointInOpenPopover(t.clientX,t.clientY))return;let r=document.elementFromPoint(t.clientX,t.clientY);r instanceof globalThis.Element&&r.closest(QT)||this.requestClose()};_focusDialogShell(){let e=this.querySelector(`.compose-dialog-inner`);if(e){e.focus();return}this._dialogEl?.focus()}_restorePageEditorFocus(){this.updateComplete.then(()=>this._editor?.focusInput())}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showCollection?(this._closeCollectionPicker({restoreFocus:`editor`}),!0):this._showPublishPanel?(this._closePublishPanel(!0),!0):this._altPanelOpen?(this._closeAltPanel(),this._restorePageEditorFocus(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1}_handleKeydown=t=>{let n=t;if(!(n.isComposing||n.keyCode===229)){if(n.key!==`Escape`&&this._clearFilePickerEscapeState(),n.key===`Escape`){if(n.preventDefault(),n.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(n.key===`Enter`&&this._confirmPanelOpen)n.preventDefault(),this._handleConfirmSave();else if((n.metaKey||n.ctrlKey)&&n.key===`Enter`){if(t.preventDefault(),this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField(`published`);return}this._submit(`published`)}else if((n.metaKey||n.ctrlKey)&&!n.altKey&&!n.shiftKey&&n.key>=`1`&&n.key<=String(e._FORMATS.length)){n.preventDefault();let t=e._FORMATS[Number(n.key)-1];this._threadItems.length>0?this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.dispatchEvent(new CustomEvent(`jant:format-change`,{detail:{format:t},bubbles:!0})):this._switchFormat(t)}}};_handleAltPanelOpen=e=>{this._altPanelIndex=e.detail.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle,e.detail.selection),t.adoptPendingUploads(),this.updateComplete.then(()=>t.focusSelection(e.detail.selection))),this._replyExpanded=e.detail.replyExpanded};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext()};_handleAttachedPanelOpen=e=>{this._attachedTextIndex=e.detail.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=JT({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=uE(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(uE(this._attachedEditor.getJSON()))!==JSON.stringify(uE(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasContent()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json(),n=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.attachments??[]).filter(e=>e.type===`media`).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt??null,mimeType:e.mimeType}))})),r=new Set(n.map(e=>e.id));this._drafts=n.filter(e=>!e.replyToId||!r.has(e.replyToId))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _populateEditorFromPost(e,t){let{media:n,textAttachments:r,attachmentOrder:i}=await gE(t.attachments??[]);e.populate({format:t.format,title:t.format===`quote`?void 0:t.title??void 0,bodyJson:t.body??void 0,url:t.format===`quote`?t.sourceUrl??void 0:t.url??void 0,quoteText:t.quoteText??void 0,quoteAuthor:t.format===`quote`?t.sourceName??void 0:void 0,rating:t.rating??void 0,media:n,textAttachments:r,attachmentOrder:i})}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=n.publishedAt?fE(n.publishedAt):``,this._publishedAtTimeMinutes=n.publishedAt?mE(n.publishedAt):null,this._originalPublishedAt=n.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),n.threadId===n.id||n.threadId===void 0)try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(e.ok){let t=await e.json(),r=(Array.isArray(t)?t:t.posts??[]).filter(e=>e.id!==n.id&&e.threadId===n.id&&e.status===`draft`).map(e=>({id:e.id,format:e.format,replyToId:e.replyToId??null,title:e.title??null,body:e.body??null,url:e.url??null,sourceUrl:e.sourceUrl??null,sourceName:e.sourceName??null,quoteText:e.quoteText??null,rating:e.rating??null,attachments:e.attachments??[],visibility:e.visibility??null}));if(r.length>0){let e=[],t=n.id;for(let n=0;n<r.length;n++){let n=r.find(e=>e.replyToId===t);if(!n)break;e.push(n),t=n.id}for(let t of r)e.includes(t)||e.push(t);this._threadItems=[{id:ZT(),format:n.format},...e.map(e=>({id:ZT(),format:e.format}))],this._focusedThreadIndex=0,await this.updateComplete;let i=Array.from(this.querySelectorAll(`jant-compose-editor`)),a=i[0];a&&await this._populateEditorFromPost(a,n);for(let t=0;t<e.length;t++){let r=i[t+1];if(!r)continue;let a=e[t];await this._populateEditorFromPost(r,{id:a.id,threadId:n.id,format:a.format,replyToId:a.replyToId,title:a.title,body:a.body,url:a.url,sourceUrl:a.sourceUrl,sourceName:a.sourceName,quoteText:a.quoteText,rating:a.rating,attachments:a.attachments,visibility:a.visibility})}globalThis.requestAnimationFrame(()=>{i[0]?.focusInput(),this._captureInitialSnapshot()});return}}}catch{}await this.updateComplete;let r=this._editor;r&&await this._populateEditorFromPost(r,n),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();a(this.labels.draftDeleted)}catch{a(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.bodyText?e.bodyText:e.title?e.title:e.quoteText?e.quoteText:e.url?e.url:null}_getThreadLimitMessage(){return this.labels.threadLimitReached||`Threads can include up to 20 posts.`}static _DRAFT_KEY=`jant:compose-draft`;static _EDIT_DRAFT_KEY_PREFIX=`jant:compose-edit:`;static _DRAFT_MAX_AGE=10080*60*1e3;_currentDraftStorageKey(){return this._editPostId?e._EDIT_DRAFT_KEY_PREFIX+this._editPostId:e._DRAFT_KEY}_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),this._draftSourceId||this._scheduleDraftSave()};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));if(!e.some(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.rating>0||t.attachedTexts.length>0||t.attachments.length>0})){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let t=this._threadItems.map((t,n)=>{let r=e[n];if(!r)return null;let i=r.getData();return{format:t.format,title:i.title,bodyJson:r.getNormalizedBodyJson(),url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,attachedTexts:i.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...i.attachmentOrder]}}).filter(e=>e!==null),n={format:this._threadItems[0]?.format??this._format,title:``,bodyJson:null,url:``,quoteText:``,quoteAuthor:``,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:0,showTitle:!1,showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:[],attachmentOrder:[],threadItems:t,savedAt:Date.now()};try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(n))}catch{}return}let e=this._editor;if(!e)return;if(!this._hasUnsavedChanges()){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let t=e.getData();if(!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.rating>0||t.attachedTexts.length>0)){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let n={format:this._format,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:t.rating,showTitle:this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,showRating:t.rating>0?e._showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:t.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...t.attachmentOrder],savedAt:Date.now()};try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(n))}catch{}}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),globalThis.localStorage.removeItem(this._currentDraftStorageKey())}clearLocalDraftFromStorage(){this._clearDraftFromStorage()}clearEditDraftFromStorage(t){globalThis.localStorage.removeItem(e._EDIT_DRAFT_KEY_PREFIX+t)}async restoreLocalDraft(t){if(this._editPostId||this._draftSourceId||this._hasContent())return;let n;try{n=globalThis.localStorage.getItem(e._DRAFT_KEY)}catch{return}if(!n)return;let r;try{r=JSON.parse(n)}catch{globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(Date.now()-r.savedAt>e._DRAFT_MAX_AGE){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(t?.expectedReplyToId!==void 0&&r.replyToId!==t.expectedReplyToId)return;if(this._collectionIds=[...r.collectionIds??[]],this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAtInput??``,this._publishedAtTimeMinutes=r.publishedAtTimeMinutes??null,this._visibility=r.visibility??`public`,r.replyToId&&(this._replyToId=r.replyToId,this._visibilityLocked=!0,await this._fetchReplyContext(r.replyToId)),r.threadItems&&r.threadItems.length>=2){this._format=r.threadItems[0].format,this._threadItems=r.threadItems.map(e=>({id:ZT(),format:e.format})),this._focusedThreadIndex=0,await this.updateComplete;let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<r.threadItems.length;t++){let n=r.threadItems[t],i=e[t];if(!i)continue;let a=n.attachedTexts?.flatMap(e=>{let t=uE(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});i.populate({format:n.format,title:n.title||void 0,bodyJson:n.bodyJson?JSON.stringify(n.bodyJson):void 0,url:n.url||void 0,quoteText:n.quoteText||void 0,quoteAuthor:n.quoteAuthor||void 0,textAttachments:a?.length?a:void 0,attachmentOrder:n.attachmentOrder})}this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()});return}this._format=r.format,await this.updateComplete;let i=r.attachedTexts?.flatMap(e=>{let t=uE(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});this._editor?.populate({format:r.format,title:r.title||void 0,bodyJson:r.bodyJson?JSON.stringify(r.bodyJson):void 0,url:r.url||void 0,quoteText:r.quoteText||void 0,quoteAuthor:r.quoteAuthor||void 0,rating:r.rating||void 0,showTitle:r.showTitle,showRating:r.showRating,textAttachments:i?.length?i:void 0,attachmentOrder:r.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()})}_restoreEditDraftIfAvailable(t){let n=e._EDIT_DRAFT_KEY_PREFIX+t,r;try{r=globalThis.localStorage.getItem(n)}catch{return!1}if(!r)return!1;let i;try{i=JSON.parse(r)}catch{return globalThis.localStorage.removeItem(n),!1}if(Date.now()-i.savedAt>e._DRAFT_MAX_AGE)return globalThis.localStorage.removeItem(n),!1;this._format=i.format,this._collectionIds=[...i.collectionIds??[]],this._slug=i.slug??``,this._publishedAtInput=i.publishedAtInput??``,this._publishedAtTimeMinutes=i.publishedAtTimeMinutes??null,this._visibility=i.visibility??`public`;let o=i.attachedTexts?.flatMap(e=>{let t=uE(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});return this._editor?.populate({format:i.format,title:i.title||void 0,bodyJson:i.bodyJson?JSON.stringify(i.bodyJson):void 0,url:i.url||void 0,quoteText:i.quoteText||void 0,quoteAuthor:i.quoteAuthor||void 0,rating:i.rating||void 0,showTitle:i.showTitle,showRating:i.showRating,textAttachments:o?.length?o:void 0,attachmentOrder:i.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),!0}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?u`
408
+ </svg>`}function _E(e){return Array.isArray(e)?e.flatMap(e=>{if(!e||typeof e!=`object`)return[];let t=Reflect.get(e,`id`),n=Reflect.get(e,`title`),r=Reflect.get(e,`slug`);return typeof t!=`string`||typeof n!=`string`?[]:[{id:t,title:n,slug:typeof r==`string`?r:``}]}):[]}function vE(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0))}function yE(e){return e?vE(e)?null:e:null}function bE(e){return String(e).padStart(2,`0`)}function xE(e){let t=new Date(e*1e3);return`${t.getFullYear()}-${bE(t.getMonth()+1)}-${bE(t.getDate())}`}function SE(e){let t=e.trim();if(!t)return null;let n=/^(\d{4})-(\d{2})-(\d{2})$/.exec(t);if(!n)return null;let r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=new Date(r,i-1,a);return Number.isNaN(o.getTime())||o.getFullYear()!==r||o.getMonth()!==i-1||o.getDate()!==a?null:{year:r,monthIndex:i-1,day:a}}function CE(e){let t=new Date(e*1e3);return t.getHours()*60+t.getMinutes()}function wE(e,t){let n=SE(e);if(!n)return null;let r=Math.min(Math.max(t,0),1439),i=Math.floor(r/60),a=r%60;return Math.floor(new Date(n.year,n.monthIndex,n.day,i,a,0,0).getTime()/1e3)}async function TE(e){let t=e.filter(e=>e.type===`media`),n=e.filter(e=>e.type===`text`);return{media:t.map(e=>({id:e.id,previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,alt:e.alt,mimeType:e.mimeType,originalName:e.originalName,summary:e.summary,chars:e.chars})),textAttachments:await Promise.all(n.map(async e=>{try{let t=await fetch(e.contentUrl);if(t.ok){let n=await t.json(),r=n.contentFormat===`markdown`&&n.content?n.content:``,i=r?qx(r):null;if(i)return{bodyJson:JSON.stringify(i),bodyHtml:``,summary:e.summary??``,mediaId:e.id}}}catch{}return{bodyJson:JSON.stringify({type:`doc`,content:[{type:`paragraph`}]}),bodyHtml:``,summary:e.summary??``,mediaId:e.id}})),attachmentOrder:e.map(e=>e.id)}}var EE=class e extends _{static _lastNewPostVisibility=`public`;_sourceCollectionId=null;static _collectionVisibilityKey(e){return`jant:collection-visibility:${e}`}static _getCollectionVisibility(t){try{let n=globalThis.localStorage.getItem(e._collectionVisibilityKey(t));if(n===`public`||n===`latest_hidden`||n===`private`)return n}catch{}return null}static _setCollectionVisibility(t,n){try{globalThis.localStorage.setItem(e._collectionVisibilityKey(t),n)}catch{}}static properties={collections:{type:Array},labels:{type:Object},uploadMaxFileSize:{type:Number,attribute:`upload-max-file-size`},pageMode:{type:Boolean,attribute:`page-mode`},closeHref:{type:String,attribute:`close-href`},autoRestoreDraft:{type:Boolean,attribute:`auto-restore-draft`},slashCommandDiscovered:{type:Boolean,attribute:`slash-command-discovered`},_format:{state:!0},_status:{state:!0},_loading:{state:!0},_openingEdit:{state:!0},_collectionIds:{state:!0},_showCollection:{state:!0},_collectionSearch:{state:!0},_altPanelOpen:{state:!0},_altPanelIndex:{state:!0},_attachedPanelOpen:{state:!0},_attachedTextIndex:{state:!0},_confirmPanelOpen:{state:!0},_editPostId:{state:!0},_draftSourceId:{state:!0},_draftsPanelOpen:{state:!0},_drafts:{state:!0},_draftsLoading:{state:!0},_draftsError:{state:!0},_draftMenuOpenId:{state:!0},_addCollectionPanelOpen:{state:!0},_replyToId:{state:!0},_replyToData:{state:!0},_replyExpanded:{state:!0},_threadItems:{state:!0},_focusedThreadIndex:{state:!0},_slug:{state:!0},_publishedAtInput:{state:!0},_visibility:{state:!0},_showPublishPanel:{state:!0},_publishPanelFullscreen:{state:!0},_suggestedSlug:{state:!0},_suggestedSlugLoading:{state:!0},_slugCheckLoading:{state:!0},_slugTaken:{state:!0},_visibilityLocked:{state:!0},_quietReply:{state:!0}};_attachedEditor=null;_attachedTextSnapshot=null;_confirmForDrafts=!1;_confirmForAttachedText=!1;_draftSaveTimer=null;_draftRestored=!1;_initialSnapshot=null;_pageFocusApplied=!1;_pageLeaveRequested=!1;_replyThreadRootId=null;_replyRefreshKind=null;_replyRefreshId=null;_publishedAtTimeMinutes=null;_originalPublishedAt=null;_initialPublishedAtTimeMinutes=null;_initialPublishedAtInput=``;_initialSlug=``;_slugCheckTimer=null;_slugSuggestTimer=null;_slugSuggestRequestId=0;_slugCheckRequestId=0;_slugSuggestionKey=``;_suppressBeforeUnload=!1;_dialogEl=null;_mousedownOnBackdrop=!1;_mousedownPos=null;_filePickerActive=!1;_ignoreNextEscapeClose=!1;_openEditRequestId=0;_collectionPickerOrder=[];_suppressCollectionOptionClickUntil=0;_suppressedCollectionOptionId=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.collections=[],this.labels={},this.uploadMaxFileSize=1024,this.pageMode=!1,this.closeHref=`/`,this.autoRestoreDraft=!1,this.slashCommandDiscovered=!1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._showCollection=!1,this._collectionSearch=``,this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._publishPanelFullscreen=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._visibilityLocked=!1,this._quietReply=!1}get _editor(){return this.querySelector(`jant-compose-editor`)}updated(e){super.updated(e),this._initialSnapshot===null&&this._editor&&this._captureInitialSnapshot(),e.has(`_addCollectionPanelOpen`)&&this._addCollectionPanelOpen&&this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()}),e.has(`_showCollection`)&&this._showCollection&&this._scheduleCollectionPickerAutofocus(),(e.has(`_collectionIds`)||e.has(`_slug`)||e.has(`_publishedAtInput`)||e.has(`_visibility`))&&(this._draftSourceId||this._scheduleDraftSave()),this._showPublishPanel&&this._updatePublishPanelLayout(),this._showCollection&&this._updateCollectionPopoverSide()}reset(){this._openEditRequestId+=1,this._format=`note`,this._status=`published`,this._loading=!1,this._openingEdit=!1,this._collectionIds=[],this._closeCollectionPicker(),this._altPanelOpen=!1,this._altPanelIndex=0,this._attachedPanelOpen=!1,this._attachedTextIndex=0,this._confirmPanelOpen=!1,this._editPostId=null,this._draftSourceId=null,this._draftsPanelOpen=!1,this._drafts=[],this._draftsLoading=!1,this._draftsError=null,this._draftMenuOpenId=null,this._addCollectionPanelOpen=!1,this._replyToId=null,this._replyToData=null,this._replyExpanded=!1,this._threadItems=[],this._focusedThreadIndex=0,this._replyThreadRootId=null,this._replyRefreshKind=null,this._replyRefreshId=null,this._slug=``,this._publishedAtInput=``,this._publishedAtTimeMinutes=null,this._originalPublishedAt=null,this._initialPublishedAtTimeMinutes=null,this._initialPublishedAtInput=``,this._initialSlug=``,this._visibility=e._lastNewPostVisibility,this._sourceCollectionId=null,this._showPublishPanel=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugCheckLoading=!1,this._slugTaken=!1,this._slugSuggestionKey=``,this._visibilityLocked=!1,this._quietReply=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._initialSnapshot=null,this._pageFocusApplied=!1,this._pageLeaveRequested=!1,this._slugSuggestRequestId+=1,this._slugCheckRequestId+=1,this._suppressBeforeUnload=!1,this._filePickerActive=!1,this._ignoreNextEscapeClose=!1,this._cancelSlugTimers(),this._destroyAttachedEditor(),this._editor?.reset(),this._captureInitialSnapshot()}async refreshCollections(){try{let e=await fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}});if(!e.ok)return!1;let t=await e.json().catch(()=>null);return Array.isArray(t?.collections)?(this.collections=_E(t.collections),!0):!1}catch{return!1}}async openEdit(e){this.reset();let t=++this._openEditRequestId;this._openingEdit=!0,this._editPostId=e;let n=this.closest(`dialog`);n&&!n.open&&n.showModal(),await this.updateComplete,this._focusDialogShell();try{let n=await fetch(`/api/posts/${e}`);if(!n.ok)throw Error(`Failed to load post`);let r=await n.json();if(t!==this._openEditRequestId||(this._format=r.format,this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAt?xE(r.publishedAt):``,this._publishedAtTimeMinutes=r.publishedAt?CE(r.publishedAt):null,this._originalPublishedAt=r.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=r.visibility??`public`,this._visibilityLocked=!!r.replyToId,r.replyToId&&(this._replyToId=r.replyToId,await this._fetchReplyContext(r.replyToId),t!==this._openEditRequestId)))return;r.collectionIds?.length&&(this._collectionIds=r.collectionIds);let{media:i,textAttachments:a,attachmentOrder:o}=await TE(r.attachments??[]);if(t!==this._openEditRequestId||(this._openingEdit=!1,await this.updateComplete,t!==this._openEditRequestId))return;this._restoreEditDraftIfAvailable(e)||this._editor?.populate({format:r.format,title:r.format===`quote`?void 0:r.title??void 0,bodyJson:r.body??void 0,url:r.format===`quote`?r.sourceUrl??void 0:r.url??void 0,quoteText:r.quoteText??void 0,quoteAuthor:r.format===`quote`?r.sourceName??void 0:void 0,rating:r.rating??void 0,media:i,textAttachments:a,attachmentOrder:o}),globalThis.requestAnimationFrame(()=>{t===this._openEditRequestId&&(this._focusDialogShell(),this._captureInitialSnapshot())})}catch{if(t!==this._openEditRequestId)return;this._openingEdit=!1,this._closeDialog(),this.reset(),a(this.labels.loadPostFailed,`error`)}}async openNew(t){if(this.reset(),t?.restoreDraft!==!1&&await this.restoreLocalDraft(),t?.initialFormat&&(this._format=t.initialFormat),t?.collectionId&&!this._collectionIds.includes(t.collectionId)&&(this._collectionIds=[t.collectionId,...this._collectionIds]),t?.collectionId){this._sourceCollectionId=t.collectionId;let n=e._getCollectionVisibility(t.collectionId);n&&(this._visibility=n)}this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async openReply(e,t,n,r,i){this.reset(),this._replyToId=e,this._replyThreadRootId=n??e,this._replyRefreshKind=r?.kind??null,this._replyRefreshId=r?.id??null,this._replyToData=t??null,this._visibilityLocked=!0,this._format=i?.initialFormat??`note`,i?.restoreDraft!==!1&&await this.restoreLocalDraft({expectedReplyToId:e}),this.closest(`dialog`)?.showModal(),await this.updateComplete,this._editor?.focusInput(),this._captureInitialSnapshot()}async _fetchReplyContext(e){try{let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();this._replyThreadRootId=n.replyToId?n.threadId:n.id;let r=n.publishedAt?new Date(n.publishedAt*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`}):``,i=(n.attachments??[]).filter(e=>e.type===`media`).map(e=>({url:e.url??e.previewUrl,previewUrl:e.previewUrl,alt:e.alt,mimeType:e.mimeType,width:e.width,height:e.height}));this._replyToData={contentHtml:n.bodyHtml??``,dateText:r,media:i.length>0?i:void 0}}catch{}}set loading(e){this._loading=e}_closeDialog(){let e=this.closest(`dialog`);if(e){e.close(),document.activeElement?.blur();return}this.pageMode&&(this._suppressBeforeUnload=!0,globalThis.location.assign(this.closeHref||o(`/`)))}requestCloseAndLeave(){this._pageLeaveRequested=!0,this.requestClose()}consumePageLeaveRequest(){let e=this._pageLeaveRequested;return this._pageLeaveRequested=!1,e}preparePageLeave(){this._suppressBeforeUnload=!0}_clearFilePickerEscapeState(){this._filePickerActive=!1,this._ignoreNextEscapeClose=!1}_shouldIgnoreEscapeClose(){return this._filePickerActive||this._ignoreNextEscapeClose?(this._clearFilePickerEscapeState(),!0):!1}_hasContent(){if(this._threadItems.length>0){let e=this.querySelector(`jant-compose-editor`);if(!e)return!1;let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.attachments.length>0}let e=this._editor;if(!e)return!1;let t=e.getData();return!!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.attachedTexts.length>0||t.rating>0||t.attachments.length>0)}_buildSnapshot(){let e=this._editor;if(!e)return null;let t=e.getData(),n=e.getEffectiveAttachedTexts(),r=this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,i=t.rating>0?e._showRating:!1;return{format:this._format,collectionIds:[...this._collectionIds],slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,rating:t.rating,showTitle:r,showRating:i,attachments:e._attachments.map(e=>({clientId:e.clientId,mediaId:e.mediaId,previewUrl:e.previewUrl,mimeType:e.file.type,alt:e.alt,status:e.status,summary:e.summary,chars:e.chars})),attachedTexts:n.map(e=>({clientId:e.clientId,mediaId:e.mediaId??null,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:e.getEffectiveAttachmentOrder()}}_serializeSnapshot(e){return e?JSON.stringify(e):null}_captureInitialSnapshot(){this._initialSnapshot=this._serializeSnapshot(this._buildSnapshot())}_hasUnsavedChanges(){let e=this._serializeSnapshot(this._buildSnapshot());return e===null||!this._editPostId&&!this._draftSourceId&&!this._hasContent()?!1:this._initialSnapshot===null?this._hasContent():e!==this._initialSnapshot}requestClose(){if(!this._loading){if(this._showCollection&&this._closeCollectionPicker(),this._showPublishPanel&&=!1,this._confirmPanelOpen){let e=this._confirmForAttachedText;this._confirmPanelOpen=!1,this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._pageLeaveRequested=!1,this.updateComplete.then(()=>{if(e){this._attachedEditor?.commands.focus();return}this._editor?.focusInput()});return}if(this._editPostId){this._hasUnsavedChanges()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset());return}this._hasContent()?(this._confirmForDrafts=!1,this._confirmForAttachedText=!1,this._confirmPanelOpen=!0):(this._closeDialog(),this.reset())}}_discardAndClose(){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._clearDraftFromStorage(),this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._closeDialog(),this.reset()}_discardAttachedPanel(){this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_handleConfirmSave(){this._confirmForAttachedText?(this._confirmPanelOpen=!1,this._confirmForAttachedText=!1,this._doneAttachedPanel()):this._confirmForDrafts?(this._confirmPanelOpen=!1,this._editor?.hasPendingInlineImageUploads()?this._saveDraftAndOpenDrafts():this._finishDraftSaveAndOpenDrafts()):this._editPostId?(this._confirmPanelOpen=!1,this._submit(`published`)):(this._confirmPanelOpen=!1,this._submit(`draft`))}_handleConfirmDiscard(){if(this._confirmForAttachedText)this._confirmPanelOpen=!1,this._discardAttachedPanel();else if(this._confirmForDrafts){if(this._draftSourceId){let e=this._draftSourceId;fetch(`/api/posts/${e}`,{method:`DELETE`}).catch(()=>{}),a(this.labels.draftDeleted)}this._confirmPanelOpen=!1,this.reset(),this._openDraftsPanel()}else this._discardAndClose()}_buildEditorPostDetail(e,t,n,r){let i=e.getData(),a=new Map((i.attachments??[]).map(e=>[e.clientId,e])),o=new Map(i.attachedTexts.map(e=>[e.clientId,e])),s=[];for(let e of i.attachmentOrder){let t=a.get(e);if(t){s.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=o.get(e);n?.bodyJson&&s.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:yE(n.originalBodyJson??null)})}let c=n===0;return{format:t,title:i.title,body:i.body,url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,status:r,slug:c&&this._slug.trim()||void 0,publishedAt:c?this._getPublishedAtSubmitValue(r):void 0,visibility:c?this._visibilityLocked?void 0:this._visibility:void 0,rating:i.rating,collectionIds:c?[...this._collectionIds]:[],attachments:s,replyToId:c?this._replyToId??void 0:void 0,replyThreadRootId:c?this._replyThreadRootId??void 0:void 0,replyRefreshKind:c?this._replyRefreshKind??void 0:void 0,replyRefreshId:c?this._replyRefreshId??void 0:void 0}}_buildSubmitDetail(e){let t=this._editor;if(!t)return null;let n=t.getData(),r=new Map((n.attachments??[]).map(e=>[e.clientId,e])),i=new Map(n.attachedTexts.map(e=>[e.clientId,e])),a=[];for(let e of n.attachmentOrder){let t=r.get(e);if(t){a.push({type:`media`,clientId:e,mediaId:t.mediaId,alt:t.alt||void 0});continue}let n=i.get(e);n?.bodyJson&&a.push({type:`text`,clientId:e,bodyJson:n.bodyJson,summary:n.summary,mediaId:n.mediaId,originalBodyJson:yE(n.originalBodyJson??null)})}return{format:this._format,title:n.title,body:n.body,url:n.url,quoteText:n.quoteText,quoteAuthor:n.quoteAuthor,slug:this._slug.trim()||void 0,publishedAt:this._getPublishedAtSubmitValue(e),status:e,visibility:this._visibilityLocked?void 0:this._visibility,rating:n.rating,collectionIds:[...this._collectionIds],attachments:a,editPostId:this._editPostId??this._draftSourceId??void 0,replyToId:this._replyToId??void 0,quietReply:this._quietReply||void 0,replyThreadRootId:this._replyThreadRootId??void 0,replyRefreshKind:this._replyRefreshKind??void 0,replyRefreshId:this._replyRefreshId??void 0}}_focusBlockedSubmitField(e){if(e===`published`&&this._getPublishedAtValidationMessage()!==null)return this._revealPublishedAtField(),!0;if(this._getSlugValidationMessage())return this._revealSlugField(),!0;if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<this._threadItems.length;t++){let n=this._threadItems[t],r=e[t];if(r){if(r.getUrlValidationMessage())return r.revealUrlValidation(),r.focusUrlInput(`end`),!0;if(r.getLinkTitleValidationMessage())return r.revealLinkTitleValidation(),r.focusLinkTitleInput(`end`),!0;if(n.format===`quote`&&!r._quoteText.trim())return r.focusInput(`end`),!0}}return!1}let t=this._editor;return t?t.getUrlValidationMessage()?(t.revealUrlValidation(),t.focusUrlInput(`end`),!0):t.getLinkTitleValidationMessage()?(t.revealLinkTitleValidation(),t.focusLinkTitleInput(`end`),!0):this._format===`quote`&&!t._quoteText.trim()?(t.focusInput(`end`),!0):!1:!1}_dispatchSubmit(e){if(this._loading||this._focusBlockedSubmitField(e))return!1;if(this._draftSourceId||(this._cancelDraftSaveTimer(),this._saveDraftToStorage()),this._threadItems.length>0){if(this._threadItems.length>20)return a(this._getThreadLimitMessage(),`error`),!1;let t=Array.from(this.querySelectorAll(`jant-compose-editor`));if(t.length!==this._threadItems.length)return!1;let n=[],r=[];for(let i=0;i<this._threadItems.length;i++){let a=this._threadItems[i],o=t[i];if(!o)return!1;n.push(this._buildEditorPostDetail(o,a.format,i,e)),r.push(...(o._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`))}return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n[0],editPostId:this._editPostId??this._draftSourceId??void 0,threadPosts:n,pendingAttachments:r}})),!0}let t=this._editor;if(!t)return!1;let n=this._buildSubmitDetail(e);if(!n)return!1;let r=(t._attachments??[]).filter(e=>e.status===`pending`||e.status===`processing`||e.status===`uploading`);return this.dispatchEvent(new CustomEvent(`jant:compose-submit-deferred`,{bubbles:!0,detail:{...n,pendingAttachments:r}})),!0}_saveDraftAndOpenDrafts(){this._finishDraftSaveAndOpenDrafts()}_finishDraftSaveAndOpenDrafts(){if(!this._dispatchSubmit(`draft`))return;this.reset();let e=()=>{clearTimeout(t),this.isConnected&&this._openDraftsPanel()},t=globalThis.setTimeout(()=>{document.removeEventListener(`jant:compose-submit-complete`,e)},1e4);document.addEventListener(`jant:compose-submit-complete`,e,{once:!0})}_finishSubmit(e){if(this._dispatchSubmit(e)){if(this.pageMode){this._loading=!0;return}this._closeDialog(),this.reset()}}_submit(e){this._showPublishPanel=!1,this._finishSubmit(e)}_toggleCollection(e){this._collectionIds.includes(e)?this._collectionIds=this._collectionIds.filter(t=>t!==e):this._collectionIds=[...this._collectionIds,e]}_selectedCollectionLabel(e){let t=this._collectionIds,n=e.find(e=>e.id===t[0]);if(!n)return``;if(t.length===1)return n.title;if(t.length===2){let r=e.find(e=>e.id===t[1]);return r?`${n.title}, ${r.title}`:n.title}return this.labels.collectionCountLabel.replace(`%name%`,n.title).replace(`%count%`,String(t.length-1))}_prepareCollectionPickerOrder(){this._collectionPickerOrder=$x(this.collections??[],this._collectionIds)}_focusCollectionPickerInitialTarget(){this.querySelector(`.compose-collection-search-input, .compose-collection-option, .compose-collection-add-action`)?.focus()}_focusCollectionSearchInput(){let e=this.querySelector(`.compose-collection-search-input`);if(!e)return!1;e.focus();let t=e.value.length;return e.setSelectionRange(t,t),!0}_closeCollectionPicker(e){if(this._showCollection=!1,this._collectionSearch=``,this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,e?.restoreFocus===`trigger`){this.updateComplete.then(()=>{this.querySelector(`.compose-collection-trigger`)?.focus()});return}e?.restoreFocus===`editor`&&this._restorePageEditorFocus()}_suppressNextCollectionOptionClick(e){this._suppressedCollectionOptionId=e,this._suppressCollectionOptionClickUntil=Date.now()+250}_isTouchViewport(){return globalThis.matchMedia?.(`(hover: none) and (pointer: coarse)`)?.matches??!1}_shouldAutofocusCollectionPicker(){return!this._isTouchViewport()}_shouldAutofocusFormatInput(){return!this._isTouchViewport()}_scheduleCollectionPickerAutofocus(){this._shouldAutofocusCollectionPicker()&&globalThis.requestAnimationFrame(()=>{this._showCollection&&this._focusCollectionPickerInitialTarget()})}_scheduleCollectionSearchFocus(){globalThis.requestAnimationFrame(()=>{this._showCollection&&(this._focusCollectionSearchInput()||this._focusCollectionPickerInitialTarget())})}_isPrintableCollectionSearchKey(e){return e.length===1&&e.trim().length>0}_handleCollectionTriggerKeydown=e=>{if(!(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)){if(e.key===`ArrowDown`){e.preventDefault(),this._scheduleCollectionSearchFocus();return}!this._showCollection||!this._isPrintableCollectionSearchKey(e.key)||(e.preventDefault(),this._collectionSearch+=e.key,this._scheduleCollectionSearchFocus())}};_getCollectionOptionElements(){return Array.from(this.querySelectorAll(`.compose-collection-option`))}_handleCollectionSearchKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this._closeCollectionPicker({restoreFocus:`trigger`});return}if(e.key!==`ArrowDown`)return;let[t]=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-add-action`),r=t??n;r&&(e.preventDefault(),r.focus())};_handleCollectionOptionKeydown=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this._getCollectionOptionElements(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`.compose-collection-add-action`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.compose-collection-search-input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._toggleCollection(t);return}e.key===`Enter`&&(e.preventDefault(),this._suppressNextCollectionOptionClick(t),this._closeCollectionPicker({restoreFocus:`trigger`}))};_handleCollectionOptionClick=e=>{if(this._suppressedCollectionOptionId===e&&Date.now()<=this._suppressCollectionOptionClickUntil){this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0;return}this._suppressedCollectionOptionId=null,this._suppressCollectionOptionClickUntil=0,this._toggleCollection(e)};_handleCollectionAddActionKeydown=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this._getCollectionOptionElements(),n=this.querySelector(`.compose-collection-search-input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};_updateCollectionPopoverSide(){let e=this.querySelector(`.compose-collection-trigger`),t=this.querySelector(`.compose-collection-popover[data-popover]`);if(!e||!t)return;let n=globalThis.visualViewport,r=n?.offsetTop??0,i=r+(n?.height??globalThis.innerHeight),a=e.getBoundingClientRect(),o=Math.max(0,i-12-a.bottom-4),s=Math.max(0,a.top-r-12-4);t.dataset.side=o>=s?`bottom`:`top`}_cancelSlugTimers(){this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null)}_currentSlugOwnerId(){return this._editPostId??this._draftSourceId??void 0}_hasManualSlug(){return this._slug.trim().length>0}_currentSuggestionTitle(){return this._editor?.getData().title.trim()??``}_canSuggestSlug(){return this._currentSuggestionTitle().length>0}_currentSuggestionKey(){return`${this._currentSlugOwnerId()??``}::${this._currentSuggestionTitle()}`}_scheduleSuggestedSlugRefresh(e=!1){if(!this._showPublishPanel||this._hasManualSlug())return;if(!this._canSuggestSlug()){this._slugSuggestRequestId+=1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``;return}let t=this._currentSuggestionKey();if(this._slugSuggestionKey!==t&&(this._suggestedSlug=``),!e&&!this._suggestedSlugLoading&&this._suggestedSlug&&this._slugSuggestionKey===t)return;this._slugSuggestTimer!==null&&(clearTimeout(this._slugSuggestTimer),this._slugSuggestTimer=null);let n=()=>void this._refreshSuggestedSlug(t);if(e){n();return}this._slugSuggestTimer=setTimeout(n,250)}async _refreshSuggestedSlug(e){if(this._slugSuggestTimer=null,this._hasManualSlug()||!this._canSuggestSlug())return;let t=++this._slugSuggestRequestId;this._suggestedSlugLoading=!0;let n=new URLSearchParams({mode:`suggest`}),r=this._currentSuggestionTitle();r&&n.set(`title`,r);let i=this._currentSlugOwnerId();i&&n.set(`postId`,i);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugSuggestRequestId||this._hasManualSlug()||!this._showPublishPanel)return;this._suggestedSlug=i.slug?.trim()??``,this._slugSuggestionKey=e}catch{}finally{t===this._slugSuggestRequestId&&(this._suggestedSlugLoading=!1)}}_scheduleSlugAvailabilityCheck(){if(!this._hasManualSlug()){this._slugTaken=!1,this._slugCheckLoading=!1;return}if(this._slugCheckTimer!==null&&(clearTimeout(this._slugCheckTimer),this._slugCheckTimer=null),this._getSlugSyncValidationMessage()){this._slugTaken=!1,this._slugCheckLoading=!1;return}this._slugCheckLoading=!0;let e=this._slug.trim();this._slugCheckTimer=setTimeout(()=>{this._checkSlugAvailability(e)},250)}async _checkSlugAvailability(e){this._slugCheckTimer=null;let t=++this._slugCheckRequestId,n=new URLSearchParams({mode:`check`,slug:e}),r=this._currentSlugOwnerId();r&&n.set(`postId`,r);try{let r=await fetch(`/api/posts/slug?${n.toString()}`);if(!r.ok)return;let i=await r.json();if(t!==this._slugCheckRequestId||this._slug.trim()!==e)return;this._slugTaken=i.available===!1}catch{}finally{t===this._slugCheckRequestId&&(this._slugCheckLoading=!1)}}_useSuggestedSlug(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugTaken=!1,this._slugCheckLoading=!1,this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()}))}_resetCustomSlug(){this._slug=``,this._slugTaken=!1,this._slugCheckLoading=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-slug-input`)?.focus()})}connectedCallback(){super.connectedCallback(),this._syncPublishPanelPresentation(),this.addEventListener(`keydown`,this._handleKeydown),this.addEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.addEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.addEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.addEventListener(`jant:compose-content-changed`,this._onContentChanged),this.addEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.addEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.addEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.addEventListener(`pointerdown`,this._handlePointerDown),document.addEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.addEventListener(`beforeunload`,this._onBeforeUnload),window.addEventListener(`resize`,this._handleViewportChange),window.addEventListener(`scroll`,this._handleViewportChange,{passive:!0}),globalThis.visualViewport?.addEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.addEventListener(`scroll`,this._handleViewportChange),this._dialogEl=this.closest(`dialog`),this._dialogEl&&(this._dialogEl.addEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.addEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.addEventListener(`click`,this._handleDialogClick)),this.pageMode&&this.updateComplete.then(()=>this._focusPageEditorOnMount())}disconnectedCallback(){super.disconnectedCallback(),this.removeEventListener(`keydown`,this._handleKeydown),this.removeEventListener(`jant:alt-panel-open`,this._handleAltPanelOpen),this.removeEventListener(`jant:alt-panel-close`,this._handleAltPanelClose),this.removeEventListener(`jant:attached-panel-open`,this._handleAttachedPanelOpen),this.removeEventListener(`jant:compose-content-changed`,this._onContentChanged),this.removeEventListener(`jant:file-picker-open`,this._handleFilePickerOpen),this.removeEventListener(`jant:file-picker-close`,this._handleFilePickerClose),this.removeEventListener(`jant:fullscreen-open`,this._handleFullscreenOpen),this.removeEventListener(`pointerdown`,this._handlePointerDown),document.removeEventListener(`jant:fullscreen-close`,this._handleFullscreenClose),window.removeEventListener(`beforeunload`,this._onBeforeUnload),window.removeEventListener(`resize`,this._handleViewportChange),window.removeEventListener(`scroll`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`resize`,this._handleViewportChange),globalThis.visualViewport?.removeEventListener(`scroll`,this._handleViewportChange),this._cancelSlugTimers(),this._destroyAttachedEditor(),this._cancelDraftSaveTimer(),this._dialogEl&&=(this._dialogEl.removeEventListener(`cancel`,this._handleDialogCancel),this._dialogEl.removeEventListener(`mousedown`,this._handleDialogMousedown),this._dialogEl.removeEventListener(`click`,this._handleDialogClick),null)}_handleFilePickerOpen=()=>{this._filePickerActive=!0,this._ignoreNextEscapeClose=!1};_handleFilePickerClose=e=>{this._filePickerActive=!1,this._ignoreNextEscapeClose=!!e.detail?.cancelled};_handlePointerDown=()=>{this._clearFilePickerEscapeState()};_syncPublishPanelPresentation(){let e=globalThis.matchMedia?.(cE)?.matches??!1;e!==this._publishPanelFullscreen&&(this._publishPanelFullscreen=e)}_handleViewportChange=()=>{this._syncPublishPanelPresentation(),this._showPublishPanel&&this.updateComplete.then(()=>this._updatePublishPanelLayout()),this._showCollection&&this.updateComplete.then(()=>this._updateCollectionPopoverSide())};_handleDialogCancel=e=>{e.preventDefault();let t=e;t.isComposing||t.keyCode===229||this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay()||this.requestClose()};_pointInOpenPopover(e,t){for(let n of document.querySelectorAll(`:popover-open`)){let r=n.getBoundingClientRect();if(e>=r.left&&e<=r.right&&t>=r.top&&t<=r.bottom)return!0}return!1}_handleDialogMousedown=e=>{let t=e;this._mousedownOnBackdrop=e.target===this._dialogEl&&!this._pointInOpenPopover(t.clientX,t.clientY),this._mousedownPos=this._mousedownOnBackdrop?{x:t.clientX,y:t.clientY}:null};_handleDialogClick=e=>{if(!this._dialogEl||e.target!==this._dialogEl||!this._mousedownOnBackdrop)return;let t=e;if(this._mousedownPos){let e=t.clientX-this._mousedownPos.x,n=t.clientY-this._mousedownPos.y;if(e*e+n*n>16)return}let n=document.getSelection();if(n&&!n.isCollapsed||this._pointInOpenPopover(t.clientX,t.clientY))return;let r=document.elementFromPoint(t.clientX,t.clientY);r instanceof globalThis.Element&&r.closest(sE)||this.requestClose()};_focusDialogShell(){let e=this.querySelector(`.compose-dialog-inner`);if(e){e.focus();return}this._dialogEl?.focus()}_restorePageEditorFocus(){this.updateComplete.then(()=>this._editor?.focusInput())}_dismissEscapeOverlay(){return this._confirmPanelOpen?(this.requestClose(),!0):this._addCollectionPanelOpen?(this._closeAddCollectionPanel(),!0):this._editor?.isEmojiPickerOpen()?(this._editor.closeEmojiPicker({restoreFocus:!0}),!0):this._showCollection?(this._closeCollectionPicker({restoreFocus:`editor`}),!0):this._showPublishPanel?(this._closePublishPanel(!0),!0):this._altPanelOpen?(this._closeAltPanel(),this._restorePageEditorFocus(),!0):this._draftMenuOpenId?(this._draftMenuOpenId=null,!0):this._draftsPanelOpen?(this._closeDraftsPanel(),!0):this._attachedPanelOpen?(this._cancelAttachedPanel(),!0):!1}_handleKeydown=t=>{let n=t;if(!(n.isComposing||n.keyCode===229)){if(n.key!==`Escape`&&this._clearFilePickerEscapeState(),n.key===`Escape`){if(n.preventDefault(),n.stopPropagation(),this._shouldIgnoreEscapeClose()||this._dismissEscapeOverlay())return;this.requestClose()}else if(n.key===`Enter`&&this._confirmPanelOpen)n.preventDefault(),this._handleConfirmSave();else if((n.metaKey||n.ctrlKey)&&n.key===`Enter`){if(t.preventDefault(),this._attachedPanelOpen){this._doneAttachedPanel();return}if(!this._canPublish()){this._focusBlockedSubmitField(`published`);return}this._submit(`published`)}else if((n.metaKey||n.ctrlKey)&&!n.altKey&&!n.shiftKey&&n.key>=`1`&&n.key<=String(e._FORMATS.length)){n.preventDefault();let t=e._FORMATS[Number(n.key)-1];this._threadItems.length>0?this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.dispatchEvent(new CustomEvent(`jant:format-change`,{detail:{format:t},bubbles:!0})):this._switchFormat(t)}}};_handleAltPanelOpen=e=>{this._altPanelIndex=e.detail.index,this._altPanelOpen=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-alt-input`)?.focus()})};_handleAltPanelClose=()=>{this._altPanelOpen=!1};_getAltAttachment(){return this._editor?._attachments[this._altPanelIndex]??null}_onAltInput(e){let t=e.target.value;this._editor?.updateAlt(this._altPanelIndex,t)}_closeAltPanel(){this._altPanelOpen=!1}_handleFullscreenClose=e=>{let t=this._editor;t&&(t.setEditorState(e.detail.json,e.detail.title,e.detail.showTitle,e.detail.selection),t.adoptPendingUploads(),this.updateComplete.then(()=>t.focusSelection(e.detail.selection))),this._replyExpanded=e.detail.replyExpanded};_buildFullscreenReplyContext(){return!this._replyToId||!this._replyToData?null:{contentHtml:this._replyToData.contentHtml,dateText:this._replyToData.dateText,expanded:this._replyExpanded}}_handleFullscreenOpen=e=>{e.detail.replyContext=this._buildFullscreenReplyContext()};_handleAttachedPanelOpen=e=>{this._attachedTextIndex=e.detail.index,this._attachedPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-attached-tiptap`);if(!e)return;let t=this._editor?._attachedTexts[this._attachedTextIndex]?.bodyJson??null;this._attachedTextSnapshot=t?JSON.parse(JSON.stringify(t)):null,this._attachedEditor=rE({element:e,placeholder:this.labels.attachedTextPlaceholder,content:t,toolbarMode:`compose`}),this._focusAttachedEditorBoundary(t)})};_focusAttachedEditorBoundary(e){if(!this._attachedEditor)return;let t=yE(e??this._attachedEditor.getJSON())?`end`:`start`;this._attachedEditor.commands.focus(t)}_isAttachedTextDirty(){return this._attachedEditor?JSON.stringify(yE(this._attachedEditor.getJSON()))!==JSON.stringify(yE(this._attachedTextSnapshot)):!1}_destroyAttachedEditor(){this._attachedEditor&&=(this._attachedEditor.destroy(),null),this._attachedTextSnapshot=null}_doneAttachedPanel(){if(this._attachedEditor){let e=this._attachedEditor.getJSON(),t=this._attachedEditor.getHTML();this._editor?.updateAttachedText(this._attachedTextIndex,e,t)}this._confirmForAttachedText=!1,this._destroyAttachedEditor(),this._attachedPanelOpen=!1,this._editor?.closeAttachedPanel(this._attachedTextIndex)}_cancelAttachedPanel(){if(this._isAttachedTextDirty()){this._confirmForDrafts=!1,this._confirmForAttachedText=!0,this._confirmPanelOpen=!0;return}this._discardAttachedPanel()}_handleAttachedEditorMouseDown(e){e.target===e.currentTarget&&(e.preventDefault(),this._focusAttachedEditorBoundary())}_handleDraftButtonClick(){this._loading||(this._hasContent()?(this._confirmForDrafts=!0,this._confirmPanelOpen=!0):this._openDraftsPanel())}async _openDraftsPanel(){this._draftsPanelOpen=!0,this._draftsLoading=!0,this._draftsError=null,this._draftMenuOpenId=null;try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(!e.ok)throw Error(`Failed to load drafts`);let t=await e.json(),n=(Array.isArray(t)?t:t.posts??[]).map(e=>({id:e.id,format:e.format,title:(e.format===`quote`?e.sourceName:e.title)??null,bodyText:e.bodyText??null,bodyHtml:e.bodyHtml??null,url:(e.format===`quote`?e.sourceUrl:e.url)??null,quoteText:e.quoteText??null,replyToId:e.replyToId??null,updatedAt:e.updatedAt,mediaAttachments:(e.attachments??[]).filter(e=>e.type===`media`).map(e=>({id:e.id,previewUrl:e.previewUrl,alt:e.alt??null,mimeType:e.mimeType}))})),r=new Set(n.map(e=>e.id));this._drafts=n.filter(e=>!e.replyToId||!r.has(e.replyToId))}catch{this._draftsError=`Could not load drafts. Try again.`,this._drafts=[]}finally{this._draftsLoading=!1}}_closeDraftsPanel(){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.updateComplete.then(()=>this._editor?.focusInput())}async _populateEditorFromPost(e,t){let{media:n,textAttachments:r,attachmentOrder:i}=await TE(t.attachments??[]);e.populate({format:t.format,title:t.format===`quote`?void 0:t.title??void 0,bodyJson:t.body??void 0,url:t.format===`quote`?t.sourceUrl??void 0:t.url??void 0,quoteText:t.quoteText??void 0,quoteAuthor:t.format===`quote`?t.sourceName??void 0:void 0,rating:t.rating??void 0,media:n,textAttachments:r,attachmentOrder:i})}async _loadDraft(e){this._draftsPanelOpen=!1,this._draftMenuOpenId=null,this.reset();let t=await fetch(`/api/posts/${e}`);if(!t.ok)return;let n=await t.json();if(this._draftSourceId=e,this._format=n.format,this._slug=n.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=n.publishedAt?xE(n.publishedAt):``,this._publishedAtTimeMinutes=n.publishedAt?CE(n.publishedAt):null,this._originalPublishedAt=n.publishedAt??null,this._initialPublishedAtTimeMinutes=this._publishedAtTimeMinutes,this._initialPublishedAtInput=this._publishedAtInput,this._initialSlug=this._slug.trim(),this._visibility=n.visibility??`public`,this._visibilityLocked=!!n.replyToId,n.collectionIds?.length&&(this._collectionIds=n.collectionIds),n.replyToId&&(this._replyToId=n.replyToId,await this._fetchReplyContext(n.replyToId)),n.threadId===n.id||n.threadId===void 0)try{let e=await fetch(`/api/posts?status=draft&limit=50`);if(e.ok){let t=await e.json(),r=(Array.isArray(t)?t:t.posts??[]).filter(e=>e.id!==n.id&&e.threadId===n.id&&e.status===`draft`).map(e=>({id:e.id,format:e.format,replyToId:e.replyToId??null,title:e.title??null,body:e.body??null,url:e.url??null,sourceUrl:e.sourceUrl??null,sourceName:e.sourceName??null,quoteText:e.quoteText??null,rating:e.rating??null,attachments:e.attachments??[],visibility:e.visibility??null}));if(r.length>0){let e=[],t=n.id;for(let n=0;n<r.length;n++){let n=r.find(e=>e.replyToId===t);if(!n)break;e.push(n),t=n.id}for(let t of r)e.includes(t)||e.push(t);this._threadItems=[{id:oE(),format:n.format},...e.map(e=>({id:oE(),format:e.format}))],this._focusedThreadIndex=0,await this.updateComplete;let i=Array.from(this.querySelectorAll(`jant-compose-editor`)),a=i[0];a&&await this._populateEditorFromPost(a,n);for(let t=0;t<e.length;t++){let r=i[t+1];if(!r)continue;let a=e[t];await this._populateEditorFromPost(r,{id:a.id,threadId:n.id,format:a.format,replyToId:a.replyToId,title:a.title,body:a.body,url:a.url,sourceUrl:a.sourceUrl,sourceName:a.sourceName,quoteText:a.quoteText,rating:a.rating,attachments:a.attachments,visibility:a.visibility})}globalThis.requestAnimationFrame(()=>{i[0]?.focusInput(),this._captureInitialSnapshot()});return}}}catch{}await this.updateComplete;let r=this._editor;r&&await this._populateEditorFromPost(r,n),globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._captureInitialSnapshot()})}async _deleteDraft(e){this._draftMenuOpenId=null,this._drafts=this._drafts.filter(t=>t.id!==e);try{if(!(await fetch(`/api/posts/${e}`,{method:`DELETE`})).ok)throw Error();a(this.labels.draftDeleted)}catch{a(`Failed to delete draft. Try again.`,`error`),this._openDraftsPanel()}}_formatDraftDate(e){let t=Date.now()/1e3-e;return t<60?`now`:t<3600?`${Math.floor(t/60)}m`:t<86400?`${Math.floor(t/3600)}h`:t<604800?`${Math.floor(t/86400)}d`:new Date(e*1e3).toLocaleDateString(void 0,{month:`short`,day:`numeric`})}_getDraftPreview(e){return e.bodyText?e.bodyText:e.title?e.title:e.quoteText?e.quoteText:e.url?e.url:null}_getThreadLimitMessage(){return this.labels.threadLimitReached||`Threads can include up to 20 posts.`}static _DRAFT_KEY=`jant:compose-draft`;static _EDIT_DRAFT_KEY_PREFIX=`jant:compose-edit:`;static _DRAFT_MAX_AGE=10080*60*1e3;_currentDraftStorageKey(){return this._editPostId?e._EDIT_DRAFT_KEY_PREFIX+this._editPostId:e._DRAFT_KEY}_onContentChanged=()=>{this.requestUpdate(),this._hasManualSlug()||this._scheduleSuggestedSlugRefresh(),this._draftSourceId||this._scheduleDraftSave()};_cancelDraftSaveTimer(){this._draftSaveTimer!==null&&(clearTimeout(this._draftSaveTimer),this._draftSaveTimer=null)}_scheduleDraftSave(){this._cancelDraftSaveTimer(),this._draftSaveTimer=setTimeout(()=>this._saveDraftToStorage(),1e3)}_onBeforeUnload=e=>{if(this._suppressBeforeUnload)return;this._draftSaveTimer!==null&&(this._cancelDraftSaveTimer(),this._saveDraftToStorage());let t=this.closest(`dialog`);this._hasUnsavedChanges()&&(this.pageMode||t?.open===!0)&&(e.preventDefault(),e.returnValue=``)};_saveDraftToStorage(){if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));if(!e.some(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.rating>0||t.attachedTexts.length>0||t.attachments.length>0})){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let t=this._threadItems.map((t,n)=>{let r=e[n];if(!r)return null;let i=r.getData();return{format:t.format,title:i.title,bodyJson:r.getNormalizedBodyJson(),url:i.url,quoteText:i.quoteText,quoteAuthor:i.quoteAuthor,attachedTexts:i.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...i.attachmentOrder]}}).filter(e=>e!==null),n={format:this._threadItems[0]?.format??this._format,title:``,bodyJson:null,url:``,quoteText:``,quoteAuthor:``,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:0,showTitle:!1,showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:[],attachmentOrder:[],threadItems:t,savedAt:Date.now()};try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(n))}catch{}return}let e=this._editor;if(!e)return;if(!this._hasUnsavedChanges()){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let t=e.getData();if(!(t.body||t.title.trim()||t.url.trim()||t.quoteText.trim()||t.quoteAuthor.trim()||t.rating>0||t.attachedTexts.length>0)){globalThis.localStorage.removeItem(this._currentDraftStorageKey());return}let n={format:this._format,title:t.title,bodyJson:e.getNormalizedBodyJson(),url:t.url,quoteText:t.quoteText,quoteAuthor:t.quoteAuthor,slug:this._slug,publishedAtInput:this._publishedAtInput,publishedAtTimeMinutes:this._publishedAtTimeMinutes,visibility:this._visibility,rating:t.rating,showTitle:this._format===`note`&&t.title.trim().length>0?e._showTitle:!1,showRating:t.rating>0?e._showRating:!1,collectionIds:[...this._collectionIds],replyToId:this._replyToId,attachedTexts:t.attachedTexts.map(e=>({clientId:e.clientId,bodyJson:e.bodyJson,bodyHtml:e.bodyHtml,summary:e.summary})),attachmentOrder:[...t.attachmentOrder],savedAt:Date.now()};try{globalThis.localStorage.setItem(this._currentDraftStorageKey(),JSON.stringify(n))}catch{}}_clearDraftFromStorage(){this._cancelDraftSaveTimer(),globalThis.localStorage.removeItem(this._currentDraftStorageKey())}clearLocalDraftFromStorage(){this._clearDraftFromStorage()}clearEditDraftFromStorage(t){globalThis.localStorage.removeItem(e._EDIT_DRAFT_KEY_PREFIX+t)}async restoreLocalDraft(t){if(this._editPostId||this._draftSourceId||this._hasContent())return;let n;try{n=globalThis.localStorage.getItem(e._DRAFT_KEY)}catch{return}if(!n)return;let r;try{r=JSON.parse(n)}catch{globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(Date.now()-r.savedAt>e._DRAFT_MAX_AGE){globalThis.localStorage.removeItem(e._DRAFT_KEY);return}if(t?.expectedReplyToId!==void 0&&r.replyToId!==t.expectedReplyToId)return;if(this._collectionIds=[...r.collectionIds??[]],this._slug=r.slug??``,this._slugTaken=!1,this._slugCheckLoading=!1,this._suggestedSlug=``,this._suggestedSlugLoading=!1,this._slugSuggestionKey=``,this._publishedAtInput=r.publishedAtInput??``,this._publishedAtTimeMinutes=r.publishedAtTimeMinutes??null,this._visibility=r.visibility??`public`,r.replyToId&&(this._replyToId=r.replyToId,this._visibilityLocked=!0,await this._fetchReplyContext(r.replyToId)),r.threadItems&&r.threadItems.length>=2){this._format=r.threadItems[0].format,this._threadItems=r.threadItems.map(e=>({id:oE(),format:e.format})),this._focusedThreadIndex=0,await this.updateComplete;let e=Array.from(this.querySelectorAll(`jant-compose-editor`));for(let t=0;t<r.threadItems.length;t++){let n=r.threadItems[t],i=e[t];if(!i)continue;let a=n.attachedTexts?.flatMap(e=>{let t=yE(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});i.populate({format:n.format,title:n.title||void 0,bodyJson:n.bodyJson?JSON.stringify(n.bodyJson):void 0,url:n.url||void 0,quoteText:n.quoteText||void 0,quoteAuthor:n.quoteAuthor||void 0,textAttachments:a?.length?a:void 0,attachmentOrder:n.attachmentOrder})}this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()});return}this._format=r.format,await this.updateComplete;let i=r.attachedTexts?.flatMap(e=>{let t=yE(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});this._editor?.populate({format:r.format,title:r.title||void 0,bodyJson:r.bodyJson?JSON.stringify(r.bodyJson):void 0,url:r.url||void 0,quoteText:r.quoteText||void 0,quoteAuthor:r.quoteAuthor||void 0,rating:r.rating||void 0,showTitle:r.showTitle,showRating:r.showRating,textAttachments:i?.length?i:void 0,attachmentOrder:r.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),globalThis.requestAnimationFrame(()=>{this._captureInitialSnapshot()})}_restoreEditDraftIfAvailable(t){let n=e._EDIT_DRAFT_KEY_PREFIX+t,r;try{r=globalThis.localStorage.getItem(n)}catch{return!1}if(!r)return!1;let i;try{i=JSON.parse(r)}catch{return globalThis.localStorage.removeItem(n),!1}if(Date.now()-i.savedAt>e._DRAFT_MAX_AGE)return globalThis.localStorage.removeItem(n),!1;this._format=i.format,this._collectionIds=[...i.collectionIds??[]],this._slug=i.slug??``,this._publishedAtInput=i.publishedAtInput??``,this._publishedAtTimeMinutes=i.publishedAtTimeMinutes??null,this._visibility=i.visibility??`public`;let o=i.attachedTexts?.flatMap(e=>{let t=yE(e.bodyJson);return t?[{clientId:e.clientId,bodyJson:JSON.stringify(t),bodyHtml:e.bodyHtml,summary:e.summary}]:[]});return this._editor?.populate({format:i.format,title:i.title||void 0,bodyJson:i.bodyJson?JSON.stringify(i.bodyJson):void 0,url:i.url||void 0,quoteText:i.quoteText||void 0,quoteAuthor:i.quoteAuthor||void 0,rating:i.rating||void 0,showTitle:i.showTitle,showRating:i.showRating,textAttachments:o?.length?o:void 0,attachmentOrder:i.attachmentOrder}),this._draftRestored=!0,a(this.labels.draftRestored),!0}async _focusPageEditorOnMount(){this._pageFocusApplied||(this.autoRestoreDraft&&await this.restoreLocalDraft(),await this.updateComplete,globalThis.requestAnimationFrame(()=>{this._editor?.focusInput(),this._pageFocusApplied=!0}))}_renderDraftsPanel(){return this._draftsPanelOpen?u`
409
409
  <div class="compose-drafts-panel">
410
410
  <div class="compose-alt-header">
411
411
  <button
@@ -572,7 +572,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
572
572
  ?disabled=${this._loading}
573
573
  @click=${()=>this._handleDraftButtonClick()}
574
574
  >
575
- ${iE(eE.drafts)}
575
+ ${pE(lE.drafts)}
576
576
  </button>`}
577
577
  </div>
578
578
  </header>
@@ -598,10 +598,10 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
598
598
  @click=${()=>{let e=!this._showCollection;this._showPublishPanel=!1,e&&this._prepareCollectionPickerOrder(),this._showCollection=e,e||this._closeCollectionPicker()}}
599
599
  >
600
600
  <span class="compose-collection-trigger-icon">
601
- ${oE(rE.collection,`compose-collection-trigger-svg`)}
601
+ ${hE(fE.collection,`compose-collection-trigger-svg`)}
602
602
  </span>
603
603
  <span class="compose-collection-label">${a}</span>
604
- ${oE(rE.chevron,`compose-collection-chevron`)}
604
+ ${hE(fE.chevron,`compose-collection-chevron`)}
605
605
  </button>
606
606
  <div
607
607
  class="compose-collection-popover"
@@ -610,7 +610,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
610
610
  >
611
611
  ${e.length>0?u`<div class="compose-collection-popover-header">
612
612
  <label class="compose-collection-search-shell">
613
- ${oE(rE.search,`compose-collection-search-icon`)}
613
+ ${hE(fE.search,`compose-collection-search-icon`)}
614
614
  <input
615
615
  type="text"
616
616
  role="combobox"
@@ -666,7 +666,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
666
666
  stroke-linecap="round"
667
667
  stroke-linejoin="round"
668
668
  />
669
- </svg>`:oE(rE.plusCircle,`compose-collection-option-plus-circle`)}
669
+ </svg>`:hE(fE.plusCircle,`compose-collection-option-plus-circle`)}
670
670
  </span>
671
671
  </button>
672
672
  `}):u`<div class="compose-collection-empty">
@@ -681,7 +681,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
681
681
  @click=${()=>{this._closeCollectionPicker(),this._addCollectionPanelOpen=!0}}
682
682
  >
683
683
  <span class="compose-collection-add-icon">
684
- ${oE(rE.plus,`compose-collection-add-svg`)}
684
+ ${hE(fE.plus,`compose-collection-add-svg`)}
685
685
  </span>
686
686
  ${this.labels.addCollection}
687
687
  </button>
@@ -855,7 +855,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
855
855
  </button>
856
856
  </div>
857
857
  </div>
858
- `}_getSubmitLabel(){return this._editPostId?this.labels.update:this._replyToId?this._quietReply?this.labels.quietReplyLabel:this.labels.reply:this._visibility===`latest_hidden`?this.labels.postHiddenFromLatest:this._visibility===`private`?this.labels.postPrivately:this.labels.post}_getSlugSyncValidationMessage(){let e=FS(this._slug);return e===`invalid`?this.labels.publishSlugInvalid:e===`reserved`?this.labels.publishSlugReserved:null}_getSlugValidationMessage(){return this._getSlugSyncValidationMessage()||(this._hasManualSlug()&&this._slugTaken?this.labels.publishSlugTaken:null)}_getSlugPreviewUrl(){if(!this._hasManualSlug()||this._getSlugValidationMessage())return null;let e=o(`/${this._slug.trim()}`),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}_getSlugPreviewParts(){let e=this._getSlugPreviewUrl();if(!e)return null;let t=new URL(e);return{full:e,origin:t.origin,path:`${t.pathname}${t.search}${t.hash}`}}_getSlugStatusMessage(){return this._hasManualSlug()?this._getSlugValidationMessage()?this._getSlugValidationMessage():null:this._suggestedSlugLoading?this.labels.publishSlugGenerating:null}_getCurrentTimestamp(){return Math.floor(Date.now()/1e3)}_getPublishedAtMaxInput(){return fE(this._getCurrentTimestamp())}_getPublishedAtTimeMinutes(){return this._publishedAtTimeMinutes??mE(this._getCurrentTimestamp())}_hasPublishedAtValue(){return this._publishedAtInput.trim().length>0}_getPublishedAtValidationMessage(){return this._hasPublishedAtValue()?pE(this._publishedAtInput)===null?this.labels.publishDateInvalid:this._publishedAtInput>this._getPublishedAtMaxInput()?this.labels.publishDateFutureError:null:null}_getPublishedAtSummary(){if(this._editPostId||this._draftSourceId){if(this._publishedAtInput===this._initialPublishedAtInput)return null;if(!this._hasPublishedAtValue())return{input:``,text:this.labels.publishDateSummaryNow}}if(this._getPublishedAtValidationMessage()!==null)return null;let e=pE(this._publishedAtInput);return e===null?null:{input:this._publishedAtInput,text:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(e.year,e.monthIndex,e.day))}}_getSlugSummary(){let e=this._slug.trim();if(e&&this._getSlugValidationMessage()!==null)return null;if(this._editPostId||this._draftSourceId){if(e===this._initialSlug)return null;if(!e)return{kind:`slug`,text:this.labels.publishSlugSummaryAuto,actionLabel:this.labels.publishSlugSummaryAction,value:e}}return e?{kind:`slug`,text:`/${e}`,actionLabel:this.labels.publishSlugSummaryAction,value:e}:null}_getPublishSummaryChips(){let e=[],t=this._getPublishedAtSummary();t!==null&&e.push({kind:`publishedAt`,text:t.text,actionLabel:this.labels.publishDateSummaryAction,value:t.input});let n=this._getSlugSummary();return n!==null&&e.push(n),e}_getPublishedAtSubmitValue(e){if(e===`draft`)return;let t=hE(this._publishedAtInput,this._getPublishedAtTimeMinutes());if(t!==null)return this._originalPublishedAt!==null&&this._publishedAtInput===this._initialPublishedAtInput&&this._publishedAtTimeMinutes===this._initialPublishedAtTimeMinutes?Math.min(this._originalPublishedAt,this._getCurrentTimestamp()):Math.min(t,this._getCurrentTimestamp());if(!(this._publishedAtInput.trim().length>0)&&this._editPostId)return this._getCurrentTimestamp()}_openPublishPanelAndFocus(e){this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!0,this._confirmPanelOpen=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}_revealSlugField(){this._openPublishPanelAndFocus(`.compose-publish-slug-input`)}_revealPublishedAtField(){this._openPublishPanelAndFocus(`.compose-publish-date-input`)}_canPublish(){if(this._loading||this._getPublishedAtValidationMessage()||this._getSlugValidationMessage())return!1;if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));if(e.length===0)return!1;for(let t of e)if(t.getUrlValidationMessage()||t.getLinkTitleValidationMessage())return!1;return e.every(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.attachments.length>0})}let e=this._editor;if(!e||e.getUrlValidationMessage()||e.getLinkTitleValidationMessage())return!1;let t=e.getData();return this._format===`link`?t.url.trim().length>0:this._format===`quote`?t.quoteText.trim().length>0:this._hasContent()}_focusPublishPanelInitialField(){let e=this._visibilityLocked?`.compose-publish-date-input`:`.compose-publish-option[role='radio']`;this.querySelector(e)?.focus()}_closePublishPanel(e=!1){this._showPublishPanel&&(this._showPublishPanel=!1,e&&this.updateComplete.then(()=>this._restorePageEditorFocus()))}_togglePublishPanel(){this._showCollection=!1,this._collectionSearch=``;let e=!this._showPublishPanel;this._showPublishPanel=e,e&&(this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>this._focusPublishPanelInitialField()))}_setVisibility(t){this._visibilityLocked||(this._visibility=t,!this._editPostId&&!this._draftSourceId&&!this._replyToId&&(e._lastNewPostVisibility=t,this._sourceCollectionId&&e._setCollectionVisibility(this._sourceCollectionId,t)))}_onSlugInput(e){if(this._slug=e.target.value.toLowerCase(),this._slugTaken=!1,this._slugCheckLoading=!1,this._hasManualSlug()){this._scheduleSlugAvailabilityCheck();return}this._scheduleSuggestedSlugRefresh()}_onPublishedAtInput(e){this._publishedAtInput=e.target.value}_resetPublishedAt(){let e=this._getCurrentTimestamp();this._publishedAtInput=fE(e),this._publishedAtTimeMinutes=mE(e),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-date-input`)?.focus()})}_renderVisibilityIcon(e,t=`menu`){let n=T({"compose-publish-visibility-icon":!0,"compose-publish-visibility-icon-toggle":t===`toggle`,"compose-publish-visibility-icon-public":e===`public`,"compose-publish-visibility-icon-latest_hidden":e===`latest_hidden`,"compose-publish-visibility-icon-private":e===`private`});return aE(tE[e],n)}_renderPublishVisibilityChip(e,t){let n=this._visibility===e;return u`
858
+ `}_getSubmitLabel(){return this._editPostId?this.labels.update:this._replyToId?this._quietReply?this.labels.quietReplyLabel:this.labels.reply:this._visibility===`latest_hidden`?this.labels.postHiddenFromLatest:this._visibility===`private`?this.labels.postPrivately:this.labels.post}_getSlugSyncValidationMessage(){let e=FS(this._slug);return e===`invalid`?this.labels.publishSlugInvalid:e===`reserved`?this.labels.publishSlugReserved:null}_getSlugValidationMessage(){return this._getSlugSyncValidationMessage()||(this._hasManualSlug()&&this._slugTaken?this.labels.publishSlugTaken:null)}_getSlugPreviewUrl(){if(!this._hasManualSlug()||this._getSlugValidationMessage())return null;let e=o(`/${this._slug.trim()}`),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}_getSlugPreviewParts(){let e=this._getSlugPreviewUrl();if(!e)return null;let t=new URL(e);return{full:e,origin:t.origin,path:`${t.pathname}${t.search}${t.hash}`}}_getSlugStatusMessage(){return this._hasManualSlug()?this._getSlugValidationMessage()?this._getSlugValidationMessage():null:this._suggestedSlugLoading?this.labels.publishSlugGenerating:null}_getCurrentTimestamp(){return Math.floor(Date.now()/1e3)}_getPublishedAtMaxInput(){return xE(this._getCurrentTimestamp())}_getPublishedAtTimeMinutes(){return this._publishedAtTimeMinutes??CE(this._getCurrentTimestamp())}_hasPublishedAtValue(){return this._publishedAtInput.trim().length>0}_getPublishedAtValidationMessage(){return this._hasPublishedAtValue()?SE(this._publishedAtInput)===null?this.labels.publishDateInvalid:this._publishedAtInput>this._getPublishedAtMaxInput()?this.labels.publishDateFutureError:null:null}_getPublishedAtSummary(){if(this._editPostId||this._draftSourceId){if(this._publishedAtInput===this._initialPublishedAtInput)return null;if(!this._hasPublishedAtValue())return{input:``,text:this.labels.publishDateSummaryNow}}if(this._getPublishedAtValidationMessage()!==null)return null;let e=SE(this._publishedAtInput);return e===null?null:{input:this._publishedAtInput,text:new Intl.DateTimeFormat(void 0,{month:`short`,day:`numeric`,year:`numeric`}).format(new Date(e.year,e.monthIndex,e.day))}}_getSlugSummary(){let e=this._slug.trim();if(e&&this._getSlugValidationMessage()!==null)return null;if(this._editPostId||this._draftSourceId){if(e===this._initialSlug)return null;if(!e)return{kind:`slug`,text:this.labels.publishSlugSummaryAuto,actionLabel:this.labels.publishSlugSummaryAction,value:e}}return e?{kind:`slug`,text:`/${e}`,actionLabel:this.labels.publishSlugSummaryAction,value:e}:null}_getPublishSummaryChips(){let e=[],t=this._getPublishedAtSummary();t!==null&&e.push({kind:`publishedAt`,text:t.text,actionLabel:this.labels.publishDateSummaryAction,value:t.input});let n=this._getSlugSummary();return n!==null&&e.push(n),e}_getPublishedAtSubmitValue(e){if(e===`draft`)return;let t=wE(this._publishedAtInput,this._getPublishedAtTimeMinutes());if(t!==null)return this._originalPublishedAt!==null&&this._publishedAtInput===this._initialPublishedAtInput&&this._publishedAtTimeMinutes===this._initialPublishedAtTimeMinutes?Math.min(this._originalPublishedAt,this._getCurrentTimestamp()):Math.min(t,this._getCurrentTimestamp());if(!(this._publishedAtInput.trim().length>0)&&this._editPostId)return this._getCurrentTimestamp()}_openPublishPanelAndFocus(e){this._showCollection=!1,this._collectionSearch=``,this._showPublishPanel=!0,this._confirmPanelOpen=!1,this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}_revealSlugField(){this._openPublishPanelAndFocus(`.compose-publish-slug-input`)}_revealPublishedAtField(){this._openPublishPanelAndFocus(`.compose-publish-date-input`)}_canPublish(){if(this._loading||this._getPublishedAtValidationMessage()||this._getSlugValidationMessage())return!1;if(this._threadItems.length>0){let e=Array.from(this.querySelectorAll(`jant-compose-editor`));if(e.length===0)return!1;for(let t of e)if(t.getUrlValidationMessage()||t.getLinkTitleValidationMessage())return!1;return e.every(e=>{let t=e.getData();return!!t.body||!!t.title.trim()||!!t.url.trim()||!!t.quoteText.trim()||t.attachments.length>0})}let e=this._editor;if(!e||e.getUrlValidationMessage()||e.getLinkTitleValidationMessage())return!1;let t=e.getData();return this._format===`link`?t.url.trim().length>0:this._format===`quote`?t.quoteText.trim().length>0:this._hasContent()}_focusPublishPanelInitialField(){let e=this._visibilityLocked?`.compose-publish-date-input`:`.compose-publish-option[role='radio']`;this.querySelector(e)?.focus()}_closePublishPanel(e=!1){this._showPublishPanel&&(this._showPublishPanel=!1,e&&this.updateComplete.then(()=>this._restorePageEditorFocus()))}_togglePublishPanel(){this._showCollection=!1,this._collectionSearch=``;let e=!this._showPublishPanel;this._showPublishPanel=e,e&&(this._scheduleSuggestedSlugRefresh(!0),this.updateComplete.then(()=>this._focusPublishPanelInitialField()))}_setVisibility(t){this._visibilityLocked||(this._visibility=t,!this._editPostId&&!this._draftSourceId&&!this._replyToId&&(e._lastNewPostVisibility=t,this._sourceCollectionId&&e._setCollectionVisibility(this._sourceCollectionId,t)))}_onSlugInput(e){if(this._slug=e.target.value.toLowerCase(),this._slugTaken=!1,this._slugCheckLoading=!1,this._hasManualSlug()){this._scheduleSlugAvailabilityCheck();return}this._scheduleSuggestedSlugRefresh()}_onPublishedAtInput(e){this._publishedAtInput=e.target.value}_resetPublishedAt(){let e=this._getCurrentTimestamp();this._publishedAtInput=xE(e),this._publishedAtTimeMinutes=CE(e),this.updateComplete.then(()=>{this.querySelector(`.compose-publish-date-input`)?.focus()})}_renderVisibilityIcon(e,t=`menu`){let n=T({"compose-publish-visibility-icon":!0,"compose-publish-visibility-icon-toggle":t===`toggle`,"compose-publish-visibility-icon-public":e===`public`,"compose-publish-visibility-icon-latest_hidden":e===`latest_hidden`,"compose-publish-visibility-icon-private":e===`private`});return mE(uE[e],n)}_renderPublishVisibilityChip(e,t){let n=this._visibility===e;return u`
859
859
  <button
860
860
  type="button"
861
861
  class=${T({"compose-publish-chip":!0,"compose-publish-chip-selected":n})}
@@ -1196,7 +1196,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1196
1196
  title=${this.labels.publishSettings}
1197
1197
  @click=${()=>this._togglePublishPanel()}
1198
1198
  >
1199
- ${sE(nE.chevron,`compose-publish-toggle-chevron`)}
1199
+ ${gE(dE.chevron,`compose-publish-toggle-chevron`)}
1200
1200
  </button>
1201
1201
  </div>
1202
1202
  ${this._renderDesktopPublishPanel()}
@@ -1260,7 +1260,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1260
1260
  </div>
1261
1261
  </div>
1262
1262
  </div>
1263
- `}_addThreadItem(){if((this._threadItems.length===0?2:this._threadItems.length+1)>20){a(this._getThreadLimitMessage(),`error`);return}let e=this._threadItems.length>0?this._threadItems[this._threadItems.length-1].format:this._format;if(this._threadItems.length===0){let t=this._editor,n=t?.getEditorState()??null,r=t?.getData(),i=t?.getNormalizedBodyJson()??null;this._threadItems=[{id:ZT(),format:this._format},{id:ZT(),format:e}];let a=t?._rating??0,o=t?._showRating??!1;(n||r)&&this.updateComplete.then(()=>{let e=this.querySelectorAll(`jant-compose-editor`)[0];if(!e)return;n&&e.setEditorState(n.json,n.title,n.showTitle,n.selection),r&&(this._format===`link`&&r.url?e._url=r.url:this._format===`quote`&&(r.quoteText&&(e._quoteText=r.quoteText),r.quoteAuthor&&(e._quoteAuthor=r.quoteAuthor)),i&&(e._bodyJson=i));let s=t?._attachments??[],c=t?._attachmentOrder??[],l=t?._attachedTexts??[];s.length>0&&(e._attachments=[...s],e._attachmentOrder=[...c]),l.length>0&&(e._attachedTexts=[...l]),a>0&&(e._rating=a,e._showRating=o)})}else this._threadItems=[...this._threadItems,{id:ZT(),format:e}];this._focusedThreadIndex=this._threadItems.length-1,this.updateComplete.then(()=>{this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.focusInput()})}_removeThreadItem(e){if(this._threadItems.length<=1)return;let t=this._threadItems.filter((t,n)=>n!==e);if(t.length===1){let n=this.querySelectorAll(`jant-compose-editor`)[e===0?1:0]??null,r=n?.getEditorState()??null,i=n?.getData(),a=n?.getNormalizedBodyJson()??null,o=t[0].format,s=n?._rating??0,c=n?._showRating??!1;this._threadItems=[],this._focusedThreadIndex=0,this._format=o,this.updateComplete.then(()=>{let e=this._editor;if(!e)return;e.format=o,r&&e.setEditorState(r.json,r.title,r.showTitle,r.selection),i&&(o===`link`&&i.url?e._url=i.url:o===`quote`&&(i.quoteText&&(e._quoteText=i.quoteText),i.quoteAuthor&&(e._quoteAuthor=i.quoteAuthor)),a&&(e._bodyJson=a));let t=n?._attachments??[],l=n?._attachmentOrder??[],u=n?._attachedTexts??[];t.length>0&&(e._attachments=[...t],e._attachmentOrder=[...l]),u.length>0&&(e._attachedTexts=[...u]),s>0&&(e._rating=s,e._showRating=c),e.focusInput(),this.requestUpdate()})}else this._threadItems=t,this._focusedThreadIndex=Math.min(this._focusedThreadIndex,t.length-1)}_renderThreadPost(e,t,n){return u`
1263
+ `}_addThreadItem(){if((this._threadItems.length===0?2:this._threadItems.length+1)>20){a(this._getThreadLimitMessage(),`error`);return}let e=this._threadItems.length>0?this._threadItems[this._threadItems.length-1].format:this._format;if(this._threadItems.length===0){let t=this._editor,n=t?.getEditorState()??null,r=t?.getData(),i=t?.getNormalizedBodyJson()??null;this._threadItems=[{id:oE(),format:this._format},{id:oE(),format:e}];let a=t?._rating??0,o=t?._showRating??!1;(n||r)&&this.updateComplete.then(()=>{let e=this.querySelectorAll(`jant-compose-editor`)[0];if(!e)return;n&&e.setEditorState(n.json,n.title,n.showTitle,n.selection),r&&(this._format===`link`&&r.url?e._url=r.url:this._format===`quote`&&(r.quoteText&&(e._quoteText=r.quoteText),r.quoteAuthor&&(e._quoteAuthor=r.quoteAuthor)),i&&(e._bodyJson=i));let s=t?._attachments??[],c=t?._attachmentOrder??[],l=t?._attachedTexts??[];s.length>0&&(e._attachments=[...s],e._attachmentOrder=[...c]),l.length>0&&(e._attachedTexts=[...l]),a>0&&(e._rating=a,e._showRating=o)})}else this._threadItems=[...this._threadItems,{id:oE(),format:e}];this._focusedThreadIndex=this._threadItems.length-1,this.updateComplete.then(()=>{this.querySelectorAll(`jant-compose-editor`)[this._focusedThreadIndex]?.focusInput()})}_removeThreadItem(e){if(this._threadItems.length<=1)return;let t=this._threadItems.filter((t,n)=>n!==e);if(t.length===1){let n=this.querySelectorAll(`jant-compose-editor`)[e===0?1:0]??null,r=n?.getEditorState()??null,i=n?.getData(),a=n?.getNormalizedBodyJson()??null,o=t[0].format,s=n?._rating??0,c=n?._showRating??!1;this._threadItems=[],this._focusedThreadIndex=0,this._format=o,this.updateComplete.then(()=>{let e=this._editor;if(!e)return;e.format=o,r&&e.setEditorState(r.json,r.title,r.showTitle,r.selection),i&&(o===`link`&&i.url?e._url=i.url:o===`quote`&&(i.quoteText&&(e._quoteText=i.quoteText),i.quoteAuthor&&(e._quoteAuthor=i.quoteAuthor)),a&&(e._bodyJson=a));let t=n?._attachments??[],l=n?._attachmentOrder??[],u=n?._attachedTexts??[];t.length>0&&(e._attachments=[...t],e._attachmentOrder=[...l]),u.length>0&&(e._attachedTexts=[...u]),s>0&&(e._rating=s,e._showRating=c),e.focusInput(),this.requestUpdate()})}else this._threadItems=t,this._focusedThreadIndex=Math.min(this._focusedThreadIndex,t.length-1)}_renderThreadPost(e,t,n){return u`
1264
1264
  <div
1265
1265
  class="compose-editor-row compose-thread-post"
1266
1266
  data-thread-index=${t}
@@ -1376,7 +1376,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1376
1376
  ${this._renderConfirmPanel()}
1377
1377
  </div>
1378
1378
  ${this._renderAddCollectionPanel()}
1379
- `}};customElements.define(`jant-compose-dialog`,_E);var vE=e=>e??m;function yE(e,t,n){return(t=EE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function bE(){return bE=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},bE.apply(null,arguments)}function xE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function SE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?xE(Object(n),!0).forEach(function(t){yE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function CE(e,t){if(e==null)return{};var n,r,i=wE(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function wE(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function TE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function EE(e){var t=TE(e,`string`);return typeof t==`symbol`?t:t+``}function DE(e){"@babel/helpers - typeof";return DE=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},DE(e)}var OE=`1.15.7`;function kE(e){if(typeof window<`u`&&window.navigator)return!!navigator.userAgent.match(e)}var AE=kE(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),jE=kE(/Edge/i),ME=kE(/firefox/i),NE=kE(/safari/i)&&!kE(/chrome/i)&&!kE(/android/i),PE=kE(/iP(ad|od|hone)/i),FE=kE(/chrome/i)&&kE(/android/i),IE={capture:!1,passive:!1};function L(e,t,n){e.addEventListener(t,n,!AE&&IE)}function R(e,t,n){e.removeEventListener(t,n,!AE&&IE)}function LE(e,t){if(t){if(t[0]===`>`&&(t=t.substring(1)),e)try{if(e.matches)return e.matches(t);if(e.msMatchesSelector)return e.msMatchesSelector(t);if(e.webkitMatchesSelector)return e.webkitMatchesSelector(t)}catch{return!1}return!1}}function RE(e){return e.host&&e!==document&&e.host.nodeType&&e.host!==e?e.host:e.parentNode}function zE(e,t,n,r){if(e){n||=document;do{if(t!=null&&(t[0]===`>`?e.parentNode===n&&LE(e,t):LE(e,t))||r&&e===n)return e;if(e===n)break}while(e=RE(e))}return null}var BE=/\s+/g;function VE(e,t,n){e&&t&&(e.classList?e.classList[n?`add`:`remove`](t):e.className=((` `+e.className+` `).replace(BE,` `).replace(` `+t+` `,` `)+(n?` `+t:``)).replace(BE,` `))}function z(e,t,n){var r=e&&e.style;if(r){if(n===void 0)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(e,``):e.currentStyle&&(n=e.currentStyle),t===void 0?n:n[t];!(t in r)&&t.indexOf(`webkit`)===-1&&(t=`-webkit-`+t),r[t]=n+(typeof n==`string`?``:`px`)}}function HE(e,t){var n=``;if(typeof e==`string`)n=e;else do{var r=z(e,`transform`);r&&r!==`none`&&(n=r+` `+n)}while(!t&&(e=e.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function UE(e,t,n){if(e){var r=e.getElementsByTagName(t),i=0,a=r.length;if(n)for(;i<a;i++)n(r[i],i);return r}return[]}function WE(){return document.scrollingElement||document.documentElement}function GE(e,t,n,r,i){if(!(!e.getBoundingClientRect&&e!==window)){var a,o,s,c,l,u,d;if(e!==window&&e.parentNode&&e!==WE()?(a=e.getBoundingClientRect(),o=a.top,s=a.left,c=a.bottom,l=a.right,u=a.height,d=a.width):(o=0,s=0,c=window.innerHeight,l=window.innerWidth,u=window.innerHeight,d=window.innerWidth),(t||n)&&e!==window&&(i||=e.parentNode,!AE))do if(i&&i.getBoundingClientRect&&(z(i,`transform`)!==`none`||n&&z(i,`position`)!==`static`)){var f=i.getBoundingClientRect();o-=f.top+parseInt(z(i,`border-top-width`)),s-=f.left+parseInt(z(i,`border-left-width`)),c=o+a.height,l=s+a.width;break}while(i=i.parentNode);if(r&&e!==window){var p=HE(i||e),m=p&&p.a,h=p&&p.d;p&&(o/=h,s/=m,d/=m,u/=h,c=o+u,l=s+d)}return{top:o,left:s,bottom:c,right:l,width:d,height:u}}}function KE(e,t,n){for(var r=QE(e,!0),i=GE(e)[t];r;){var a=GE(r)[n],o=void 0;if(o=n===`top`||n===`left`?i>=a:i<=a,!o)return r;if(r===WE())break;r=QE(r,!1)}return!1}function qE(e,t,n,r){for(var i=0,a=0,o=e.children;a<o.length;){if(o[a].style.display!==`none`&&o[a]!==H.ghost&&(r||o[a]!==H.dragged)&&zE(o[a],n.draggable,e,!1)){if(i===t)return o[a];i++}a++}return null}function JE(e,t){for(var n=e.lastElementChild;n&&(n===H.ghost||z(n,`display`)===`none`||t&&!LE(n,t));)n=n.previousElementSibling;return n||null}function YE(e,t){var n=0;if(!e||!e.parentNode)return-1;for(;e=e.previousElementSibling;)e.nodeName.toUpperCase()!==`TEMPLATE`&&e!==H.clone&&(!t||LE(e,t))&&n++;return n}function XE(e){var t=0,n=0,r=WE();if(e)do{var i=HE(e),a=i.a,o=i.d;t+=e.scrollLeft*a,n+=e.scrollTop*o}while(e!==r&&(e=e.parentNode));return[t,n]}function ZE(e,t){for(var n in e)if(e.hasOwnProperty(n)){for(var r in t)if(t.hasOwnProperty(r)&&t[r]===e[n][r])return Number(n)}return-1}function QE(e,t){if(!e||!e.getBoundingClientRect)return WE();var n=e,r=!1;do if(n.clientWidth<n.scrollWidth||n.clientHeight<n.scrollHeight){var i=z(n);if(n.clientWidth<n.scrollWidth&&(i.overflowX==`auto`||i.overflowX==`scroll`)||n.clientHeight<n.scrollHeight&&(i.overflowY==`auto`||i.overflowY==`scroll`)){if(!n.getBoundingClientRect||n===document.body)return WE();if(r||t)return n;r=!0}}while(n=n.parentNode);return WE()}function $E(e,t){if(e&&t)for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function eD(e,t){return Math.round(e.top)===Math.round(t.top)&&Math.round(e.left)===Math.round(t.left)&&Math.round(e.height)===Math.round(t.height)&&Math.round(e.width)===Math.round(t.width)}var tD;function nD(e,t){return function(){if(!tD){var n=arguments,r=this;n.length===1?e.call(r,n[0]):e.apply(r,n),tD=setTimeout(function(){tD=void 0},t)}}}function rD(){clearTimeout(tD),tD=void 0}function iD(e,t,n){e.scrollLeft+=t,e.scrollTop+=n}function aD(e){var t=window.Polymer,n=window.jQuery||window.Zepto;return t&&t.dom?t.dom(e).cloneNode(!0):n?n(e).clone(!0)[0]:e.cloneNode(!0)}function oD(e,t,n){var r={};return Array.from(e.children).forEach(function(i){if(!(!zE(i,t.draggable,e,!1)||i.animated||i===n)){var a=GE(i);r.left=Math.min(r.left??1/0,a.left),r.top=Math.min(r.top??1/0,a.top),r.right=Math.max(r.right??-1/0,a.right),r.bottom=Math.max(r.bottom??-1/0,a.bottom)}}),r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}var sD=`Sortable`+new Date().getTime();function cD(){var e=[],t;return{captureAnimationState:function(){e=[],this.options.animation&&[].slice.call(this.el.children).forEach(function(t){if(!(z(t,`display`)===`none`||t===H.ghost)){e.push({target:t,rect:GE(t)});var n=SE({},e[e.length-1].rect);if(t.thisAnimationDuration){var r=HE(t,!0);r&&(n.top-=r.f,n.left-=r.e)}t.fromRect=n}})},addAnimationState:function(t){e.push(t)},removeAnimationState:function(t){e.splice(ZE(e,{target:t}),1)},animateAll:function(n){var r=this;if(!this.options.animation){clearTimeout(t),typeof n==`function`&&n();return}var i=!1,a=0;e.forEach(function(e){var t=0,n=e.target,o=n.fromRect,s=GE(n),c=n.prevFromRect,l=n.prevToRect,u=e.rect,d=HE(n,!0);d&&(s.top-=d.f,s.left-=d.e),n.toRect=s,n.thisAnimationDuration&&eD(c,s)&&!eD(o,s)&&(u.top-s.top)/(u.left-s.left)===(o.top-s.top)/(o.left-s.left)&&(t=uD(u,c,l,r.options)),eD(s,o)||(n.prevFromRect=o,n.prevToRect=s,t||=r.options.animation,r.animate(n,u,s,t)),t&&(i=!0,a=Math.max(a,t),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout(function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null},t),n.thisAnimationDuration=t)}),clearTimeout(t),i?t=setTimeout(function(){typeof n==`function`&&n()},a):typeof n==`function`&&n(),e=[]},animate:function(e,t,n,r){if(r){z(e,`transition`,``),z(e,`transform`,``);var i=HE(this.el),a=i&&i.a,o=i&&i.d,s=(t.left-n.left)/(a||1),c=(t.top-n.top)/(o||1);e.animatingX=!!s,e.animatingY=!!c,z(e,`transform`,`translate3d(`+s+`px,`+c+`px,0)`),this.forRepaintDummy=lD(e),z(e,`transition`,`transform `+r+`ms`+(this.options.easing?` `+this.options.easing:``)),z(e,`transform`,`translate3d(0,0,0)`),typeof e.animated==`number`&&clearTimeout(e.animated),e.animated=setTimeout(function(){z(e,`transition`,``),z(e,`transform`,``),e.animated=!1,e.animatingX=!1,e.animatingY=!1},r)}}}}function lD(e){return e.offsetWidth}function uD(e,t,n,r){return Math.sqrt((t.top-e.top)**2+(t.left-e.left)**2)/Math.sqrt((t.top-n.top)**2+(t.left-n.left)**2)*r.animation}var dD=[],fD={initializeByDefault:!0},pD={mount:function(e){for(var t in fD)fD.hasOwnProperty(t)&&!(t in e)&&(e[t]=fD[t]);dD.forEach(function(t){if(t.pluginName===e.pluginName)throw`Sortable: Cannot mount plugin ${e.pluginName} more than once`}),dD.push(e)},pluginEvent:function(e,t,n){var r=this;this.eventCanceled=!1,n.cancel=function(){r.eventCanceled=!0};var i=e+`Global`;dD.forEach(function(r){t[r.pluginName]&&(t[r.pluginName][i]&&t[r.pluginName][i](SE({sortable:t},n)),t.options[r.pluginName]&&t[r.pluginName][e]&&t[r.pluginName][e](SE({sortable:t},n)))})},initializePlugins:function(e,t,n,r){for(var i in dD.forEach(function(r){var i=r.pluginName;if(!(!e.options[i]&&!r.initializeByDefault)){var a=new r(e,t,e.options);a.sortable=e,a.options=e.options,e[i]=a,bE(n,a.defaults)}}),e.options)if(e.options.hasOwnProperty(i)){var a=this.modifyOption(e,i,e.options[i]);a!==void 0&&(e.options[i]=a)}},getEventProperties:function(e,t){var n={};return dD.forEach(function(r){typeof r.eventProperties==`function`&&bE(n,r.eventProperties.call(t[r.pluginName],e))}),n},modifyOption:function(e,t,n){var r;return dD.forEach(function(i){e[i.pluginName]&&i.optionListeners&&typeof i.optionListeners[t]==`function`&&(r=i.optionListeners[t].call(e[i.pluginName],n))}),r}};function mD(e){var t=e.sortable,n=e.rootEl,r=e.name,i=e.targetEl,a=e.cloneEl,o=e.toEl,s=e.fromEl,c=e.oldIndex,l=e.newIndex,u=e.oldDraggableIndex,d=e.newDraggableIndex,f=e.originalEvent,p=e.putSortable,m=e.extraEventProperties;if(t||=n&&n[sD],t){var h,g=t.options,_=`on`+r.charAt(0).toUpperCase()+r.substr(1);window.CustomEvent&&!AE&&!jE?h=new CustomEvent(r,{bubbles:!0,cancelable:!0}):(h=document.createEvent(`Event`),h.initEvent(r,!0,!0)),h.to=o||n,h.from=s||n,h.item=i||n,h.clone=a,h.oldIndex=c,h.newIndex=l,h.oldDraggableIndex=u,h.newDraggableIndex=d,h.originalEvent=f,h.pullMode=p?p.lastPutMode:void 0;var v=SE(SE({},m),pD.getEventProperties(r,t));for(var y in v)h[y]=v[y];n&&n.dispatchEvent(h),g[_]&&g[_].call(t,h)}}var hD=[`evt`],gD=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.evt,i=CE(n,hD);pD.pluginEvent.bind(H)(e,t,SE({dragEl:B,parentEl:vD,ghostEl:V,rootEl:yD,nextEl:bD,lastDownEl:xD,cloneEl:SD,cloneHidden:CD,dragStarted:zD,putSortable:kD,activeSortable:H.active,originalEvent:r,oldIndex:wD,oldDraggableIndex:ED,newIndex:TD,newDraggableIndex:DD,hideGhostForTarget:iO,unhideGhostForTarget:aO,cloneNowHidden:function(){CD=!0},cloneNowShown:function(){CD=!1},dispatchSortableEvent:function(e){_D({sortable:t,name:e,originalEvent:r})}},i))};function _D(e){mD(SE({putSortable:kD,cloneEl:SD,targetEl:B,rootEl:yD,oldIndex:wD,oldDraggableIndex:ED,newIndex:TD,newDraggableIndex:DD},e))}var B,vD,V,yD,bD,xD,SD,CD,wD,TD,ED,DD,OD,kD,AD=!1,jD=!1,MD=[],ND,PD,FD,ID,LD,RD,zD,BD,VD,HD=!1,UD=!1,WD,GD,KD=[],qD=!1,JD=[],YD=typeof document<`u`,XD=PE,ZD=jE||AE?`cssFloat`:`float`,QD=YD&&!FE&&!PE&&`draggable`in document.createElement(`div`),$D=function(){if(YD){if(AE)return!1;var e=document.createElement(`x`);return e.style.cssText=`pointer-events:auto`,e.style.pointerEvents===`auto`}}(),eO=function(e,t){var n=z(e),r=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=qE(e,0,t),a=qE(e,1,t),o=i&&z(i),s=a&&z(a),c=o&&parseInt(o.marginLeft)+parseInt(o.marginRight)+GE(i).width,l=s&&parseInt(s.marginLeft)+parseInt(s.marginRight)+GE(a).width;if(n.display===`flex`)return n.flexDirection===`column`||n.flexDirection===`column-reverse`?`vertical`:`horizontal`;if(n.display===`grid`)return n.gridTemplateColumns.split(` `).length<=1?`vertical`:`horizontal`;if(i&&o.float&&o.float!==`none`){var u=o.float===`left`?`left`:`right`;return a&&(s.clear===`both`||s.clear===u)?`vertical`:`horizontal`}return i&&(o.display===`block`||o.display===`flex`||o.display===`table`||o.display===`grid`||c>=r&&n[ZD]===`none`||a&&n[ZD]===`none`&&c+l>r)?`vertical`:`horizontal`},tO=function(e,t,n){var r=n?e.left:e.top,i=n?e.right:e.bottom,a=n?e.width:e.height,o=n?t.left:t.top,s=n?t.right:t.bottom,c=n?t.width:t.height;return r===o||i===s||r+a/2===o+c/2},nO=function(e,t){var n;return MD.some(function(r){var i=r[sD].options.emptyInsertThreshold;if(!(!i||JE(r))){var a=GE(r),o=e>=a.left-i&&e<=a.right+i,s=t>=a.top-i&&t<=a.bottom+i;if(o&&s)return n=r}}),n},rO=function(e){function t(e,n){return function(r,i,a,o){var s=r.options.group.name&&i.options.group.name&&r.options.group.name===i.options.group.name;if(e==null&&(n||s))return!0;if(e==null||e===!1)return!1;if(n&&e===`clone`)return e;if(typeof e==`function`)return t(e(r,i,a,o),n)(r,i,a,o);var c=(n?r:i).options.group.name;return e===!0||typeof e==`string`&&e===c||e.join&&e.indexOf(c)>-1}}var n={},r=e.group;(!r||DE(r)!=`object`)&&(r={name:r}),n.name=r.name,n.checkPull=t(r.pull,!0),n.checkPut=t(r.put),n.revertClone=r.revertClone,e.group=n},iO=function(){!$D&&V&&z(V,`display`,`none`)},aO=function(){!$D&&V&&z(V,`display`,``)};YD&&!FE&&document.addEventListener(`click`,function(e){if(jD)return e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),jD=!1,!1},!0);var oO=function(e){if(B){e=e.touches?e.touches[0]:e;var t=nO(e.clientX,e.clientY);if(t){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);n.target=n.rootEl=t,n.preventDefault=void 0,n.stopPropagation=void 0,t[sD]._onDragOver(n)}}},sO=function(e){B&&B.parentNode[sD]._isOutsideThisEl(e.target)};function H(e,t){if(!(e&&e.nodeType&&e.nodeType===1))throw`Sortable: \`el\` must be an HTMLElement, not ${{}.toString.call(e)}`;this.el=e,this.options=t=bE({},t),e[sD]=this;var n={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(e.nodeName)?`>li`:`>*`,swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return eO(e,this.options)},ghostClass:`sortable-ghost`,chosenClass:`sortable-chosen`,dragClass:`sortable-drag`,ignore:`a, img`,filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(e,t){e.setData(`Text`,t.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:`data-id`,delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:`sortable-fallback`,fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:H.supportPointer!==!1&&`PointerEvent`in window&&(!NE||PE),emptyInsertThreshold:5};for(var r in pD.initializePlugins(this,e,n),n)!(r in t)&&(t[r]=n[r]);for(var i in rO(t),this)i.charAt(0)===`_`&&typeof this[i]==`function`&&(this[i]=this[i].bind(this));this.nativeDraggable=t.forceFallback?!1:QD,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?L(e,`pointerdown`,this._onTapStart):(L(e,`mousedown`,this._onTapStart),L(e,`touchstart`,this._onTapStart)),this.nativeDraggable&&(L(e,`dragover`,this),L(e,`dragenter`,this)),MD.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),bE(this,cD())}H.prototype={constructor:H,_isOutsideThisEl:function(e){!this.el.contains(e)&&e!==this.el&&(BD=null)},_getDirection:function(e,t){return typeof this.options.direction==`function`?this.options.direction.call(this,e,t,B):this.options.direction},_onTapStart:function(e){if(e.cancelable){var t=this,n=this.el,r=this.options,i=r.preventOnFilter,a=e.type,o=e.touches&&e.touches[0]||e.pointerType&&e.pointerType===`touch`&&e,s=(o||e).target,c=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||s,l=r.filter;if(_O(n),!B&&!(/mousedown|pointerdown/.test(a)&&e.button!==0||r.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&NE&&s&&s.tagName.toUpperCase()===`SELECT`)&&(s=zE(s,r.draggable,n,!1),!(s&&s.animated)&&xD!==s)){if(wD=YE(s),ED=YE(s,r.draggable),typeof l==`function`){if(l.call(this,e,s,this)){_D({sortable:t,rootEl:c,name:`filter`,targetEl:s,toEl:n,fromEl:n}),gD(`filter`,t,{evt:e}),i&&e.preventDefault();return}}else if(l&&(l=l.split(`,`).some(function(r){if(r=zE(c,r.trim(),n,!1),r)return _D({sortable:t,rootEl:r,name:`filter`,targetEl:s,fromEl:n,toEl:n}),gD(`filter`,t,{evt:e}),!0}),l)){i&&e.preventDefault();return}r.handle&&!zE(c,r.handle,n,!1)||this._prepareDragStart(e,o,s)}}},_prepareDragStart:function(e,t,n){var r=this,i=r.el,a=r.options,o=i.ownerDocument,s;if(n&&!B&&n.parentNode===i){var c=GE(n);if(yD=i,B=n,vD=B.parentNode,bD=B.nextSibling,xD=n,OD=a.group,H.dragged=B,ND={target:B,clientX:(t||e).clientX,clientY:(t||e).clientY},LD=ND.clientX-c.left,RD=ND.clientY-c.top,this._lastX=(t||e).clientX,this._lastY=(t||e).clientY,B.style[`will-change`]=`all`,s=function(){if(gD(`delayEnded`,r,{evt:e}),H.eventCanceled){r._onDrop();return}r._disableDelayedDragEvents(),!ME&&r.nativeDraggable&&(B.draggable=!0),r._triggerDragStart(e,t),_D({sortable:r,name:`choose`,originalEvent:e}),VE(B,a.chosenClass,!0)},a.ignore.split(`,`).forEach(function(e){UE(B,e.trim(),uO)}),L(o,`dragover`,oO),L(o,`mousemove`,oO),L(o,`touchmove`,oO),a.supportPointer?(L(o,`pointerup`,r._onDrop),!this.nativeDraggable&&L(o,`pointercancel`,r._onDrop)):(L(o,`mouseup`,r._onDrop),L(o,`touchend`,r._onDrop),L(o,`touchcancel`,r._onDrop)),ME&&this.nativeDraggable&&(this.options.touchStartThreshold=4,B.draggable=!0),gD(`delayStart`,this,{evt:e}),a.delay&&(!a.delayOnTouchOnly||t)&&(!this.nativeDraggable||!(jE||AE))){if(H.eventCanceled){this._onDrop();return}a.supportPointer?(L(o,`pointerup`,r._disableDelayedDrag),L(o,`pointercancel`,r._disableDelayedDrag)):(L(o,`mouseup`,r._disableDelayedDrag),L(o,`touchend`,r._disableDelayedDrag),L(o,`touchcancel`,r._disableDelayedDrag)),L(o,`mousemove`,r._delayedDragTouchMoveHandler),L(o,`touchmove`,r._delayedDragTouchMoveHandler),a.supportPointer&&L(o,`pointermove`,r._delayedDragTouchMoveHandler),r._dragStartTimer=setTimeout(s,a.delay)}else s()}},_delayedDragTouchMoveHandler:function(e){var t=e.touches?e.touches[0]:e;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){B&&uO(B),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;R(e,`mouseup`,this._disableDelayedDrag),R(e,`touchend`,this._disableDelayedDrag),R(e,`touchcancel`,this._disableDelayedDrag),R(e,`pointerup`,this._disableDelayedDrag),R(e,`pointercancel`,this._disableDelayedDrag),R(e,`mousemove`,this._delayedDragTouchMoveHandler),R(e,`touchmove`,this._delayedDragTouchMoveHandler),R(e,`pointermove`,this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,t){t||=e.pointerType==`touch`&&e,!this.nativeDraggable||t?this.options.supportPointer?L(document,`pointermove`,this._onTouchMove):t?L(document,`touchmove`,this._onTouchMove):L(document,`mousemove`,this._onTouchMove):(L(B,`dragend`,this),L(yD,`dragstart`,this._onDragStart));try{document.selection?vO(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(e,t){if(AD=!1,yD&&B){gD(`dragStarted`,this,{evt:t}),this.nativeDraggable&&L(document,`dragover`,sO);var n=this.options;!e&&VE(B,n.dragClass,!1),VE(B,n.ghostClass,!0),H.active=this,e&&this._appendGhost(),_D({sortable:this,name:`start`,originalEvent:t})}else this._nulling()},_emulateDragOver:function(){if(PD){this._lastX=PD.clientX,this._lastY=PD.clientY,iO();for(var e=document.elementFromPoint(PD.clientX,PD.clientY),t=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(PD.clientX,PD.clientY),e!==t);)t=e;if(B.parentNode[sD]._isOutsideThisEl(e),t)do{if(t[sD]){var n=void 0;if(n=t[sD]._onDragOver({clientX:PD.clientX,clientY:PD.clientY,target:e,rootEl:t}),n&&!this.options.dragoverBubble)break}e=t}while(t=RE(t));aO()}},_onTouchMove:function(e){if(ND){var t=this.options,n=t.fallbackTolerance,r=t.fallbackOffset,i=e.touches?e.touches[0]:e,a=V&&HE(V,!0),o=V&&a&&a.a,s=V&&a&&a.d,c=XD&&GD&&XE(GD),l=(i.clientX-ND.clientX+r.x)/(o||1)+(c?c[0]-KD[0]:0)/(o||1),u=(i.clientY-ND.clientY+r.y)/(s||1)+(c?c[1]-KD[1]:0)/(s||1);if(!H.active&&!AD){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<n)return;this._onDragStart(e,!0)}if(V){a?(a.e+=l-(FD||0),a.f+=u-(ID||0)):a={a:1,b:0,c:0,d:1,e:l,f:u};var d=`matrix(${a.a},${a.b},${a.c},${a.d},${a.e},${a.f})`;z(V,`webkitTransform`,d),z(V,`mozTransform`,d),z(V,`msTransform`,d),z(V,`transform`,d),FD=l,ID=u,PD=i}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!V){var e=this.options.fallbackOnBody?document.body:yD,t=GE(B,!0,XD,!0,e),n=this.options;if(XD){for(GD=e;z(GD,`position`)===`static`&&z(GD,`transform`)===`none`&&GD!==document;)GD=GD.parentNode;GD!==document.body&&GD!==document.documentElement?(GD===document&&(GD=WE()),t.top+=GD.scrollTop,t.left+=GD.scrollLeft):GD=WE(),KD=XE(GD)}V=B.cloneNode(!0),VE(V,n.ghostClass,!1),VE(V,n.fallbackClass,!0),VE(V,n.dragClass,!0),z(V,`transition`,``),z(V,`transform`,``),z(V,`box-sizing`,`border-box`),z(V,`margin`,0),z(V,`top`,t.top),z(V,`left`,t.left),z(V,`width`,t.width),z(V,`height`,t.height),z(V,`opacity`,`0.8`),z(V,`position`,XD?`absolute`:`fixed`),z(V,`zIndex`,`100000`),z(V,`pointerEvents`,`none`),H.ghost=V,e.appendChild(V),z(V,`transform-origin`,LD/parseInt(V.style.width)*100+`% `+RD/parseInt(V.style.height)*100+`%`)}},_onDragStart:function(e,t){var n=this,r=e.dataTransfer,i=n.options;if(gD(`dragStart`,this,{evt:e}),H.eventCanceled){this._onDrop();return}gD(`setupClone`,this),H.eventCanceled||(SD=aD(B),SD.removeAttribute(`id`),SD.draggable=!1,SD.style[`will-change`]=``,this._hideClone(),VE(SD,this.options.chosenClass,!1),H.clone=SD),n.cloneId=vO(function(){gD(`clone`,n),!H.eventCanceled&&(n.options.removeCloneOnHide||yD.insertBefore(SD,B),n._hideClone(),_D({sortable:n,name:`clone`}))}),!t&&VE(B,i.dragClass,!0),t?(jD=!0,n._loopId=setInterval(n._emulateDragOver,50)):(R(document,`mouseup`,n._onDrop),R(document,`touchend`,n._onDrop),R(document,`touchcancel`,n._onDrop),r&&(r.effectAllowed=`move`,i.setData&&i.setData.call(n,r,B)),L(document,`drop`,n),z(B,`transform`,`translateZ(0)`)),AD=!0,n._dragStartId=vO(n._dragStarted.bind(n,t,e)),L(document,`selectstart`,n),zD=!0,window.getSelection().removeAllRanges(),NE&&z(document.body,`user-select`,`none`)},_onDragOver:function(e){var t=this.el,n=e.target,r,i,a,o=this.options,s=o.group,c=H.active,l=OD===s,u=o.sort,d=kD||c,f,p=this,m=!1;if(qD)return;function h(o,s){gD(o,p,SE({evt:e,isOwner:l,axis:f?`vertical`:`horizontal`,revert:a,dragRect:r,targetRect:i,canSort:u,fromSortable:d,target:n,completed:_,onMove:function(n,i){return lO(yD,t,B,r,n,GE(n),e,i)},changed:v},s))}function g(){h(`dragOverAnimationCapture`),p.captureAnimationState(),p!==d&&d.captureAnimationState()}function _(r){return h(`dragOverCompleted`,{insertion:r}),r&&(l?c._hideClone():c._showClone(p),p!==d&&(VE(B,kD?kD.options.ghostClass:c.options.ghostClass,!1),VE(B,o.ghostClass,!0)),kD!==p&&p!==H.active?kD=p:p===H.active&&kD&&(kD=null),d===p&&(p._ignoreWhileAnimating=n),p.animateAll(function(){h(`dragOverAnimationComplete`),p._ignoreWhileAnimating=null}),p!==d&&(d.animateAll(),d._ignoreWhileAnimating=null)),(n===B&&!B.animated||n===t&&!n.animated)&&(BD=null),!o.dragoverBubble&&!e.rootEl&&n!==document&&(B.parentNode[sD]._isOutsideThisEl(e.target),!r&&oO(e)),!o.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),m=!0}function v(){TD=YE(B),DD=YE(B,o.draggable),_D({sortable:p,name:`change`,toEl:t,newIndex:TD,newDraggableIndex:DD,originalEvent:e})}if(e.preventDefault!==void 0&&e.cancelable&&e.preventDefault(),n=zE(n,o.draggable,t,!0),h(`dragOver`),H.eventCanceled)return m;if(B.contains(e.target)||n.animated&&n.animatingX&&n.animatingY||p._ignoreWhileAnimating===n)return _(!1);if(jD=!1,c&&!o.disabled&&(l?u||(a=vD!==yD):kD===this||(this.lastPutMode=OD.checkPull(this,c,B,e))&&s.checkPut(this,c,B,e))){if(f=this._getDirection(e,n)===`vertical`,r=GE(B),h(`dragOverValid`),H.eventCanceled)return m;if(a)return vD=yD,g(),this._hideClone(),h(`revert`),H.eventCanceled||(bD?yD.insertBefore(B,bD):yD.appendChild(B)),_(!0);var y=JE(t,o.draggable);if(!y||pO(e,f,this)&&!y.animated){if(y===B)return _(!1);if(y&&t===e.target&&(n=y),n&&(i=GE(n)),lO(yD,t,B,r,n,i,e,!!n)!==!1)return g(),y&&y.nextSibling?t.insertBefore(B,y.nextSibling):t.appendChild(B),vD=t,v(),_(!0)}else if(y&&fO(e,f,this)){var b=qE(t,0,o,!0);if(b===B)return _(!1);if(n=b,i=GE(n),lO(yD,t,B,r,n,i,e,!1)!==!1)return g(),t.insertBefore(B,b),vD=t,v(),_(!0)}else if(n.parentNode===t){i=GE(n);var x=0,S,C=B.parentNode!==t,ee=!tO(B.animated&&B.toRect||r,n.animated&&n.toRect||i,f),te=f?`top`:`left`,ne=KE(n,`top`,`top`)||KE(B,`top`,`top`),re=ne?ne.scrollTop:void 0;BD!==n&&(S=i[te],HD=!1,UD=!ee&&o.invertSwap||C),x=mO(e,n,i,f,ee?1:o.swapThreshold,o.invertedSwapThreshold==null?o.swapThreshold:o.invertedSwapThreshold,UD,BD===n);var ie;if(x!==0){var ae=YE(B);do ae-=x,ie=vD.children[ae];while(ie&&(z(ie,`display`)===`none`||ie===V))}if(x===0||ie===n)return _(!1);BD=n,VD=x;var oe=n.nextElementSibling,se=!1;se=x===1;var ce=lO(yD,t,B,r,n,i,e,se);if(ce!==!1)return(ce===1||ce===-1)&&(se=ce===1),qD=!0,setTimeout(dO,30),g(),se&&!oe?t.appendChild(B):n.parentNode.insertBefore(B,se?oe:n),ne&&iD(ne,0,re-ne.scrollTop),vD=B.parentNode,S!==void 0&&!UD&&(WD=Math.abs(S-GE(n)[te])),v(),_(!0)}if(t.contains(B))return _(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){R(document,`mousemove`,this._onTouchMove),R(document,`touchmove`,this._onTouchMove),R(document,`pointermove`,this._onTouchMove),R(document,`dragover`,oO),R(document,`mousemove`,oO),R(document,`touchmove`,oO)},_offUpEvents:function(){var e=this.el.ownerDocument;R(e,`mouseup`,this._onDrop),R(e,`touchend`,this._onDrop),R(e,`pointerup`,this._onDrop),R(e,`pointercancel`,this._onDrop),R(e,`touchcancel`,this._onDrop),R(document,`selectstart`,this)},_onDrop:function(e){var t=this.el,n=this.options;if(TD=YE(B),DD=YE(B,n.draggable),gD(`drop`,this,{evt:e}),vD=B&&B.parentNode,TD=YE(B),DD=YE(B,n.draggable),H.eventCanceled){this._nulling();return}AD=!1,UD=!1,HD=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),yO(this.cloneId),yO(this._dragStartId),this.nativeDraggable&&(R(document,`drop`,this),R(t,`dragstart`,this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),NE&&z(document.body,`user-select`,``),z(B,`transform`,``),e&&(zD&&(e.cancelable&&e.preventDefault(),!n.dropBubble&&e.stopPropagation()),V&&V.parentNode&&V.parentNode.removeChild(V),(yD===vD||kD&&kD.lastPutMode!==`clone`)&&SD&&SD.parentNode&&SD.parentNode.removeChild(SD),B&&(this.nativeDraggable&&R(B,`dragend`,this),uO(B),B.style[`will-change`]=``,zD&&!AD&&VE(B,kD?kD.options.ghostClass:this.options.ghostClass,!1),VE(B,this.options.chosenClass,!1),_D({sortable:this,name:`unchoose`,toEl:vD,newIndex:null,newDraggableIndex:null,originalEvent:e}),yD===vD?TD!==wD&&TD>=0&&(_D({sortable:this,name:`update`,toEl:vD,originalEvent:e}),_D({sortable:this,name:`sort`,toEl:vD,originalEvent:e})):(TD>=0&&(_D({rootEl:vD,name:`add`,toEl:vD,fromEl:yD,originalEvent:e}),_D({sortable:this,name:`remove`,toEl:vD,originalEvent:e}),_D({rootEl:vD,name:`sort`,toEl:vD,fromEl:yD,originalEvent:e}),_D({sortable:this,name:`sort`,toEl:vD,originalEvent:e})),kD&&kD.save()),H.active&&((TD==null||TD===-1)&&(TD=wD,DD=ED),_D({sortable:this,name:`end`,toEl:vD,originalEvent:e}),this.save()))),this._nulling()},_nulling:function(){gD(`nulling`,this),yD=B=vD=V=bD=SD=xD=CD=ND=PD=zD=TD=DD=wD=ED=BD=VD=kD=OD=H.dragged=H.ghost=H.clone=H.active=null;var e=this.el;JD.forEach(function(t){e.contains(t)&&(t.checked=!0)}),JD.length=FD=ID=0},handleEvent:function(e){switch(e.type){case`drop`:case`dragend`:this._onDrop(e);break;case`dragenter`:case`dragover`:B&&(this._onDragOver(e),cO(e));break;case`selectstart`:e.preventDefault();break}},toArray:function(){for(var e=[],t,n=this.el.children,r=0,i=n.length,a=this.options;r<i;r++)t=n[r],zE(t,a.draggable,this.el,!1)&&e.push(t.getAttribute(a.dataIdAttr)||gO(t));return e},sort:function(e,t){var n={},r=this.el;this.toArray().forEach(function(e,t){var i=r.children[t];zE(i,this.options.draggable,r,!1)&&(n[e]=i)},this),t&&this.captureAnimationState(),e.forEach(function(e){n[e]&&(r.removeChild(n[e]),r.appendChild(n[e]))}),t&&this.animateAll()},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,t){return zE(e,t||this.options.draggable,this.el,!1)},option:function(e,t){var n=this.options;if(t===void 0)return n[e];var r=pD.modifyOption(this,e,t);r===void 0?n[e]=t:n[e]=r,e===`group`&&rO(n)},destroy:function(){gD(`destroy`,this);var e=this.el;e[sD]=null,R(e,`mousedown`,this._onTapStart),R(e,`touchstart`,this._onTapStart),R(e,`pointerdown`,this._onTapStart),this.nativeDraggable&&(R(e,`dragover`,this),R(e,`dragenter`,this)),Array.prototype.forEach.call(e.querySelectorAll(`[draggable]`),function(e){e.removeAttribute(`draggable`)}),this._onDrop(),this._disableDelayedDragEvents(),MD.splice(MD.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!CD){if(gD(`hideClone`,this),H.eventCanceled)return;z(SD,`display`,`none`),this.options.removeCloneOnHide&&SD.parentNode&&SD.parentNode.removeChild(SD),CD=!0}},_showClone:function(e){if(e.lastPutMode!==`clone`){this._hideClone();return}if(CD){if(gD(`showClone`,this),H.eventCanceled)return;B.parentNode==yD&&!this.options.group.revertClone?yD.insertBefore(SD,B):bD?yD.insertBefore(SD,bD):yD.appendChild(SD),this.options.group.revertClone&&this.animate(B,SD),z(SD,`display`,``),CD=!1}}};function cO(e){e.dataTransfer&&(e.dataTransfer.dropEffect=`move`),e.cancelable&&e.preventDefault()}function lO(e,t,n,r,i,a,o,s){var c,l=e[sD],u=l.options.onMove,d;return window.CustomEvent&&!AE&&!jE?c=new CustomEvent(`move`,{bubbles:!0,cancelable:!0}):(c=document.createEvent(`Event`),c.initEvent(`move`,!0,!0)),c.to=t,c.from=e,c.dragged=n,c.draggedRect=r,c.related=i||t,c.relatedRect=a||GE(t),c.willInsertAfter=s,c.originalEvent=o,e.dispatchEvent(c),u&&(d=u.call(l,c,o)),d}function uO(e){e.draggable=!1}function dO(){qD=!1}function fO(e,t,n){var r=GE(qE(n.el,0,n.options,!0)),i=oD(n.el,n.options,V),a=10;return t?e.clientX<i.left-a||e.clientY<r.top&&e.clientX<r.right:e.clientY<i.top-a||e.clientY<r.bottom&&e.clientX<r.left}function pO(e,t,n){var r=GE(JE(n.el,n.options.draggable)),i=oD(n.el,n.options,V),a=10;return t?e.clientX>i.right+a||e.clientY>r.bottom&&e.clientX>r.left:e.clientY>i.bottom+a||e.clientX>r.right&&e.clientY>r.top}function mO(e,t,n,r,i,a,o,s){var c=r?e.clientY:e.clientX,l=r?n.height:n.width,u=r?n.top:n.left,d=r?n.bottom:n.right,f=!1;if(!o){if(s&&WD<l*i){if(!HD&&(VD===1?c>u+l*a/2:c<d-l*a/2)&&(HD=!0),HD)f=!0;else if(VD===1?c<u+WD:c>d-WD)return-VD}else if(c>u+l*(1-i)/2&&c<d-l*(1-i)/2)return hO(t)}return f||=o,f&&(c<u+l*a/2||c>d-l*a/2)?c>u+l/2?1:-1:0}function hO(e){return YE(B)<YE(e)?1:-1}function gO(e){for(var t=e.tagName+e.className+e.src+e.href+e.textContent,n=t.length,r=0;n--;)r+=t.charCodeAt(n);return r.toString(36)}function _O(e){JD.length=0;for(var t=e.getElementsByTagName(`input`),n=t.length;n--;){var r=t[n];r.checked&&JD.push(r)}}function vO(e){return setTimeout(e,0)}function yO(e){return clearTimeout(e)}YD&&L(document,`touchmove`,function(e){(H.active||AD)&&e.cancelable&&e.preventDefault()}),H.utils={on:L,off:R,css:z,find:UE,is:function(e,t){return!!zE(e,t,e,!1)},extend:$E,throttle:nD,closest:zE,toggleClass:VE,clone:aD,index:YE,nextTick:vO,cancelNextTick:yO,detectDirection:eO,getChild:qE,expando:sD},H.get=function(e){return e[sD]},H.mount=function(){var e=[...arguments];e[0].constructor===Array&&(e=e[0]),e.forEach(function(e){if(!e.prototype||!e.prototype.constructor)throw`Sortable: Mounted plugin must be a constructor function, not ${{}.toString.call(e)}`;e.utils&&(H.utils=SE(SE({},H.utils),e.utils)),pD.mount(e)})},H.create=function(e,t){return new H(e,t)},H.version=OE;var bO=[],xO,SO,CO=!1,wO,TO,EO,DO;function OO(){function e(){for(var e in this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)e.charAt(0)===`_`&&typeof this[e]==`function`&&(this[e]=this[e].bind(this))}return e.prototype={dragStarted:function(e){var t=e.originalEvent;this.sortable.nativeDraggable?L(document,`dragover`,this._handleAutoScroll):this.options.supportPointer?L(document,`pointermove`,this._handleFallbackAutoScroll):t.touches?L(document,`touchmove`,this._handleFallbackAutoScroll):L(document,`mousemove`,this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var t=e.originalEvent;!this.options.dragOverBubble&&!t.rootEl&&this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?R(document,`dragover`,this._handleAutoScroll):(R(document,`pointermove`,this._handleFallbackAutoScroll),R(document,`touchmove`,this._handleFallbackAutoScroll),R(document,`mousemove`,this._handleFallbackAutoScroll)),AO(),kO(),rD()},nulling:function(){EO=SO=xO=CO=DO=wO=TO=null,bO.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,t){var n=this,r=(e.touches?e.touches[0]:e).clientX,i=(e.touches?e.touches[0]:e).clientY,a=document.elementFromPoint(r,i);if(EO=e,t||this.options.forceAutoScrollFallback||jE||AE||NE){jO(e,this.options,a,t);var o=QE(a,!0);CO&&(!DO||r!==wO||i!==TO)&&(DO&&AO(),DO=setInterval(function(){var a=QE(document.elementFromPoint(r,i),!0);a!==o&&(o=a,kO()),jO(e,n.options,a,t)},10),wO=r,TO=i)}else{if(!this.options.bubbleScroll||QE(a,!0)===WE()){kO();return}jO(e,this.options,QE(a,!1),!1)}}},bE(e,{pluginName:`scroll`,initializeByDefault:!0})}function kO(){bO.forEach(function(e){clearInterval(e.pid)}),bO=[]}function AO(){clearInterval(DO)}var jO=nD(function(e,t,n,r){if(t.scroll){var i=(e.touches?e.touches[0]:e).clientX,a=(e.touches?e.touches[0]:e).clientY,o=t.scrollSensitivity,s=t.scrollSpeed,c=WE(),l=!1,u;SO!==n&&(SO=n,kO(),xO=t.scroll,u=t.scrollFn,xO===!0&&(xO=QE(n,!0)));var d=0,f=xO;do{var p=f,m=GE(p),h=m.top,g=m.bottom,_=m.left,v=m.right,y=m.width,b=m.height,x=void 0,S=void 0,C=p.scrollWidth,ee=p.scrollHeight,te=z(p),ne=p.scrollLeft,re=p.scrollTop;p===c?(x=y<C&&(te.overflowX===`auto`||te.overflowX===`scroll`||te.overflowX===`visible`),S=b<ee&&(te.overflowY===`auto`||te.overflowY===`scroll`||te.overflowY===`visible`)):(x=y<C&&(te.overflowX===`auto`||te.overflowX===`scroll`),S=b<ee&&(te.overflowY===`auto`||te.overflowY===`scroll`));var ie=x&&(Math.abs(v-i)<=o&&ne+y<C)-(Math.abs(_-i)<=o&&!!ne),ae=S&&(Math.abs(g-a)<=o&&re+b<ee)-(Math.abs(h-a)<=o&&!!re);if(!bO[d])for(var oe=0;oe<=d;oe++)bO[oe]||(bO[oe]={});(bO[d].vx!=ie||bO[d].vy!=ae||bO[d].el!==p)&&(bO[d].el=p,bO[d].vx=ie,bO[d].vy=ae,clearInterval(bO[d].pid),(ie!=0||ae!=0)&&(l=!0,bO[d].pid=setInterval(function(){r&&this.layer===0&&H.active._onTouchMove(EO);var t=bO[this.layer].vy?bO[this.layer].vy*s:0,n=bO[this.layer].vx?bO[this.layer].vx*s:0;typeof u==`function`&&u.call(H.dragged.parentNode[sD],n,t,e,EO,bO[this.layer].el)!==`continue`||iD(bO[this.layer].el,n,t)}.bind({layer:d}),24))),d++}while(t.bubbleScroll&&f!==c&&(f=QE(f,!1)));CO=l}},30),MO=function(e){var t=e.originalEvent,n=e.putSortable,r=e.dragEl,i=e.activeSortable,a=e.dispatchSortableEvent,o=e.hideGhostForTarget,s=e.unhideGhostForTarget;if(t){var c=n||i;o();var l=t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:t,u=document.elementFromPoint(l.clientX,l.clientY);s(),c&&!c.el.contains(u)&&(a(`spill`),this.onSpill({dragEl:r,putSortable:n}))}};function NO(){}NO.prototype={startIndex:null,dragStart:function(e){this.startIndex=e.oldDraggableIndex},onSpill:function(e){var t=e.dragEl,n=e.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();var r=qE(this.sortable.el,this.startIndex,this.options);r?this.sortable.el.insertBefore(t,r):this.sortable.el.appendChild(t),this.sortable.animateAll(),n&&n.animateAll()},drop:MO},bE(NO,{pluginName:`revertOnSpill`});function PO(){}PO.prototype={onSpill:function(e){var t=e.dragEl,n=e.putSortable||this.sortable;n.captureAnimationState(),t.parentNode&&t.parentNode.removeChild(t),n.animateAll()},drop:MO},bE(PO,{pluginName:`removeOnSpill`}),H.mount(new OO),H.mount(PO,NO);var FO={animation:180,bubbleScroll:!1,delay:150,delayOnTouchOnly:!0,fallbackTolerance:4,forceAutoScrollFallback:!0,scrollSensitivity:56,scrollSpeed:18};function IO(e,t,n){return[...e.querySelectorAll(t)].map(e=>e.dataset[n]).filter(e=>e!==void 0)}function LO(e){return e.item.nextSibling}function RO(e,t,n=null){let{item:r,oldIndex:i,newIndex:a}=t;if(i==null||a==null||i===a)return;if(r.parentNode?.removeChild(r),n){e.insertBefore(r,n);return}let o=e.children;i>=o.length?e.appendChild(r):e.insertBefore(r,o[i]??null)}function zO(e,t){if(t){e.dataset.dragging=`true`;return}delete e.dataset.dragging}function BO(e,t){let n=t==null?void 0:e[t];if(!n)return{movedId:void 0,movedIndex:-1,afterId:null,beforeId:null};let r=e.indexOf(n);return{movedId:n,movedIndex:r,afterId:r>0?e[r-1]:null,beforeId:r>=0&&r<e.length-1?e[r+1]:null}}var VO=`0 0 96 96`,HO=[`M24.4 10.5C16.9 17.7 11.5 26.8 8.2 37.7C4.9 48.7 4.8 58.9 7.8 68.2C10.3 75.7 15.4 79.5 22.9 79.5C28 79.5 32.2 77.8 35.4 74.2C38.6 70.7 40.2 66.5 40.2 61.4C40.2 56.5 38.8 52.6 36 49.6C33.3 46.6 29.7 45.1 25.2 45.1C23.4 45.1 21.8 45.3 20.2 45.8C22.2 37.3 26.7 29.2 33.6 21.4L24.4 10.5Z`,`M60.8 10.5C53.3 17.7 47.9 26.8 44.6 37.7C41.3 48.7 41.2 58.9 44.2 68.2C46.7 75.7 51.8 79.5 59.3 79.5C64.4 79.5 68.6 77.8 71.8 74.2C75 70.7 76.6 66.5 76.6 61.4C76.6 56.5 75.2 52.6 72.4 49.6C69.7 46.6 66.1 45.1 61.6 45.1C59.8 45.1 58.2 45.3 56.6 45.8C58.6 37.3 63.1 29.2 70 21.4L60.8 10.5Z`].map(e=>`<path fill="currentColor" d="${e}" />`).join(``),UO=`jant.slashCommandDiscovery`,WO=`/api/settings/discovery/slash-command`,GO=600,KO=3,qO=`compose-slash-discovery-visible`,JO=!1,YO=null,XO=null;function ZO(){try{return globalThis.localStorage!==void 0}catch{return!1}}function QO(){if(!ZO())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(UO);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(UO),{shownCount:0,completed:!1}}}function $O(e){if(ZO())try{globalThis.localStorage.setItem(UO,JSON.stringify(e))}catch{}}function ek(){YO!==null&&(clearTimeout(YO),YO=null)}function tk(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function nk(e){return QO().completed?!0:e.dataset.slashCommandDiscovered===`true`}function rk(){document.querySelectorAll(`jant-compose-editor`).forEach(e=>{e.dataset.slashCommandDiscovered=`true`,e.classList.remove(qO)})}function ik(){let e=QO();e.completed||JO||e.shownCount>=KO||(JO=!0,$O({...e,shownCount:e.shownCount+1}))}function ak(e){return!tk()||nk(e)?!1:QO().shownCount<KO||JO}function ok(e){ek(),e?e.classList.remove(qO):XO&&XO.classList.remove(qO),(!e||e===XO)&&(XO=null)}function sk(e){ak(e)&&(ok(XO),XO=e,e.classList.add(qO),ik())}function ck(e){ak(e)&&(e.classList.contains(qO)||(ek(),YO=setTimeout(()=>{sk(e)},GO)))}function lk(){let e=QO();e.completed||$O({shownCount:Math.max(e.shownCount,KO),completed:!0}),rk(),ok(XO),typeof globalThis.fetch==`function`&&globalThis.fetch(WO,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}var uk=`modulepreload`,dk=function(e){return`/`+e},fk={},pk=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=dk(t,n),t in fk)return;fk[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:uk,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},mk={media:`
1379
+ `}};customElements.define(`jant-compose-dialog`,EE);var DE=e=>e??m;function OE(e,t,n){return(t=FE(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function kE(){return kE=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},kE.apply(null,arguments)}function AE(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function jE(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?AE(Object(n),!0).forEach(function(t){OE(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):AE(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function ME(e,t){if(e==null)return{};var n,r,i=NE(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function NE(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function PE(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function FE(e){var t=PE(e,`string`);return typeof t==`symbol`?t:t+``}function IE(e){"@babel/helpers - typeof";return IE=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},IE(e)}var LE=`1.15.7`;function RE(e){if(typeof window<`u`&&window.navigator)return!!navigator.userAgent.match(e)}var zE=RE(/(?:Trident.*rv[ :]?11\.|msie|iemobile|Windows Phone)/i),BE=RE(/Edge/i),VE=RE(/firefox/i),HE=RE(/safari/i)&&!RE(/chrome/i)&&!RE(/android/i),UE=RE(/iP(ad|od|hone)/i),WE=RE(/chrome/i)&&RE(/android/i),GE={capture:!1,passive:!1};function L(e,t,n){e.addEventListener(t,n,!zE&&GE)}function R(e,t,n){e.removeEventListener(t,n,!zE&&GE)}function KE(e,t){if(t){if(t[0]===`>`&&(t=t.substring(1)),e)try{if(e.matches)return e.matches(t);if(e.msMatchesSelector)return e.msMatchesSelector(t);if(e.webkitMatchesSelector)return e.webkitMatchesSelector(t)}catch{return!1}return!1}}function qE(e){return e.host&&e!==document&&e.host.nodeType&&e.host!==e?e.host:e.parentNode}function JE(e,t,n,r){if(e){n||=document;do{if(t!=null&&(t[0]===`>`?e.parentNode===n&&KE(e,t):KE(e,t))||r&&e===n)return e;if(e===n)break}while(e=qE(e))}return null}var YE=/\s+/g;function XE(e,t,n){e&&t&&(e.classList?e.classList[n?`add`:`remove`](t):e.className=((` `+e.className+` `).replace(YE,` `).replace(` `+t+` `,` `)+(n?` `+t:``)).replace(YE,` `))}function z(e,t,n){var r=e&&e.style;if(r){if(n===void 0)return document.defaultView&&document.defaultView.getComputedStyle?n=document.defaultView.getComputedStyle(e,``):e.currentStyle&&(n=e.currentStyle),t===void 0?n:n[t];!(t in r)&&t.indexOf(`webkit`)===-1&&(t=`-webkit-`+t),r[t]=n+(typeof n==`string`?``:`px`)}}function ZE(e,t){var n=``;if(typeof e==`string`)n=e;else do{var r=z(e,`transform`);r&&r!==`none`&&(n=r+` `+n)}while(!t&&(e=e.parentNode));var i=window.DOMMatrix||window.WebKitCSSMatrix||window.CSSMatrix||window.MSCSSMatrix;return i&&new i(n)}function QE(e,t,n){if(e){var r=e.getElementsByTagName(t),i=0,a=r.length;if(n)for(;i<a;i++)n(r[i],i);return r}return[]}function $E(){return document.scrollingElement||document.documentElement}function eD(e,t,n,r,i){if(!(!e.getBoundingClientRect&&e!==window)){var a,o,s,c,l,u,d;if(e!==window&&e.parentNode&&e!==$E()?(a=e.getBoundingClientRect(),o=a.top,s=a.left,c=a.bottom,l=a.right,u=a.height,d=a.width):(o=0,s=0,c=window.innerHeight,l=window.innerWidth,u=window.innerHeight,d=window.innerWidth),(t||n)&&e!==window&&(i||=e.parentNode,!zE))do if(i&&i.getBoundingClientRect&&(z(i,`transform`)!==`none`||n&&z(i,`position`)!==`static`)){var f=i.getBoundingClientRect();o-=f.top+parseInt(z(i,`border-top-width`)),s-=f.left+parseInt(z(i,`border-left-width`)),c=o+a.height,l=s+a.width;break}while(i=i.parentNode);if(r&&e!==window){var p=ZE(i||e),m=p&&p.a,h=p&&p.d;p&&(o/=h,s/=m,d/=m,u/=h,c=o+u,l=s+d)}return{top:o,left:s,bottom:c,right:l,width:d,height:u}}}function tD(e,t,n){for(var r=sD(e,!0),i=eD(e)[t];r;){var a=eD(r)[n],o=void 0;if(o=n===`top`||n===`left`?i>=a:i<=a,!o)return r;if(r===$E())break;r=sD(r,!1)}return!1}function nD(e,t,n,r){for(var i=0,a=0,o=e.children;a<o.length;){if(o[a].style.display!==`none`&&o[a]!==H.ghost&&(r||o[a]!==H.dragged)&&JE(o[a],n.draggable,e,!1)){if(i===t)return o[a];i++}a++}return null}function rD(e,t){for(var n=e.lastElementChild;n&&(n===H.ghost||z(n,`display`)===`none`||t&&!KE(n,t));)n=n.previousElementSibling;return n||null}function iD(e,t){var n=0;if(!e||!e.parentNode)return-1;for(;e=e.previousElementSibling;)e.nodeName.toUpperCase()!==`TEMPLATE`&&e!==H.clone&&(!t||KE(e,t))&&n++;return n}function aD(e){var t=0,n=0,r=$E();if(e)do{var i=ZE(e),a=i.a,o=i.d;t+=e.scrollLeft*a,n+=e.scrollTop*o}while(e!==r&&(e=e.parentNode));return[t,n]}function oD(e,t){for(var n in e)if(e.hasOwnProperty(n)){for(var r in t)if(t.hasOwnProperty(r)&&t[r]===e[n][r])return Number(n)}return-1}function sD(e,t){if(!e||!e.getBoundingClientRect)return $E();var n=e,r=!1;do if(n.clientWidth<n.scrollWidth||n.clientHeight<n.scrollHeight){var i=z(n);if(n.clientWidth<n.scrollWidth&&(i.overflowX==`auto`||i.overflowX==`scroll`)||n.clientHeight<n.scrollHeight&&(i.overflowY==`auto`||i.overflowY==`scroll`)){if(!n.getBoundingClientRect||n===document.body)return $E();if(r||t)return n;r=!0}}while(n=n.parentNode);return $E()}function cD(e,t){if(e&&t)for(var n in t)t.hasOwnProperty(n)&&(e[n]=t[n]);return e}function lD(e,t){return Math.round(e.top)===Math.round(t.top)&&Math.round(e.left)===Math.round(t.left)&&Math.round(e.height)===Math.round(t.height)&&Math.round(e.width)===Math.round(t.width)}var uD;function dD(e,t){return function(){if(!uD){var n=arguments,r=this;n.length===1?e.call(r,n[0]):e.apply(r,n),uD=setTimeout(function(){uD=void 0},t)}}}function fD(){clearTimeout(uD),uD=void 0}function pD(e,t,n){e.scrollLeft+=t,e.scrollTop+=n}function mD(e){var t=window.Polymer,n=window.jQuery||window.Zepto;return t&&t.dom?t.dom(e).cloneNode(!0):n?n(e).clone(!0)[0]:e.cloneNode(!0)}function hD(e,t,n){var r={};return Array.from(e.children).forEach(function(i){if(!(!JE(i,t.draggable,e,!1)||i.animated||i===n)){var a=eD(i);r.left=Math.min(r.left??1/0,a.left),r.top=Math.min(r.top??1/0,a.top),r.right=Math.max(r.right??-1/0,a.right),r.bottom=Math.max(r.bottom??-1/0,a.bottom)}}),r.width=r.right-r.left,r.height=r.bottom-r.top,r.x=r.left,r.y=r.top,r}var gD=`Sortable`+new Date().getTime();function _D(){var e=[],t;return{captureAnimationState:function(){e=[],this.options.animation&&[].slice.call(this.el.children).forEach(function(t){if(!(z(t,`display`)===`none`||t===H.ghost)){e.push({target:t,rect:eD(t)});var n=jE({},e[e.length-1].rect);if(t.thisAnimationDuration){var r=ZE(t,!0);r&&(n.top-=r.f,n.left-=r.e)}t.fromRect=n}})},addAnimationState:function(t){e.push(t)},removeAnimationState:function(t){e.splice(oD(e,{target:t}),1)},animateAll:function(n){var r=this;if(!this.options.animation){clearTimeout(t),typeof n==`function`&&n();return}var i=!1,a=0;e.forEach(function(e){var t=0,n=e.target,o=n.fromRect,s=eD(n),c=n.prevFromRect,l=n.prevToRect,u=e.rect,d=ZE(n,!0);d&&(s.top-=d.f,s.left-=d.e),n.toRect=s,n.thisAnimationDuration&&lD(c,s)&&!lD(o,s)&&(u.top-s.top)/(u.left-s.left)===(o.top-s.top)/(o.left-s.left)&&(t=yD(u,c,l,r.options)),lD(s,o)||(n.prevFromRect=o,n.prevToRect=s,t||=r.options.animation,r.animate(n,u,s,t)),t&&(i=!0,a=Math.max(a,t),clearTimeout(n.animationResetTimer),n.animationResetTimer=setTimeout(function(){n.animationTime=0,n.prevFromRect=null,n.fromRect=null,n.prevToRect=null,n.thisAnimationDuration=null},t),n.thisAnimationDuration=t)}),clearTimeout(t),i?t=setTimeout(function(){typeof n==`function`&&n()},a):typeof n==`function`&&n(),e=[]},animate:function(e,t,n,r){if(r){z(e,`transition`,``),z(e,`transform`,``);var i=ZE(this.el),a=i&&i.a,o=i&&i.d,s=(t.left-n.left)/(a||1),c=(t.top-n.top)/(o||1);e.animatingX=!!s,e.animatingY=!!c,z(e,`transform`,`translate3d(`+s+`px,`+c+`px,0)`),this.forRepaintDummy=vD(e),z(e,`transition`,`transform `+r+`ms`+(this.options.easing?` `+this.options.easing:``)),z(e,`transform`,`translate3d(0,0,0)`),typeof e.animated==`number`&&clearTimeout(e.animated),e.animated=setTimeout(function(){z(e,`transition`,``),z(e,`transform`,``),e.animated=!1,e.animatingX=!1,e.animatingY=!1},r)}}}}function vD(e){return e.offsetWidth}function yD(e,t,n,r){return Math.sqrt((t.top-e.top)**2+(t.left-e.left)**2)/Math.sqrt((t.top-n.top)**2+(t.left-n.left)**2)*r.animation}var bD=[],xD={initializeByDefault:!0},SD={mount:function(e){for(var t in xD)xD.hasOwnProperty(t)&&!(t in e)&&(e[t]=xD[t]);bD.forEach(function(t){if(t.pluginName===e.pluginName)throw`Sortable: Cannot mount plugin ${e.pluginName} more than once`}),bD.push(e)},pluginEvent:function(e,t,n){var r=this;this.eventCanceled=!1,n.cancel=function(){r.eventCanceled=!0};var i=e+`Global`;bD.forEach(function(r){t[r.pluginName]&&(t[r.pluginName][i]&&t[r.pluginName][i](jE({sortable:t},n)),t.options[r.pluginName]&&t[r.pluginName][e]&&t[r.pluginName][e](jE({sortable:t},n)))})},initializePlugins:function(e,t,n,r){for(var i in bD.forEach(function(r){var i=r.pluginName;if(!(!e.options[i]&&!r.initializeByDefault)){var a=new r(e,t,e.options);a.sortable=e,a.options=e.options,e[i]=a,kE(n,a.defaults)}}),e.options)if(e.options.hasOwnProperty(i)){var a=this.modifyOption(e,i,e.options[i]);a!==void 0&&(e.options[i]=a)}},getEventProperties:function(e,t){var n={};return bD.forEach(function(r){typeof r.eventProperties==`function`&&kE(n,r.eventProperties.call(t[r.pluginName],e))}),n},modifyOption:function(e,t,n){var r;return bD.forEach(function(i){e[i.pluginName]&&i.optionListeners&&typeof i.optionListeners[t]==`function`&&(r=i.optionListeners[t].call(e[i.pluginName],n))}),r}};function CD(e){var t=e.sortable,n=e.rootEl,r=e.name,i=e.targetEl,a=e.cloneEl,o=e.toEl,s=e.fromEl,c=e.oldIndex,l=e.newIndex,u=e.oldDraggableIndex,d=e.newDraggableIndex,f=e.originalEvent,p=e.putSortable,m=e.extraEventProperties;if(t||=n&&n[gD],t){var h,g=t.options,_=`on`+r.charAt(0).toUpperCase()+r.substr(1);window.CustomEvent&&!zE&&!BE?h=new CustomEvent(r,{bubbles:!0,cancelable:!0}):(h=document.createEvent(`Event`),h.initEvent(r,!0,!0)),h.to=o||n,h.from=s||n,h.item=i||n,h.clone=a,h.oldIndex=c,h.newIndex=l,h.oldDraggableIndex=u,h.newDraggableIndex=d,h.originalEvent=f,h.pullMode=p?p.lastPutMode:void 0;var v=jE(jE({},m),SD.getEventProperties(r,t));for(var y in v)h[y]=v[y];n&&n.dispatchEvent(h),g[_]&&g[_].call(t,h)}}var wD=[`evt`],TD=function(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r=n.evt,i=ME(n,wD);SD.pluginEvent.bind(H)(e,t,jE({dragEl:B,parentEl:DD,ghostEl:V,rootEl:OD,nextEl:kD,lastDownEl:AD,cloneEl:jD,cloneHidden:MD,dragStarted:JD,putSortable:RD,activeSortable:H.active,originalEvent:r,oldIndex:ND,oldDraggableIndex:FD,newIndex:PD,newDraggableIndex:ID,hideGhostForTarget:pO,unhideGhostForTarget:mO,cloneNowHidden:function(){MD=!0},cloneNowShown:function(){MD=!1},dispatchSortableEvent:function(e){ED({sortable:t,name:e,originalEvent:r})}},i))};function ED(e){CD(jE({putSortable:RD,cloneEl:jD,targetEl:B,rootEl:OD,oldIndex:ND,oldDraggableIndex:FD,newIndex:PD,newDraggableIndex:ID},e))}var B,DD,V,OD,kD,AD,jD,MD,ND,PD,FD,ID,LD,RD,zD=!1,BD=!1,VD=[],HD,UD,WD,GD,KD,qD,JD,YD,XD,ZD=!1,QD=!1,$D,eO,tO=[],nO=!1,rO=[],iO=typeof document<`u`,aO=UE,oO=BE||zE?`cssFloat`:`float`,sO=iO&&!WE&&!UE&&`draggable`in document.createElement(`div`),cO=function(){if(iO){if(zE)return!1;var e=document.createElement(`x`);return e.style.cssText=`pointer-events:auto`,e.style.pointerEvents===`auto`}}(),lO=function(e,t){var n=z(e),r=parseInt(n.width)-parseInt(n.paddingLeft)-parseInt(n.paddingRight)-parseInt(n.borderLeftWidth)-parseInt(n.borderRightWidth),i=nD(e,0,t),a=nD(e,1,t),o=i&&z(i),s=a&&z(a),c=o&&parseInt(o.marginLeft)+parseInt(o.marginRight)+eD(i).width,l=s&&parseInt(s.marginLeft)+parseInt(s.marginRight)+eD(a).width;if(n.display===`flex`)return n.flexDirection===`column`||n.flexDirection===`column-reverse`?`vertical`:`horizontal`;if(n.display===`grid`)return n.gridTemplateColumns.split(` `).length<=1?`vertical`:`horizontal`;if(i&&o.float&&o.float!==`none`){var u=o.float===`left`?`left`:`right`;return a&&(s.clear===`both`||s.clear===u)?`vertical`:`horizontal`}return i&&(o.display===`block`||o.display===`flex`||o.display===`table`||o.display===`grid`||c>=r&&n[oO]===`none`||a&&n[oO]===`none`&&c+l>r)?`vertical`:`horizontal`},uO=function(e,t,n){var r=n?e.left:e.top,i=n?e.right:e.bottom,a=n?e.width:e.height,o=n?t.left:t.top,s=n?t.right:t.bottom,c=n?t.width:t.height;return r===o||i===s||r+a/2===o+c/2},dO=function(e,t){var n;return VD.some(function(r){var i=r[gD].options.emptyInsertThreshold;if(!(!i||rD(r))){var a=eD(r),o=e>=a.left-i&&e<=a.right+i,s=t>=a.top-i&&t<=a.bottom+i;if(o&&s)return n=r}}),n},fO=function(e){function t(e,n){return function(r,i,a,o){var s=r.options.group.name&&i.options.group.name&&r.options.group.name===i.options.group.name;if(e==null&&(n||s))return!0;if(e==null||e===!1)return!1;if(n&&e===`clone`)return e;if(typeof e==`function`)return t(e(r,i,a,o),n)(r,i,a,o);var c=(n?r:i).options.group.name;return e===!0||typeof e==`string`&&e===c||e.join&&e.indexOf(c)>-1}}var n={},r=e.group;(!r||IE(r)!=`object`)&&(r={name:r}),n.name=r.name,n.checkPull=t(r.pull,!0),n.checkPut=t(r.put),n.revertClone=r.revertClone,e.group=n},pO=function(){!cO&&V&&z(V,`display`,`none`)},mO=function(){!cO&&V&&z(V,`display`,``)};iO&&!WE&&document.addEventListener(`click`,function(e){if(BD)return e.preventDefault(),e.stopPropagation&&e.stopPropagation(),e.stopImmediatePropagation&&e.stopImmediatePropagation(),BD=!1,!1},!0);var hO=function(e){if(B){e=e.touches?e.touches[0]:e;var t=dO(e.clientX,e.clientY);if(t){var n={};for(var r in e)e.hasOwnProperty(r)&&(n[r]=e[r]);n.target=n.rootEl=t,n.preventDefault=void 0,n.stopPropagation=void 0,t[gD]._onDragOver(n)}}},gO=function(e){B&&B.parentNode[gD]._isOutsideThisEl(e.target)};function H(e,t){if(!(e&&e.nodeType&&e.nodeType===1))throw`Sortable: \`el\` must be an HTMLElement, not ${{}.toString.call(e)}`;this.el=e,this.options=t=kE({},t),e[gD]=this;var n={group:null,sort:!0,disabled:!1,store:null,handle:null,draggable:/^[uo]l$/i.test(e.nodeName)?`>li`:`>*`,swapThreshold:1,invertSwap:!1,invertedSwapThreshold:null,removeCloneOnHide:!0,direction:function(){return lO(e,this.options)},ghostClass:`sortable-ghost`,chosenClass:`sortable-chosen`,dragClass:`sortable-drag`,ignore:`a, img`,filter:null,preventOnFilter:!0,animation:0,easing:null,setData:function(e,t){e.setData(`Text`,t.textContent)},dropBubble:!1,dragoverBubble:!1,dataIdAttr:`data-id`,delay:0,delayOnTouchOnly:!1,touchStartThreshold:(Number.parseInt?Number:window).parseInt(window.devicePixelRatio,10)||1,forceFallback:!1,fallbackClass:`sortable-fallback`,fallbackOnBody:!1,fallbackTolerance:0,fallbackOffset:{x:0,y:0},supportPointer:H.supportPointer!==!1&&`PointerEvent`in window&&(!HE||UE),emptyInsertThreshold:5};for(var r in SD.initializePlugins(this,e,n),n)!(r in t)&&(t[r]=n[r]);for(var i in fO(t),this)i.charAt(0)===`_`&&typeof this[i]==`function`&&(this[i]=this[i].bind(this));this.nativeDraggable=t.forceFallback?!1:sO,this.nativeDraggable&&(this.options.touchStartThreshold=1),t.supportPointer?L(e,`pointerdown`,this._onTapStart):(L(e,`mousedown`,this._onTapStart),L(e,`touchstart`,this._onTapStart)),this.nativeDraggable&&(L(e,`dragover`,this),L(e,`dragenter`,this)),VD.push(this.el),t.store&&t.store.get&&this.sort(t.store.get(this)||[]),kE(this,_D())}H.prototype={constructor:H,_isOutsideThisEl:function(e){!this.el.contains(e)&&e!==this.el&&(YD=null)},_getDirection:function(e,t){return typeof this.options.direction==`function`?this.options.direction.call(this,e,t,B):this.options.direction},_onTapStart:function(e){if(e.cancelable){var t=this,n=this.el,r=this.options,i=r.preventOnFilter,a=e.type,o=e.touches&&e.touches[0]||e.pointerType&&e.pointerType===`touch`&&e,s=(o||e).target,c=e.target.shadowRoot&&(e.path&&e.path[0]||e.composedPath&&e.composedPath()[0])||s,l=r.filter;if(EO(n),!B&&!(/mousedown|pointerdown/.test(a)&&e.button!==0||r.disabled)&&!c.isContentEditable&&!(!this.nativeDraggable&&HE&&s&&s.tagName.toUpperCase()===`SELECT`)&&(s=JE(s,r.draggable,n,!1),!(s&&s.animated)&&AD!==s)){if(ND=iD(s),FD=iD(s,r.draggable),typeof l==`function`){if(l.call(this,e,s,this)){ED({sortable:t,rootEl:c,name:`filter`,targetEl:s,toEl:n,fromEl:n}),TD(`filter`,t,{evt:e}),i&&e.preventDefault();return}}else if(l&&(l=l.split(`,`).some(function(r){if(r=JE(c,r.trim(),n,!1),r)return ED({sortable:t,rootEl:r,name:`filter`,targetEl:s,fromEl:n,toEl:n}),TD(`filter`,t,{evt:e}),!0}),l)){i&&e.preventDefault();return}r.handle&&!JE(c,r.handle,n,!1)||this._prepareDragStart(e,o,s)}}},_prepareDragStart:function(e,t,n){var r=this,i=r.el,a=r.options,o=i.ownerDocument,s;if(n&&!B&&n.parentNode===i){var c=eD(n);if(OD=i,B=n,DD=B.parentNode,kD=B.nextSibling,AD=n,LD=a.group,H.dragged=B,HD={target:B,clientX:(t||e).clientX,clientY:(t||e).clientY},KD=HD.clientX-c.left,qD=HD.clientY-c.top,this._lastX=(t||e).clientX,this._lastY=(t||e).clientY,B.style[`will-change`]=`all`,s=function(){if(TD(`delayEnded`,r,{evt:e}),H.eventCanceled){r._onDrop();return}r._disableDelayedDragEvents(),!VE&&r.nativeDraggable&&(B.draggable=!0),r._triggerDragStart(e,t),ED({sortable:r,name:`choose`,originalEvent:e}),XE(B,a.chosenClass,!0)},a.ignore.split(`,`).forEach(function(e){QE(B,e.trim(),yO)}),L(o,`dragover`,hO),L(o,`mousemove`,hO),L(o,`touchmove`,hO),a.supportPointer?(L(o,`pointerup`,r._onDrop),!this.nativeDraggable&&L(o,`pointercancel`,r._onDrop)):(L(o,`mouseup`,r._onDrop),L(o,`touchend`,r._onDrop),L(o,`touchcancel`,r._onDrop)),VE&&this.nativeDraggable&&(this.options.touchStartThreshold=4,B.draggable=!0),TD(`delayStart`,this,{evt:e}),a.delay&&(!a.delayOnTouchOnly||t)&&(!this.nativeDraggable||!(BE||zE))){if(H.eventCanceled){this._onDrop();return}a.supportPointer?(L(o,`pointerup`,r._disableDelayedDrag),L(o,`pointercancel`,r._disableDelayedDrag)):(L(o,`mouseup`,r._disableDelayedDrag),L(o,`touchend`,r._disableDelayedDrag),L(o,`touchcancel`,r._disableDelayedDrag)),L(o,`mousemove`,r._delayedDragTouchMoveHandler),L(o,`touchmove`,r._delayedDragTouchMoveHandler),a.supportPointer&&L(o,`pointermove`,r._delayedDragTouchMoveHandler),r._dragStartTimer=setTimeout(s,a.delay)}else s()}},_delayedDragTouchMoveHandler:function(e){var t=e.touches?e.touches[0]:e;Math.max(Math.abs(t.clientX-this._lastX),Math.abs(t.clientY-this._lastY))>=Math.floor(this.options.touchStartThreshold/(this.nativeDraggable&&window.devicePixelRatio||1))&&this._disableDelayedDrag()},_disableDelayedDrag:function(){B&&yO(B),clearTimeout(this._dragStartTimer),this._disableDelayedDragEvents()},_disableDelayedDragEvents:function(){var e=this.el.ownerDocument;R(e,`mouseup`,this._disableDelayedDrag),R(e,`touchend`,this._disableDelayedDrag),R(e,`touchcancel`,this._disableDelayedDrag),R(e,`pointerup`,this._disableDelayedDrag),R(e,`pointercancel`,this._disableDelayedDrag),R(e,`mousemove`,this._delayedDragTouchMoveHandler),R(e,`touchmove`,this._delayedDragTouchMoveHandler),R(e,`pointermove`,this._delayedDragTouchMoveHandler)},_triggerDragStart:function(e,t){t||=e.pointerType==`touch`&&e,!this.nativeDraggable||t?this.options.supportPointer?L(document,`pointermove`,this._onTouchMove):t?L(document,`touchmove`,this._onTouchMove):L(document,`mousemove`,this._onTouchMove):(L(B,`dragend`,this),L(OD,`dragstart`,this._onDragStart));try{document.selection?DO(function(){document.selection.empty()}):window.getSelection().removeAllRanges()}catch{}},_dragStarted:function(e,t){if(zD=!1,OD&&B){TD(`dragStarted`,this,{evt:t}),this.nativeDraggable&&L(document,`dragover`,gO);var n=this.options;!e&&XE(B,n.dragClass,!1),XE(B,n.ghostClass,!0),H.active=this,e&&this._appendGhost(),ED({sortable:this,name:`start`,originalEvent:t})}else this._nulling()},_emulateDragOver:function(){if(UD){this._lastX=UD.clientX,this._lastY=UD.clientY,pO();for(var e=document.elementFromPoint(UD.clientX,UD.clientY),t=e;e&&e.shadowRoot&&(e=e.shadowRoot.elementFromPoint(UD.clientX,UD.clientY),e!==t);)t=e;if(B.parentNode[gD]._isOutsideThisEl(e),t)do{if(t[gD]){var n=void 0;if(n=t[gD]._onDragOver({clientX:UD.clientX,clientY:UD.clientY,target:e,rootEl:t}),n&&!this.options.dragoverBubble)break}e=t}while(t=qE(t));mO()}},_onTouchMove:function(e){if(HD){var t=this.options,n=t.fallbackTolerance,r=t.fallbackOffset,i=e.touches?e.touches[0]:e,a=V&&ZE(V,!0),o=V&&a&&a.a,s=V&&a&&a.d,c=aO&&eO&&aD(eO),l=(i.clientX-HD.clientX+r.x)/(o||1)+(c?c[0]-tO[0]:0)/(o||1),u=(i.clientY-HD.clientY+r.y)/(s||1)+(c?c[1]-tO[1]:0)/(s||1);if(!H.active&&!zD){if(n&&Math.max(Math.abs(i.clientX-this._lastX),Math.abs(i.clientY-this._lastY))<n)return;this._onDragStart(e,!0)}if(V){a?(a.e+=l-(WD||0),a.f+=u-(GD||0)):a={a:1,b:0,c:0,d:1,e:l,f:u};var d=`matrix(${a.a},${a.b},${a.c},${a.d},${a.e},${a.f})`;z(V,`webkitTransform`,d),z(V,`mozTransform`,d),z(V,`msTransform`,d),z(V,`transform`,d),WD=l,GD=u,UD=i}e.cancelable&&e.preventDefault()}},_appendGhost:function(){if(!V){var e=this.options.fallbackOnBody?document.body:OD,t=eD(B,!0,aO,!0,e),n=this.options;if(aO){for(eO=e;z(eO,`position`)===`static`&&z(eO,`transform`)===`none`&&eO!==document;)eO=eO.parentNode;eO!==document.body&&eO!==document.documentElement?(eO===document&&(eO=$E()),t.top+=eO.scrollTop,t.left+=eO.scrollLeft):eO=$E(),tO=aD(eO)}V=B.cloneNode(!0),XE(V,n.ghostClass,!1),XE(V,n.fallbackClass,!0),XE(V,n.dragClass,!0),z(V,`transition`,``),z(V,`transform`,``),z(V,`box-sizing`,`border-box`),z(V,`margin`,0),z(V,`top`,t.top),z(V,`left`,t.left),z(V,`width`,t.width),z(V,`height`,t.height),z(V,`opacity`,`0.8`),z(V,`position`,aO?`absolute`:`fixed`),z(V,`zIndex`,`100000`),z(V,`pointerEvents`,`none`),H.ghost=V,e.appendChild(V),z(V,`transform-origin`,KD/parseInt(V.style.width)*100+`% `+qD/parseInt(V.style.height)*100+`%`)}},_onDragStart:function(e,t){var n=this,r=e.dataTransfer,i=n.options;if(TD(`dragStart`,this,{evt:e}),H.eventCanceled){this._onDrop();return}TD(`setupClone`,this),H.eventCanceled||(jD=mD(B),jD.removeAttribute(`id`),jD.draggable=!1,jD.style[`will-change`]=``,this._hideClone(),XE(jD,this.options.chosenClass,!1),H.clone=jD),n.cloneId=DO(function(){TD(`clone`,n),!H.eventCanceled&&(n.options.removeCloneOnHide||OD.insertBefore(jD,B),n._hideClone(),ED({sortable:n,name:`clone`}))}),!t&&XE(B,i.dragClass,!0),t?(BD=!0,n._loopId=setInterval(n._emulateDragOver,50)):(R(document,`mouseup`,n._onDrop),R(document,`touchend`,n._onDrop),R(document,`touchcancel`,n._onDrop),r&&(r.effectAllowed=`move`,i.setData&&i.setData.call(n,r,B)),L(document,`drop`,n),z(B,`transform`,`translateZ(0)`)),zD=!0,n._dragStartId=DO(n._dragStarted.bind(n,t,e)),L(document,`selectstart`,n),JD=!0,window.getSelection().removeAllRanges(),HE&&z(document.body,`user-select`,`none`)},_onDragOver:function(e){var t=this.el,n=e.target,r,i,a,o=this.options,s=o.group,c=H.active,l=LD===s,u=o.sort,d=RD||c,f,p=this,m=!1;if(nO)return;function h(o,s){TD(o,p,jE({evt:e,isOwner:l,axis:f?`vertical`:`horizontal`,revert:a,dragRect:r,targetRect:i,canSort:u,fromSortable:d,target:n,completed:_,onMove:function(n,i){return vO(OD,t,B,r,n,eD(n),e,i)},changed:v},s))}function g(){h(`dragOverAnimationCapture`),p.captureAnimationState(),p!==d&&d.captureAnimationState()}function _(r){return h(`dragOverCompleted`,{insertion:r}),r&&(l?c._hideClone():c._showClone(p),p!==d&&(XE(B,RD?RD.options.ghostClass:c.options.ghostClass,!1),XE(B,o.ghostClass,!0)),RD!==p&&p!==H.active?RD=p:p===H.active&&RD&&(RD=null),d===p&&(p._ignoreWhileAnimating=n),p.animateAll(function(){h(`dragOverAnimationComplete`),p._ignoreWhileAnimating=null}),p!==d&&(d.animateAll(),d._ignoreWhileAnimating=null)),(n===B&&!B.animated||n===t&&!n.animated)&&(YD=null),!o.dragoverBubble&&!e.rootEl&&n!==document&&(B.parentNode[gD]._isOutsideThisEl(e.target),!r&&hO(e)),!o.dragoverBubble&&e.stopPropagation&&e.stopPropagation(),m=!0}function v(){PD=iD(B),ID=iD(B,o.draggable),ED({sortable:p,name:`change`,toEl:t,newIndex:PD,newDraggableIndex:ID,originalEvent:e})}if(e.preventDefault!==void 0&&e.cancelable&&e.preventDefault(),n=JE(n,o.draggable,t,!0),h(`dragOver`),H.eventCanceled)return m;if(B.contains(e.target)||n.animated&&n.animatingX&&n.animatingY||p._ignoreWhileAnimating===n)return _(!1);if(BD=!1,c&&!o.disabled&&(l?u||(a=DD!==OD):RD===this||(this.lastPutMode=LD.checkPull(this,c,B,e))&&s.checkPut(this,c,B,e))){if(f=this._getDirection(e,n)===`vertical`,r=eD(B),h(`dragOverValid`),H.eventCanceled)return m;if(a)return DD=OD,g(),this._hideClone(),h(`revert`),H.eventCanceled||(kD?OD.insertBefore(B,kD):OD.appendChild(B)),_(!0);var y=rD(t,o.draggable);if(!y||SO(e,f,this)&&!y.animated){if(y===B)return _(!1);if(y&&t===e.target&&(n=y),n&&(i=eD(n)),vO(OD,t,B,r,n,i,e,!!n)!==!1)return g(),y&&y.nextSibling?t.insertBefore(B,y.nextSibling):t.appendChild(B),DD=t,v(),_(!0)}else if(y&&xO(e,f,this)){var b=nD(t,0,o,!0);if(b===B)return _(!1);if(n=b,i=eD(n),vO(OD,t,B,r,n,i,e,!1)!==!1)return g(),t.insertBefore(B,b),DD=t,v(),_(!0)}else if(n.parentNode===t){i=eD(n);var x=0,S,C=B.parentNode!==t,ee=!uO(B.animated&&B.toRect||r,n.animated&&n.toRect||i,f),te=f?`top`:`left`,ne=tD(n,`top`,`top`)||tD(B,`top`,`top`),re=ne?ne.scrollTop:void 0;YD!==n&&(S=i[te],ZD=!1,QD=!ee&&o.invertSwap||C),x=CO(e,n,i,f,ee?1:o.swapThreshold,o.invertedSwapThreshold==null?o.swapThreshold:o.invertedSwapThreshold,QD,YD===n);var ie;if(x!==0){var ae=iD(B);do ae-=x,ie=DD.children[ae];while(ie&&(z(ie,`display`)===`none`||ie===V))}if(x===0||ie===n)return _(!1);YD=n,XD=x;var oe=n.nextElementSibling,se=!1;se=x===1;var ce=vO(OD,t,B,r,n,i,e,se);if(ce!==!1)return(ce===1||ce===-1)&&(se=ce===1),nO=!0,setTimeout(bO,30),g(),se&&!oe?t.appendChild(B):n.parentNode.insertBefore(B,se?oe:n),ne&&pD(ne,0,re-ne.scrollTop),DD=B.parentNode,S!==void 0&&!QD&&($D=Math.abs(S-eD(n)[te])),v(),_(!0)}if(t.contains(B))return _(!1)}return!1},_ignoreWhileAnimating:null,_offMoveEvents:function(){R(document,`mousemove`,this._onTouchMove),R(document,`touchmove`,this._onTouchMove),R(document,`pointermove`,this._onTouchMove),R(document,`dragover`,hO),R(document,`mousemove`,hO),R(document,`touchmove`,hO)},_offUpEvents:function(){var e=this.el.ownerDocument;R(e,`mouseup`,this._onDrop),R(e,`touchend`,this._onDrop),R(e,`pointerup`,this._onDrop),R(e,`pointercancel`,this._onDrop),R(e,`touchcancel`,this._onDrop),R(document,`selectstart`,this)},_onDrop:function(e){var t=this.el,n=this.options;if(PD=iD(B),ID=iD(B,n.draggable),TD(`drop`,this,{evt:e}),DD=B&&B.parentNode,PD=iD(B),ID=iD(B,n.draggable),H.eventCanceled){this._nulling();return}zD=!1,QD=!1,ZD=!1,clearInterval(this._loopId),clearTimeout(this._dragStartTimer),OO(this.cloneId),OO(this._dragStartId),this.nativeDraggable&&(R(document,`drop`,this),R(t,`dragstart`,this._onDragStart)),this._offMoveEvents(),this._offUpEvents(),HE&&z(document.body,`user-select`,``),z(B,`transform`,``),e&&(JD&&(e.cancelable&&e.preventDefault(),!n.dropBubble&&e.stopPropagation()),V&&V.parentNode&&V.parentNode.removeChild(V),(OD===DD||RD&&RD.lastPutMode!==`clone`)&&jD&&jD.parentNode&&jD.parentNode.removeChild(jD),B&&(this.nativeDraggable&&R(B,`dragend`,this),yO(B),B.style[`will-change`]=``,JD&&!zD&&XE(B,RD?RD.options.ghostClass:this.options.ghostClass,!1),XE(B,this.options.chosenClass,!1),ED({sortable:this,name:`unchoose`,toEl:DD,newIndex:null,newDraggableIndex:null,originalEvent:e}),OD===DD?PD!==ND&&PD>=0&&(ED({sortable:this,name:`update`,toEl:DD,originalEvent:e}),ED({sortable:this,name:`sort`,toEl:DD,originalEvent:e})):(PD>=0&&(ED({rootEl:DD,name:`add`,toEl:DD,fromEl:OD,originalEvent:e}),ED({sortable:this,name:`remove`,toEl:DD,originalEvent:e}),ED({rootEl:DD,name:`sort`,toEl:DD,fromEl:OD,originalEvent:e}),ED({sortable:this,name:`sort`,toEl:DD,originalEvent:e})),RD&&RD.save()),H.active&&((PD==null||PD===-1)&&(PD=ND,ID=FD),ED({sortable:this,name:`end`,toEl:DD,originalEvent:e}),this.save()))),this._nulling()},_nulling:function(){TD(`nulling`,this),OD=B=DD=V=kD=jD=AD=MD=HD=UD=JD=PD=ID=ND=FD=YD=XD=RD=LD=H.dragged=H.ghost=H.clone=H.active=null;var e=this.el;rO.forEach(function(t){e.contains(t)&&(t.checked=!0)}),rO.length=WD=GD=0},handleEvent:function(e){switch(e.type){case`drop`:case`dragend`:this._onDrop(e);break;case`dragenter`:case`dragover`:B&&(this._onDragOver(e),_O(e));break;case`selectstart`:e.preventDefault();break}},toArray:function(){for(var e=[],t,n=this.el.children,r=0,i=n.length,a=this.options;r<i;r++)t=n[r],JE(t,a.draggable,this.el,!1)&&e.push(t.getAttribute(a.dataIdAttr)||TO(t));return e},sort:function(e,t){var n={},r=this.el;this.toArray().forEach(function(e,t){var i=r.children[t];JE(i,this.options.draggable,r,!1)&&(n[e]=i)},this),t&&this.captureAnimationState(),e.forEach(function(e){n[e]&&(r.removeChild(n[e]),r.appendChild(n[e]))}),t&&this.animateAll()},save:function(){var e=this.options.store;e&&e.set&&e.set(this)},closest:function(e,t){return JE(e,t||this.options.draggable,this.el,!1)},option:function(e,t){var n=this.options;if(t===void 0)return n[e];var r=SD.modifyOption(this,e,t);r===void 0?n[e]=t:n[e]=r,e===`group`&&fO(n)},destroy:function(){TD(`destroy`,this);var e=this.el;e[gD]=null,R(e,`mousedown`,this._onTapStart),R(e,`touchstart`,this._onTapStart),R(e,`pointerdown`,this._onTapStart),this.nativeDraggable&&(R(e,`dragover`,this),R(e,`dragenter`,this)),Array.prototype.forEach.call(e.querySelectorAll(`[draggable]`),function(e){e.removeAttribute(`draggable`)}),this._onDrop(),this._disableDelayedDragEvents(),VD.splice(VD.indexOf(this.el),1),this.el=e=null},_hideClone:function(){if(!MD){if(TD(`hideClone`,this),H.eventCanceled)return;z(jD,`display`,`none`),this.options.removeCloneOnHide&&jD.parentNode&&jD.parentNode.removeChild(jD),MD=!0}},_showClone:function(e){if(e.lastPutMode!==`clone`){this._hideClone();return}if(MD){if(TD(`showClone`,this),H.eventCanceled)return;B.parentNode==OD&&!this.options.group.revertClone?OD.insertBefore(jD,B):kD?OD.insertBefore(jD,kD):OD.appendChild(jD),this.options.group.revertClone&&this.animate(B,jD),z(jD,`display`,``),MD=!1}}};function _O(e){e.dataTransfer&&(e.dataTransfer.dropEffect=`move`),e.cancelable&&e.preventDefault()}function vO(e,t,n,r,i,a,o,s){var c,l=e[gD],u=l.options.onMove,d;return window.CustomEvent&&!zE&&!BE?c=new CustomEvent(`move`,{bubbles:!0,cancelable:!0}):(c=document.createEvent(`Event`),c.initEvent(`move`,!0,!0)),c.to=t,c.from=e,c.dragged=n,c.draggedRect=r,c.related=i||t,c.relatedRect=a||eD(t),c.willInsertAfter=s,c.originalEvent=o,e.dispatchEvent(c),u&&(d=u.call(l,c,o)),d}function yO(e){e.draggable=!1}function bO(){nO=!1}function xO(e,t,n){var r=eD(nD(n.el,0,n.options,!0)),i=hD(n.el,n.options,V),a=10;return t?e.clientX<i.left-a||e.clientY<r.top&&e.clientX<r.right:e.clientY<i.top-a||e.clientY<r.bottom&&e.clientX<r.left}function SO(e,t,n){var r=eD(rD(n.el,n.options.draggable)),i=hD(n.el,n.options,V),a=10;return t?e.clientX>i.right+a||e.clientY>r.bottom&&e.clientX>r.left:e.clientY>i.bottom+a||e.clientX>r.right&&e.clientY>r.top}function CO(e,t,n,r,i,a,o,s){var c=r?e.clientY:e.clientX,l=r?n.height:n.width,u=r?n.top:n.left,d=r?n.bottom:n.right,f=!1;if(!o){if(s&&$D<l*i){if(!ZD&&(XD===1?c>u+l*a/2:c<d-l*a/2)&&(ZD=!0),ZD)f=!0;else if(XD===1?c<u+$D:c>d-$D)return-XD}else if(c>u+l*(1-i)/2&&c<d-l*(1-i)/2)return wO(t)}return f||=o,f&&(c<u+l*a/2||c>d-l*a/2)?c>u+l/2?1:-1:0}function wO(e){return iD(B)<iD(e)?1:-1}function TO(e){for(var t=e.tagName+e.className+e.src+e.href+e.textContent,n=t.length,r=0;n--;)r+=t.charCodeAt(n);return r.toString(36)}function EO(e){rO.length=0;for(var t=e.getElementsByTagName(`input`),n=t.length;n--;){var r=t[n];r.checked&&rO.push(r)}}function DO(e){return setTimeout(e,0)}function OO(e){return clearTimeout(e)}iO&&L(document,`touchmove`,function(e){(H.active||zD)&&e.cancelable&&e.preventDefault()}),H.utils={on:L,off:R,css:z,find:QE,is:function(e,t){return!!JE(e,t,e,!1)},extend:cD,throttle:dD,closest:JE,toggleClass:XE,clone:mD,index:iD,nextTick:DO,cancelNextTick:OO,detectDirection:lO,getChild:nD,expando:gD},H.get=function(e){return e[gD]},H.mount=function(){var e=[...arguments];e[0].constructor===Array&&(e=e[0]),e.forEach(function(e){if(!e.prototype||!e.prototype.constructor)throw`Sortable: Mounted plugin must be a constructor function, not ${{}.toString.call(e)}`;e.utils&&(H.utils=jE(jE({},H.utils),e.utils)),SD.mount(e)})},H.create=function(e,t){return new H(e,t)},H.version=LE;var kO=[],AO,jO,MO=!1,NO,PO,FO,IO;function LO(){function e(){for(var e in this.defaults={scroll:!0,forceAutoScrollFallback:!1,scrollSensitivity:30,scrollSpeed:10,bubbleScroll:!0},this)e.charAt(0)===`_`&&typeof this[e]==`function`&&(this[e]=this[e].bind(this))}return e.prototype={dragStarted:function(e){var t=e.originalEvent;this.sortable.nativeDraggable?L(document,`dragover`,this._handleAutoScroll):this.options.supportPointer?L(document,`pointermove`,this._handleFallbackAutoScroll):t.touches?L(document,`touchmove`,this._handleFallbackAutoScroll):L(document,`mousemove`,this._handleFallbackAutoScroll)},dragOverCompleted:function(e){var t=e.originalEvent;!this.options.dragOverBubble&&!t.rootEl&&this._handleAutoScroll(t)},drop:function(){this.sortable.nativeDraggable?R(document,`dragover`,this._handleAutoScroll):(R(document,`pointermove`,this._handleFallbackAutoScroll),R(document,`touchmove`,this._handleFallbackAutoScroll),R(document,`mousemove`,this._handleFallbackAutoScroll)),zO(),RO(),fD()},nulling:function(){FO=jO=AO=MO=IO=NO=PO=null,kO.length=0},_handleFallbackAutoScroll:function(e){this._handleAutoScroll(e,!0)},_handleAutoScroll:function(e,t){var n=this,r=(e.touches?e.touches[0]:e).clientX,i=(e.touches?e.touches[0]:e).clientY,a=document.elementFromPoint(r,i);if(FO=e,t||this.options.forceAutoScrollFallback||BE||zE||HE){BO(e,this.options,a,t);var o=sD(a,!0);MO&&(!IO||r!==NO||i!==PO)&&(IO&&zO(),IO=setInterval(function(){var a=sD(document.elementFromPoint(r,i),!0);a!==o&&(o=a,RO()),BO(e,n.options,a,t)},10),NO=r,PO=i)}else{if(!this.options.bubbleScroll||sD(a,!0)===$E()){RO();return}BO(e,this.options,sD(a,!1),!1)}}},kE(e,{pluginName:`scroll`,initializeByDefault:!0})}function RO(){kO.forEach(function(e){clearInterval(e.pid)}),kO=[]}function zO(){clearInterval(IO)}var BO=dD(function(e,t,n,r){if(t.scroll){var i=(e.touches?e.touches[0]:e).clientX,a=(e.touches?e.touches[0]:e).clientY,o=t.scrollSensitivity,s=t.scrollSpeed,c=$E(),l=!1,u;jO!==n&&(jO=n,RO(),AO=t.scroll,u=t.scrollFn,AO===!0&&(AO=sD(n,!0)));var d=0,f=AO;do{var p=f,m=eD(p),h=m.top,g=m.bottom,_=m.left,v=m.right,y=m.width,b=m.height,x=void 0,S=void 0,C=p.scrollWidth,ee=p.scrollHeight,te=z(p),ne=p.scrollLeft,re=p.scrollTop;p===c?(x=y<C&&(te.overflowX===`auto`||te.overflowX===`scroll`||te.overflowX===`visible`),S=b<ee&&(te.overflowY===`auto`||te.overflowY===`scroll`||te.overflowY===`visible`)):(x=y<C&&(te.overflowX===`auto`||te.overflowX===`scroll`),S=b<ee&&(te.overflowY===`auto`||te.overflowY===`scroll`));var ie=x&&(Math.abs(v-i)<=o&&ne+y<C)-(Math.abs(_-i)<=o&&!!ne),ae=S&&(Math.abs(g-a)<=o&&re+b<ee)-(Math.abs(h-a)<=o&&!!re);if(!kO[d])for(var oe=0;oe<=d;oe++)kO[oe]||(kO[oe]={});(kO[d].vx!=ie||kO[d].vy!=ae||kO[d].el!==p)&&(kO[d].el=p,kO[d].vx=ie,kO[d].vy=ae,clearInterval(kO[d].pid),(ie!=0||ae!=0)&&(l=!0,kO[d].pid=setInterval(function(){r&&this.layer===0&&H.active._onTouchMove(FO);var t=kO[this.layer].vy?kO[this.layer].vy*s:0,n=kO[this.layer].vx?kO[this.layer].vx*s:0;typeof u==`function`&&u.call(H.dragged.parentNode[gD],n,t,e,FO,kO[this.layer].el)!==`continue`||pD(kO[this.layer].el,n,t)}.bind({layer:d}),24))),d++}while(t.bubbleScroll&&f!==c&&(f=sD(f,!1)));MO=l}},30),VO=function(e){var t=e.originalEvent,n=e.putSortable,r=e.dragEl,i=e.activeSortable,a=e.dispatchSortableEvent,o=e.hideGhostForTarget,s=e.unhideGhostForTarget;if(t){var c=n||i;o();var l=t.changedTouches&&t.changedTouches.length?t.changedTouches[0]:t,u=document.elementFromPoint(l.clientX,l.clientY);s(),c&&!c.el.contains(u)&&(a(`spill`),this.onSpill({dragEl:r,putSortable:n}))}};function HO(){}HO.prototype={startIndex:null,dragStart:function(e){this.startIndex=e.oldDraggableIndex},onSpill:function(e){var t=e.dragEl,n=e.putSortable;this.sortable.captureAnimationState(),n&&n.captureAnimationState();var r=nD(this.sortable.el,this.startIndex,this.options);r?this.sortable.el.insertBefore(t,r):this.sortable.el.appendChild(t),this.sortable.animateAll(),n&&n.animateAll()},drop:VO},kE(HO,{pluginName:`revertOnSpill`});function UO(){}UO.prototype={onSpill:function(e){var t=e.dragEl,n=e.putSortable||this.sortable;n.captureAnimationState(),t.parentNode&&t.parentNode.removeChild(t),n.animateAll()},drop:VO},kE(UO,{pluginName:`removeOnSpill`}),H.mount(new LO),H.mount(UO,HO);var WO={animation:180,bubbleScroll:!1,delay:150,delayOnTouchOnly:!0,fallbackTolerance:4,forceAutoScrollFallback:!0,scrollSensitivity:56,scrollSpeed:18};function GO(e,t,n){return[...e.querySelectorAll(t)].map(e=>e.dataset[n]).filter(e=>e!==void 0)}function KO(e){return e.item.nextSibling}function qO(e,t,n=null){let{item:r,oldIndex:i,newIndex:a}=t;if(i==null||a==null||i===a)return;if(r.parentNode?.removeChild(r),n){e.insertBefore(r,n);return}let o=e.children;i>=o.length?e.appendChild(r):e.insertBefore(r,o[i]??null)}function JO(e,t){if(t){e.dataset.dragging=`true`;return}delete e.dataset.dragging}function YO(e,t){let n=t==null?void 0:e[t];if(!n)return{movedId:void 0,movedIndex:-1,afterId:null,beforeId:null};let r=e.indexOf(n);return{movedId:n,movedIndex:r,afterId:r>0?e[r-1]:null,beforeId:r>=0&&r<e.length-1?e[r+1]:null}}var XO=`0 0 96 96`,ZO=[`M24.4 10.5C16.9 17.7 11.5 26.8 8.2 37.7C4.9 48.7 4.8 58.9 7.8 68.2C10.3 75.7 15.4 79.5 22.9 79.5C28 79.5 32.2 77.8 35.4 74.2C38.6 70.7 40.2 66.5 40.2 61.4C40.2 56.5 38.8 52.6 36 49.6C33.3 46.6 29.7 45.1 25.2 45.1C23.4 45.1 21.8 45.3 20.2 45.8C22.2 37.3 26.7 29.2 33.6 21.4L24.4 10.5Z`,`M60.8 10.5C53.3 17.7 47.9 26.8 44.6 37.7C41.3 48.7 41.2 58.9 44.2 68.2C46.7 75.7 51.8 79.5 59.3 79.5C64.4 79.5 68.6 77.8 71.8 74.2C75 70.7 76.6 66.5 76.6 61.4C76.6 56.5 75.2 52.6 72.4 49.6C69.7 46.6 66.1 45.1 61.6 45.1C59.8 45.1 58.2 45.3 56.6 45.8C58.6 37.3 63.1 29.2 70 21.4L60.8 10.5Z`].map(e=>`<path fill="currentColor" d="${e}" />`).join(``),QO=`jant.slashCommandDiscovery`,$O=`/api/settings/discovery/slash-command`,ek=600,tk=3,nk=`compose-slash-discovery-visible`,rk=!1,ik=null,ak=null;function ok(){try{return globalThis.localStorage!==void 0}catch{return!1}}function sk(){if(!ok())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(QO);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(QO),{shownCount:0,completed:!1}}}function ck(e){if(ok())try{globalThis.localStorage.setItem(QO,JSON.stringify(e))}catch{}}function lk(){ik!==null&&(clearTimeout(ik),ik=null)}function uk(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function dk(e){return sk().completed?!0:e.dataset.slashCommandDiscovered===`true`}function fk(){document.querySelectorAll(`jant-compose-editor`).forEach(e=>{e.dataset.slashCommandDiscovered=`true`,e.classList.remove(nk)})}function pk(){let e=sk();e.completed||rk||e.shownCount>=tk||(rk=!0,ck({...e,shownCount:e.shownCount+1}))}function mk(e){return!uk()||dk(e)?!1:sk().shownCount<tk||rk}function hk(e){lk(),e?e.classList.remove(nk):ak&&ak.classList.remove(nk),(!e||e===ak)&&(ak=null)}function gk(e){mk(e)&&(hk(ak),ak=e,e.classList.add(nk),pk())}function _k(e){mk(e)&&(e.classList.contains(nk)||(lk(),ik=setTimeout(()=>{gk(e)},ek)))}function vk(){let e=sk();e.completed||ck({shownCount:Math.max(e.shownCount,tk),completed:!0}),fk(),hk(ak),typeof globalThis.fetch==`function`&&globalThis.fetch($O,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}var yk=`modulepreload`,bk=function(e){return`/`+e},xk={},Sk=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}r=o(t.map(t=>{if(t=bk(t,n),t in xk)return;xk[t]=!0;let r=t.endsWith(`.css`),i=r?`[rel="stylesheet"]`:``;if(n)for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}else if(document.querySelector(`link[href="${t}"]${i}`))return;let o=document.createElement(`link`);if(o.rel=r?`stylesheet`:yk,r||(o.as=`script`),o.crossOrigin=``,o.href=t,a&&o.setAttribute(`nonce`,a),document.head.appendChild(o),r)return new Promise((e,n)=>{o.addEventListener(`load`,e),o.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})},Ck={media:`
1380
1380
  <rect x="2.75" y="3" width="12.5" height="11.25" rx="3" />
1381
1381
  <circle cx="6.15" cy="6.85" r="0.85" fill="currentColor" stroke="none" />
1382
1382
  <path d="M3.6 11.95 6.75 8.8c.42-.42 1.11-.42 1.53 0l1.4 1.4" />
@@ -1435,7 +1435,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1435
1435
  <path d="M12.15 3H15v2.85" stroke-width="1.48" />
1436
1436
  <path d="M3 12.15V15h2.85" stroke-width="1.48" />
1437
1437
  <path d="M15 12.15V15h-2.85" stroke-width="1.48" />
1438
- `};function hk(e){return u`<svg
1438
+ `};function wk(e){return u`<svg
1439
1439
  class="compose-tool-icon"
1440
1440
  width="18"
1441
1441
  height="18"
@@ -1448,18 +1448,18 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1448
1448
  aria-hidden="true"
1449
1449
  >
1450
1450
  ${ke(e)}
1451
- </svg>`}function gk(e){return u`<span
1451
+ </svg>`}function Tk(e){return u`<span
1452
1452
  class=${`decorative-quote-mark ${e}`}
1453
1453
  aria-hidden="true"
1454
1454
  >
1455
1455
  <svg
1456
- viewBox=${VO}
1456
+ viewBox=${XO}
1457
1457
  role="presentation"
1458
1458
  focusable="false"
1459
1459
  >
1460
- ${ke(HO)}
1460
+ ${ke(ZO)}
1461
1461
  </svg>
1462
- </span>`}function _k(e,t){let n=e.state.doc.content.size,r=Math.max(1,Math.min(t.from,n));return{from:r,to:Math.max(r,Math.min(t.to,n))}}var vk=class e extends _{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},threadItem:{type:Boolean,attribute:`thread-item`},removable:{type:Boolean},inlineFormat:{type:Boolean,attribute:`inline-format`},slashCommandDiscovered:{type:Boolean},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_failedAttachmentPreviews:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_lastEditorSelection=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${ZT()}`;_onDocClickBound=this._onDocumentClick.bind(this);_scrollBufferApplied=!1;_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;_suppressContentChangedOnce=!1;#e=0;#t=new Set;#n=null;#r=null;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=1024,this.threadItem=!1,this.removable=!1,this.inlineFormat=!1,this.slashCommandDiscovered=!1,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),this.addEventListener(`dragenter`,this._onDragEnter),this.addEventListener(`dragover`,this._onDragOver,!0),this.addEventListener(`dragleave`,this._onDragLeave),this.addEventListener(`drop`,this._onDrop)}disconnectedCallback(){super.disconnectedCallback(),this.#o(),this._editor?.destroy(),this._editor=null,this.#n?.destroy(),this.#n=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),document.removeEventListener(`click`,this._onDocClickBound),this.removeEventListener(`dragenter`,this._onDragEnter),this.removeEventListener(`dragover`,this._onDragOver,!0),this.removeEventListener(`dragleave`,this._onDragLeave),this.removeEventListener(`drop`,this._onDrop),ok(this),this._emojiContainer?.remove(),this._emojiPickerEl=null,this._filePickerCleanup?.(),this._filePickerCleanup=null}#i=0;#a(e){let t=e.dataTransfer?.types;return t?Array.from(t).includes(`Files`):!1}_onDragEnter=e=>{this.#a(e)&&(this.#i+=1,this.classList.add(`compose-editor-dragover`))};_onDragOver=e=>{this.#a(e)&&(e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`))};_onDragLeave=e=>{this.#a(e)&&(this.#i=Math.max(0,this.#i-1),this.#i===0&&this.classList.remove(`compose-editor-dragover`))};_onDrop=e=>{if(this.#i=0,this.classList.remove(`compose-editor-dragover`),e.defaultPrevented)return;let t=Cw(e.dataTransfer);if(t.length===0)return;e.preventDefault();let n=[],r=[];for(let e of t)this._editor&&this._shouldPasteInlineImage(e)?n.push(e):r.push(e);for(let e of n)this._uploadAndInsertImage(e);r.length>0&&this.addFiles(r)};_onSlashCommandDiscovered=()=>{lk()};_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=this.#e,r=gw(t,e).finally(()=>{n===this.#e&&this.#t.delete(r)});return this.#t.add(r),r}hasPendingInlineImageUploads(){return this.#t.size>0}async waitForPendingInlineImageUploads(){let e=this.#e;for(;e===this.#e&&this.#t.size>0;)await Promise.allSettled(Array.from(this.#t))}#o(){this.#e+=1,this.#t.clear()}adoptPendingUploads(){if(!this._editor)return;let e=this.#e,t=_w(this._editor);for(let n of t){let t=n.finally(()=>{e===this.#e&&this.#t.delete(t)});this.#t.add(t)}}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0||e.content.every(e=>e.type===`hardBreak`)))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}reset(){this.#o(),this._title=``,this._bodyJson=null,this._editor?.commands.clearContent(),this._lastEditorSelection=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl),e.posterUrl&&URL.revokeObjectURL(e.posterUrl);this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r){this._attachments=this._attachments.map(i=>i.clientId===e?{...i,status:t,mediaId:n,error:r}:i)}updateAttachmentPreview(e,t){this._setAttachmentPreviewFailure(e,!1),this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),n.posterUrl&&URL.revokeObjectURL(n.posterUrl),{...n,file:t,previewUrl:URL.createObjectURL(t),posterUrl:null}):n)}updateAttachmentPoster(e,t){let n=URL.createObjectURL(t);this._attachments=this._attachments.map(t=>t.clientId===e?{...t,posterUrl:n}:t)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusSelection(e){if(this.format!==`note`||!this._editor){this.focusInput();return}let t=e??this.getEditorSelection();if(!t){this.focusInput();return}let n=_k(this._editor,t);this._lastEditorSelection=n,this._editor.chain().focus().setTextSelection(n).run()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?r(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}_getInlineUrlValidationMessage(){return this.format===`link`&&!this._url.trim()?null:this.getUrlValidationMessage()}_getInlineLinkTitleValidationMessage(){return this.format!==`link`||!this._title.trim()?null:this.getLinkTitleValidationMessage()}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}getEditorSelection(){return this._readEditorSelection()??this._lastEditorSelection}isEmojiPickerOpen(){return this._showEmojiPicker}_readEditorSelection(){if(!this._editor)return null;let{from:e,to:t}=this._editor.state.selection;return{from:e,to:t}}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);if(!e||this._editor)return;this.dataset.slashCommandDiscovered=this.slashCommandDiscovered?`true`:`false`,this._editor=JT({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this._ensureScrollBuffer(),ok(this)},onFocus:()=>{this._lastFocusedField=null,this._editor?.isEmpty&&ck(this)},onSelectionUpdate:e=>{this._lastEditorSelection=e},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),uploadInlineImage:e=>this._uploadAndInsertImage(e),onPasteFiles:e=>{this.addFiles(e)}}}),this._lastEditorSelection=this._readEditorSelection(),this._scrollBufferApplied=!1;let t=this._editor.view.dom;if(!this.closest(`.compose-page-shell`)){let e=t.lastElementChild,n=e?e.offsetTop+e.offsetHeight:0,r=this.format===`note`?120:60;t.style.minHeight=`${n+r}px`}}_ensureScrollBuffer(){if(this._scrollBufferApplied)return;let e=this._editor?.view?.dom;if(!e)return;let t=this.querySelector(`.compose-body`);t&&t.scrollHeight>t.clientHeight+20&&(e.style.paddingBottom=`40px`,this._scrollBufferApplied=!0)}_destroyEditor(){this.#o(),this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);updated(t){if(super.updated(t),this._editor||this._initEditor(),t.has(`format`)&&t.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(t.has(`_attachmentOrder`)||t.has(`_attachments`)||t.has(`_attachedTexts`))&&(t.has(`_attachments`)&&this._syncFailedAttachmentPreviews(),this._attachmentOrder.length>1?this.#s():(this.#n?.destroy(),this.#n=null)),this._suppressContentChangedOnce)this._suppressContentChangedOnce=!1;else for(let n of t.keys())if(e._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle,selection:this.getEditorSelection()}}getConvertibleFields(){return{title:this._title,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor,showTitle:this._showTitle,bodyJson:this._normalizeDocJson(this._editor?.getJSON()??this._bodyJson)}}applyConvertedFields(e){this._suppressContentChangedOnce=!0,this._title=e.title,this._url=e.url,this._quoteText=e.quoteText,this._quoteAuthor=e.quoteAuthor,this._showTitle=e.showTitle,this._bodyJson=e.bodyJson}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),this._failedAttachmentPreviews=[],e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:ZT(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,status:`done`,progress:null,mediaId:e.id,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e.textAttachments.map(e=>{let t=null;try{t=JSON.parse(e.bodyJson)}catch{}return{clientId:e.clientId??ZT(),bodyJson:t,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:t}});this._attachedTexts=t,this._attachmentOrder=[...this._attachmentOrder,...t.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1}setEditorState(e,t,n,r){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]}),this._lastEditorSelection=r??this._readEditorSelection()}static SUMMARY_LENGTH=100;_computeSummary(t){let n=t.replace(/\s+/g,` `).trim();return n.length<=e.SUMMARY_LENGTH?n:n.slice(0,e.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:ZT(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t){let n=this._attachmentOrder.indexOf(e),r=n+t;if(n===-1||r<0||r>=this._attachmentOrder.length)return;let i=[...this._attachmentOrder],[a]=i.splice(n,1);a&&(i.splice(r,0,a),this._attachmentOrder=i,this.#c(e))}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#s(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#n||this._attachmentOrder.length<=1||(this.#n=H.create(e,{...FO,chosenClass:`compose-attachment-chosen`,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{zO(e,!0)},onStart:e=>{this.#r=LO(e)},onUnchoose:()=>{zO(e,!1)},onEnd:t=>{let n=IO(e,`[data-attachment-id]`,`attachmentId`);if(RO(e,t,this.#r),this.#r=null,zO(e,!1),this.#n?.destroy(),this.#n=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=BO(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#c(e))}}}))}#c(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&(t.mediaId||this._hasAttachedTextContent(t.bodyJson)||(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format===`note`&&!this._showTitle?!1:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`*/*`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;!e||e.length===0||this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=DS(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){a(t,`error`);continue}let i=ZT(),o=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:o,posterUrl:null,status:`pending`,progress:null,mediaId:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)TS(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(this._setAttachmentPreviewFailure(t.clientId,!1),URL.revokeObjectURL(t.previewUrl),t.posterUrl&&URL.revokeObjectURL(t.posterUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){this._lastFocusedField=e.target}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),this._emojiPickerEl=null,document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){e.focus();return}this.focusSelection()}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([pk(()=>import(`./chunks/native-DpcrFAPh.js`),[]),pk(()=>import(`./chunks/module-DcsAZQZ_.js`),[])]);if(!this._showEmojiPicker)return;this._emojiPickerEl=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`})}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-352/2;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return TS(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:TS(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/html; charset=utf-8`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,u`<svg
1462
+ </span>`}function Ek(e,t){let n=e.state.doc.content.size,r=Math.max(1,Math.min(t.from,n));return{from:r,to:Math.max(r,Math.min(t.to,n))}}var Dk=class e extends _{static properties={format:{type:String},labels:{type:Object},uploadMaxFileSize:{type:Number},threadItem:{type:Boolean,attribute:`thread-item`},removable:{type:Boolean},inlineFormat:{type:Boolean,attribute:`inline-format`},slashCommandDiscovered:{type:Boolean},_title:{state:!0},_bodyJson:{state:!0},_url:{state:!0},_quoteText:{state:!0},_quoteAuthor:{state:!0},_rating:{state:!0},_showTitle:{state:!0},_showRating:{state:!0},_attachedTexts:{state:!0},_attachments:{state:!0},_attachmentOrder:{state:!0},_failedAttachmentPreviews:{state:!0},_showAltPanel:{state:!0},_altPanelIndex:{state:!0},_showEmojiPicker:{state:!0},_showUrlValidation:{state:!0},_showLinkTitleValidation:{state:!0}};_editor=null;_fileInput=null;_lastFocusedField=null;_lastEditorSelection=null;_emojiPickerEl=null;_emojiContainer=null;_urlStatusId=`compose-url-status-${oE()}`;_onDocClickBound=this._onDocumentClick.bind(this);_scrollBufferApplied=!1;_filePickerCleanup=null;_suppressAttachedTextOpenUntil=0;_suppressContentChangedOnce=!1;#e=0;#t=new Set;#n=0;#r;#i=null;#a=null;createRenderRoot(){return this}constructor(){super(),this.format=`note`,this.labels={},this.uploadMaxFileSize=1024,this.threadItem=!1,this.removable=!1,this.inlineFormat=!1,this.slashCommandDiscovered=!1,this._title=``,this._bodyJson=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[],this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showEmojiPicker=!1,this._showUrlValidation=!1,this._showLinkTitleValidation=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),this.addEventListener(`dragenter`,this._onDragEnter),this.addEventListener(`dragover`,this._onDragOver,!0),this.addEventListener(`dragleave`,this._onDragLeave),this.addEventListener(`drop`,this._onDrop)}disconnectedCallback(){super.disconnectedCallback(),this.#f(),this._editor?.destroy(),this._editor=null,this.#i?.destroy(),this.#i=null,document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`jant:slash-command-discovered`,this._onSlashCommandDiscovered),document.removeEventListener(`click`,this._onDocClickBound),this.removeEventListener(`dragenter`,this._onDragEnter),this.removeEventListener(`dragover`,this._onDragOver,!0),this.removeEventListener(`dragleave`,this._onDragLeave),this.removeEventListener(`drop`,this._onDrop),hk(this),this._emojiContainer?.remove(),this._emojiPickerEl=null,this._filePickerCleanup?.(),this._filePickerCleanup=null}#o=0;#s(e){let t=e.dataTransfer?.types;return t?Array.from(t).includes(`Files`):!1}_onDragEnter=e=>{this.#s(e)&&(this.#o+=1,this.classList.add(`compose-editor-dragover`))};_onDragOver=e=>{this.#s(e)&&(e.stopPropagation(),e.preventDefault(),e.dataTransfer&&(e.dataTransfer.dropEffect=`copy`))};_onDragLeave=e=>{this.#s(e)&&(this.#o=Math.max(0,this.#o-1),this.#o===0&&this.classList.remove(`compose-editor-dragover`))};_onDrop=e=>{if(this.#o=0,this.classList.remove(`compose-editor-dragover`),e.defaultPrevented)return;let t=Dw(e.dataTransfer);if(t.length===0)return;e.preventDefault();let n=[],r=[];for(let e of t)this._editor&&this._shouldPasteInlineImage(e)?n.push(e):r.push(e);for(let e of n)this._uploadAndInsertImage(e);r.length>0&&this.addFiles(r)};_onSlashCommandDiscovered=()=>{vk()};_onSlashImage=()=>{document.querySelector(`.compose-fullscreen-dialog[open]`)||this._editor&&this._triggerSlashImagePicker()};_slashImageInput=null;_triggerSlashImagePicker(){this._slashImageInput||(this._slashImageInput=document.createElement(`input`),this._slashImageInput.type=`file`,this._slashImageInput.accept=`image/*`,this._slashImageInput.style.display=`none`,this._slashImageInput.addEventListener(`change`,()=>{let e=this._slashImageInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._slashImageInput&&(this._slashImageInput.value=``)}),document.body.appendChild(this._slashImageInput)),this._trackFilePickerSession(this._slashImageInput),this._slashImageInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=this.#e,r=_w(t,e).finally(()=>{n===this.#e&&this.#t.delete(r)});return this.#t.add(r),r}#c(e){if(e.startsWith(`data:`))return!0;if(!/^https?:\/\//i.test(e))return!1;let t;try{t=new URL(e).origin}catch{return!1}if(t===window.location.origin)return!1;let n=document.documentElement.dataset.mediaBase;return!(n&&e.startsWith(n))}#l(e){let t=this._editor;if(!t){JT(e);return}let n=e.startsWith(`data:`)?async()=>{let t=await(await fetch(e)).blob();return(await dw(new File([t],`pasted-image`,{type:t.type||`image/png`}))).url}:async()=>(await vw(e)).url,r=async()=>{try{return await n()}catch(e){throw this.#u(),e}},i=this.#e,a=yw(t,e,r).finally(()=>{JT(e),i===this.#e&&this.#t.delete(a)});this.#t.add(a)}#u(){this.#n+=1,this.#r===void 0&&(this.#r=setTimeout(()=>{this.#d()},800))}#d(){this.#r=void 0;let e=this.#n;this.#n=0,!(e<=0||!this.isConnected)&&a(e===1?this.labels.imageNotRehosted??`An image couldn't be saved to your library — its original link was kept.`:(this.labels.imagesNotRehosted??`{count} images couldn't be saved to your library — their original links were kept.`).replace(`{count}`,String(e)),`error`)}hasPendingInlineImageUploads(){return this.#t.size>0}async waitForPendingInlineImageUploads(){let e=this.#e;for(;e===this.#e&&this.#t.size>0;)await Promise.allSettled(Array.from(this.#t))}#f(){this.#e+=1,this.#t.clear(),this.#r!==void 0&&(clearTimeout(this.#r),this.#r=void 0),this.#n=0}adoptPendingUploads(){if(!this._editor)return;let e=this.#e,t=bw(this._editor);for(let n of t){let t=n.finally(()=>{e===this.#e&&this.#t.delete(t)});this.#t.add(t)}}_dispatchFilePickerEvent(e,t){this.dispatchEvent(new CustomEvent(e,{bubbles:!0,composed:!0,detail:t}))}_trackFilePickerSession(e){this._filePickerCleanup?.();let t=!1,n=e=>{t||(t=!0,o(),this._dispatchFilePickerEvent(`jant:file-picker-close`,{cancelled:e}))},r=()=>n(!1),i=()=>n(!0),a=()=>{globalThis.setTimeout(()=>{n(!(e.files&&e.files.length>0))},0)},o=()=>{e.removeEventListener(`change`,r),e.removeEventListener(`cancel`,i),window.removeEventListener(`focus`,a),this._filePickerCleanup===o&&(this._filePickerCleanup=null)};this._filePickerCleanup=o,e.addEventListener(`change`,r,{once:!0}),e.addEventListener(`cancel`,i,{once:!0}),window.addEventListener(`focus`,a,{once:!0}),this._dispatchFilePickerEvent(`jant:file-picker-open`)}_isEmptyDoc(e){return!e.content||e.content.length===0?!0:e.content.every(e=>e.type===`paragraph`&&(!e.content||e.content.length===0||e.content.every(e=>e.type===`hardBreak`)))}_normalizeDocJson(e){return e?this._isEmptyDoc(e)?null:e:null}getNormalizedBodyJson(){return this._normalizeDocJson(this._bodyJson)}getEffectiveAttachedTexts(){return this._attachedTexts.flatMap(e=>{let t=this._normalizeDocJson(e.bodyJson);return t?[{...e,bodyJson:t,originalBodyJson:this._normalizeDocJson(e.originalBodyJson??null)}]:[]})}getEffectiveAttachmentOrder(){let e=new Set(this.getEffectiveAttachedTexts().map(e=>e.clientId)),t=new Set(this._attachments.map(e=>e.clientId));return this._attachmentOrder.filter(n=>t.has(n)||e.has(n))}_getEffectiveRating(){return this._showRating?this._rating:0}getData(){let e=this.getNormalizedBodyJson(),t=this.getEffectiveAttachedTexts(),n=this.getEffectiveAttachmentOrder(),r=e?JSON.stringify(e):``,i={rating:this._getEffectiveRating(),attachedTexts:t,attachments:this._attachments,attachmentOrder:n};switch(this.format){case`link`:return{...i,title:this._title,body:r,url:this._url,quoteText:``,quoteAuthor:``};case`quote`:return{...i,title:``,body:r,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor};default:return{...i,title:this._showTitle?this._title:``,body:r,url:``,quoteText:``,quoteAuthor:``}}}reset(){this.#f(),this._title=``,this._bodyJson=null,this._editor?.commands.clearContent(),this._lastEditorSelection=null,this._url=``,this._quoteText=``,this._quoteAuthor=``,this._rating=0,this._showTitle=!1,this._showRating=!1,this._attachedTexts=[];for(let e of this._attachments)URL.revokeObjectURL(e.previewUrl),e.posterUrl&&URL.revokeObjectURL(e.posterUrl);this._attachments=[],this._attachmentOrder=[],this._failedAttachmentPreviews=[],this._showAltPanel=!1,this._altPanelIndex=0,this._showUrlValidation=!1,this._showLinkTitleValidation=!1,this.closeEmojiPicker()}updateAttachmentStatus(e,t,n,r){this._attachments=this._attachments.map(i=>i.clientId===e?{...i,status:t,mediaId:n,error:r}:i)}updateAttachmentPreview(e,t){this._setAttachmentPreviewFailure(e,!1),this._attachments=this._attachments.map(n=>n.clientId===e?(URL.revokeObjectURL(n.previewUrl),n.posterUrl&&URL.revokeObjectURL(n.posterUrl),{...n,file:t,previewUrl:URL.createObjectURL(t),posterUrl:null}):n)}updateAttachmentPoster(e,t){let n=URL.createObjectURL(t);this._attachments=this._attachments.map(t=>t.clientId===e?{...t,posterUrl:n}:t)}updateAttachmentProgress(e,t){this._attachments=this._attachments.map(n=>n.clientId===e?{...n,progress:t}:n)}focusInput(e){if(this.format===`link`){this.focusUrlInput(e);return}if(this.format===`quote`){this._focusTextControl(this.querySelector(`.compose-quote-text`),e);return}if(e){this._editor?.commands.focus(e);return}this._editor?.commands.focus()}focusSelection(e){if(this.format!==`note`||!this._editor){this.focusInput();return}let t=e??this.getEditorSelection();if(!t){this.focusInput();return}let n=Ek(this._editor,t);this._lastEditorSelection=n,this._editor.chain().focus().setTextSelection(n).run()}focusUrlInput(e){this._focusTextControl(this.querySelector(`.compose-url-input`),e)}focusLinkTitleInput(e){this._focusTextControl(this.querySelector(`.compose-link-title`),e)}getUrlValidationMessage(){return this.format===`note`?null:this._url.trim()?r(this._url)?null:this.labels.urlInvalid:this.format===`link`?this.labels.linkUrlRequired:null}getLinkTitleValidationMessage(){return this.format===`link`?this._title.trim()?null:this.labels.linkTitleRequired:null}_getInlineUrlValidationMessage(){return this.format===`link`&&!this._url.trim()?null:this.getUrlValidationMessage()}_getInlineLinkTitleValidationMessage(){return this.format!==`link`||!this._title.trim()?null:this.getLinkTitleValidationMessage()}revealUrlValidation(){return this._showUrlValidation=!0,this.getUrlValidationMessage()}revealLinkTitleValidation(){return this._showLinkTitleValidation=!0,this.getLinkTitleValidationMessage()}getEditorSelection(){return this._readEditorSelection()??this._lastEditorSelection}isEmojiPickerOpen(){return this._showEmojiPicker}_readEditorSelection(){if(!this._editor)return null;let{from:e,to:t}=this._editor.state.selection;return{from:e,to:t}}_focusTextControl(e,t){if(!e||(e.focus(),!t))return;let n=t===`end`?e.value.length:0;e.setSelectionRange(n,n)}_initEditor(){let e=this.querySelector(`.compose-tiptap-body`);if(!e||this._editor)return;this.dataset.slashCommandDiscovered=this.slashCommandDiscovered?`true`:`false`,this._editor=rE({element:e,placeholder:this.format===`note`?this.labels.bodyPlaceholder:this.labels.thoughtsPlaceholder,content:this._bodyJson,toolbarMode:`compose`,onUpdate:e=>{this._bodyJson=e,this._ensureScrollBuffer(),hk(this)},onFocus:()=>{this._lastFocusedField=null,this._editor?.isEmpty&&_k(this)},onSelectionUpdate:e=>{this._lastEditorSelection=e},pasteMedia:{shouldInsertInline:e=>this._shouldPasteInlineImage(e),uploadInlineImage:e=>this._uploadAndInsertImage(e),onPasteFiles:e=>{this.addFiles(e)}},rehostImages:{shouldRehost:e=>this.#c(e),rehost:e=>this.#l(e)}}),this._lastEditorSelection=this._readEditorSelection(),this._scrollBufferApplied=!1;let t=this._editor.view.dom;if(!this.closest(`.compose-page-shell`)){let e=t.lastElementChild,n=e?e.offsetTop+e.offsetHeight:0,r=this.format===`note`?120:60;t.style.minHeight=`${n+r}px`}}_ensureScrollBuffer(){if(this._scrollBufferApplied)return;let e=this._editor?.view?.dom;if(!e)return;let t=this.querySelector(`.compose-body`);t&&t.scrollHeight>t.clientHeight+20&&(e.style.paddingBottom=`40px`,this._scrollBufferApplied=!0)}_destroyEditor(){this.#f(),this._editor?.destroy(),this._editor=null}static _CONTENT_PROPS=new Set([`_title`,`_bodyJson`,`_url`,`_quoteText`,`_quoteAuthor`,`_rating`,`_showTitle`,`_showRating`,`_attachedTexts`,`_attachmentOrder`]);updated(t){if(super.updated(t),this._editor||this._initEditor(),t.has(`format`)&&t.get(`format`)!==void 0&&(this._showUrlValidation&&=!1,this._showLinkTitleValidation&&=!1,this._destroyEditor(),this.updateComplete.then(()=>this._initEditor())),(t.has(`_attachmentOrder`)||t.has(`_attachments`)||t.has(`_attachedTexts`))&&(t.has(`_attachments`)&&this._syncFailedAttachmentPreviews(),this._attachmentOrder.length>1?this.#p():(this.#i?.destroy(),this.#i=null)),this._suppressContentChangedOnce)this._suppressContentChangedOnce=!1;else for(let n of t.keys())if(e._CONTENT_PROPS.has(n)){this.dispatchEvent(new Event(`jant:compose-content-changed`,{bubbles:!0}));break}}getEditorState(){return{json:this._editor?.getJSON()??this._bodyJson,title:this._title,showTitle:this._showTitle,selection:this.getEditorSelection()}}getConvertibleFields(){return{title:this._title,url:this._url,quoteText:this._quoteText,quoteAuthor:this._quoteAuthor,showTitle:this._showTitle,bodyJson:this._normalizeDocJson(this._editor?.getJSON()??this._bodyJson)}}applyConvertedFields(e){this._suppressContentChangedOnce=!0,this._title=e.title,this._url=e.url,this._quoteText=e.quoteText,this._quoteAuthor=e.quoteAuthor,this._showTitle=e.showTitle,this._bodyJson=e.bodyJson}populate(e){if(e.title&&(this._title=e.title),e.url&&(this._url=e.url),e.quoteText&&(this._quoteText=e.quoteText),e.quoteAuthor&&(this._quoteAuthor=e.quoteAuthor),e.rating&&e.rating>0&&(this._rating=e.rating,this._showRating=!0),e.showTitle===void 0?e.title&&e.format===`note`&&(this._showTitle=!0):this._showTitle=e.showTitle,e.showRating!==void 0&&(this._showRating=e.showRating),this._failedAttachmentPreviews=[],e.bodyJson)try{let t=JSON.parse(e.bodyJson);this._bodyJson=t,this._editor&&this._editor.commands.setContent(t)}catch{}if(e.media?.length){let t=e.media.map(e=>({clientId:oE(),file:new File([],e.originalName??`existing`,{type:e.mimeType}),previewUrl:e.previewUrl,posterUrl:e.posterUrl??null,status:`done`,progress:null,mediaId:e.id,alt:e.alt??``,error:null,summary:e.summary??null,chars:e.chars??null}));this._attachments=t,this._attachmentOrder=t.map(e=>e.clientId)}if(e.textAttachments?.length){let t=e.textAttachments.map(e=>{let t=null;try{t=JSON.parse(e.bodyJson)}catch{}return{clientId:e.clientId??oE(),bodyJson:t,bodyHtml:e.bodyHtml??``,summary:e.summary,mediaId:e.mediaId,originalBodyJson:t}});this._attachedTexts=t,this._attachmentOrder=[...this._attachmentOrder,...t.map(e=>e.clientId)]}if(e.attachmentOrder?.length){let t=e.attachmentOrder.map(e=>this._attachments.find(t=>t.mediaId===e||t.clientId===e)?.clientId||this._attachedTexts.find(t=>t.mediaId===e||t.clientId===e)?.clientId).filter(e=>e!==void 0),n=this._attachmentOrder.filter(e=>!t.includes(e));this._attachmentOrder=[...t,...n]}this._showUrlValidation=!1,this._showLinkTitleValidation=!1}setEditorState(e,t,n,r){this._bodyJson=e,this._title=t,this.format===`note`&&(this._showTitle=n||t.length>0),this._editor&&this._editor.commands.setContent(e??{type:`doc`,content:[{type:`paragraph`}]}),this._lastEditorSelection=r??this._readEditorSelection()}static SUMMARY_LENGTH=100;_computeSummary(t){let n=t.replace(/\s+/g,` `).trim();return n.length<=e.SUMMARY_LENGTH?n:n.slice(0,e.SUMMARY_LENGTH)+`…`}_openAttachedText(){let e={clientId:oE(),bodyJson:null,bodyHtml:``,summary:``};this._attachedTexts=[...this._attachedTexts,e],this._attachmentOrder=[...this._attachmentOrder,e.clientId];let t=this._attachedTexts.length-1;this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:t}}))}_moveAttachment(e,t){let n=this._attachmentOrder.indexOf(e),r=n+t;if(n===-1||r<0||r>=this._attachmentOrder.length)return;let i=[...this._attachmentOrder],[a]=i.splice(n,1);a&&(i.splice(r,0,a),this._attachmentOrder=i,this.#m(e))}_handleAttachmentKeydown(e,t,n){if(t.key===`ArrowLeft`||t.key===`ArrowUp`){t.preventDefault(),this._moveAttachment(e,-1);return}if(t.key===`ArrowRight`||t.key===`ArrowDown`){t.preventDefault(),this._moveAttachment(e,1);return}n&&(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),n())}#p(){let e=this.querySelector(`[data-attachment-list]`);!e||this.#i||this._attachmentOrder.length<=1||(this.#i=H.create(e,{...WO,chosenClass:`compose-attachment-chosen`,direction:`horizontal`,dragClass:`compose-attachment-drag`,filter:`button, a, input, textarea, select, option, [contenteditable='true']`,ghostClass:`compose-attachment-ghost`,handle:`[data-attachment-sortable]`,preventOnFilter:!1,scroll:e,onChoose:()=>{JO(e,!0)},onStart:e=>{this.#a=KO(e)},onUnchoose:()=>{JO(e,!1)},onEnd:t=>{let n=GO(e,`[data-attachment-id]`,`attachmentId`);if(qO(e,t,this.#a),this.#a=null,JO(e,!1),this.#i?.destroy(),this.#i=null,n.length===this._attachmentOrder.length){this._attachmentOrder=n;let{movedId:e}=YO(n,t.newIndex);e&&(this._suppressAttachedTextOpenUntil=Date.now()+250,this.#m(e))}}}))}#m(e){this.updateComplete.then(()=>{this.querySelector(`[data-attachment-id="${e}"]`)?.scrollIntoView({behavior:`smooth`,block:`nearest`,inline:`nearest`})})}_maybeEditAttachedText(e){Date.now()<this._suppressAttachedTextOpenUntil||this._editAttachedText(e)}_editAttachedText(e){this.dispatchEvent(new CustomEvent(`jant:attached-panel-open`,{bubbles:!0,detail:{index:e}}))}_removeAttachedText(e){let t=this._attachedTexts[e];this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId))}updateAttachedText(e,t,n){let r=this._normalizeDocJson(t),i=this._extractPlainText(r);this._attachedTexts=this._attachedTexts.map((t,a)=>a===e?{...t,bodyJson:r,bodyHtml:r?n??``:``,summary:this._computeSummary(i)}:t)}closeAttachedPanel(e){let t=this._attachedTexts[e];t&&(t.mediaId||this._hasAttachedTextContent(t.bodyJson)||(this._attachedTexts=this._attachedTexts.filter((t,n)=>n!==e),this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)))}_hasAttachedTextContent(e){let t=this._normalizeDocJson(e);return t?this._extractPlainText(t).trim().length>0:!1}_extractPlainText(e){if(!e)return``;let t=``,n=e=>{e.text&&(t+=e.text),e.content&&e.content.forEach(n)};return n(e),t}_onInput(e,t){let n=t.target;this[e]=n.value,n.tagName===`TEXTAREA`&&this._autoResize(n)}_autoResize(e){e.style.height=`auto`,e.style.height=`${e.scrollHeight}px`}_setRating(e){this._rating=this._rating===e?0:e}_shouldPasteInlineImage(e){return!e.type.startsWith(`image/`)||this.format===`note`&&!this._showTitle?!1:this._title.trim().length>0}_openFilePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`*/*`,this._fileInput.multiple=!0,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>this._handleFilesSelected()),this.appendChild(this._fileInput)),this._fileInput.value=``,this._trackFilePickerSession(this._fileInput),this._fileInput.click()}_handleFilesSelected(){let e=this._fileInput?.files;!e||e.length===0||this.addFiles(e)}addFiles(e){let t=Array.from(e);if(t.length===0)return;let n=[],r=[];for(let e of t){let t=DS(e,{maxFileSizeMB:this.uploadMaxFileSize});if(t){a(t,`error`);continue}let i=oE(),o=URL.createObjectURL(e);n.push({clientId:i,file:e,previewUrl:o,posterUrl:null,status:`pending`,progress:null,mediaId:null,alt:``,error:null,summary:null,chars:null}),r.push({file:e,clientId:i})}if(n.length!==0){this._attachments=[...this._attachments,...n],this._attachmentOrder=[...this._attachmentOrder,...n.map(e=>e.clientId)];for(let e of n)TS(e.file.type)===`text`&&e.file.text().then(t=>{let n=this._computeSummary(t),r=t.length;this._attachments=this._attachments.map(t=>t.clientId===e.clientId?{...t,summary:n,chars:r}:t)});this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:r}}))}}removeAttachment(e){let t=this._attachments.findIndex(t=>t.clientId===e);t!==-1&&this._removeAttachment(t)}_removeAttachment(e){let t=this._attachments[e];t&&(this._setAttachmentPreviewFailure(t.clientId,!1),URL.revokeObjectURL(t.previewUrl),t.posterUrl&&URL.revokeObjectURL(t.posterUrl),this.dispatchEvent(new CustomEvent(`jant:attachment-removed`,{bubbles:!0,detail:{clientId:t.clientId,mediaId:t.mediaId}}))),t&&(this._attachmentOrder=this._attachmentOrder.filter(e=>e!==t.clientId)),this._attachments=this._attachments.filter((t,n)=>n!==e),this._showAltPanel&&this._altPanelIndex===e?(this._showAltPanel=!1,this.dispatchEvent(new CustomEvent(`jant:alt-panel-close`,{bubbles:!0}))):this._showAltPanel&&this._altPanelIndex>e&&--this._altPanelIndex}_retryAllFailed(){let e=this._attachments.filter(e=>e.status===`error`);e.length!==0&&(this._attachments=this._attachments.map(e=>e.status===`error`?{...e,status:`pending`,progress:null,error:null}:e),this.dispatchEvent(new CustomEvent(`jant:files-selected`,{bubbles:!0,detail:{files:e.map(e=>({file:e.file,clientId:e.clientId}))}})))}_openAltPanel(e){this._altPanelIndex=e,this._showAltPanel=!0,this.dispatchEvent(new CustomEvent(`jant:alt-panel-open`,{bubbles:!0,detail:{index:e}}))}updateAlt(e,t){this._attachments=this._attachments.map((n,r)=>r===e?{...n,alt:t}:n)}_onFieldFocus(e){this._lastFocusedField=e.target}_toggleEmojiPicker(){this._showEmojiPicker?this.closeEmojiPicker():(this._showEmojiPicker=!0,this._mountEmojiPicker(),globalThis.setTimeout(()=>{document.addEventListener(`click`,this._onDocClickBound)},0))}closeEmojiPicker(e){if(!this._showEmojiPicker){e?.restoreFocus&&this._restoreEmojiFocus();return}this._showEmojiPicker=!1,this._emojiContainer?.remove(),this._emojiPickerEl=null,document.removeEventListener(`click`,this._onDocClickBound),e?.restoreFocus&&this._restoreEmojiFocus()}_restoreEmojiFocus(){let e=this._lastFocusedField;if(e&&this.contains(e)&&!e.disabled){e.focus();return}this.focusSelection()}_onDocumentClick(e){let t=e.target;this.querySelector(`.compose-emoji-btn`)?.contains(t)||this._emojiContainer?.contains(t)||this.closeEmojiPicker()}async _mountEmojiPicker(){let e=this.closest(`dialog`);if(this._emojiContainer||(this._emojiContainer=document.createElement(`div`),this._emojiContainer.className=`compose-emoji-picker`),(e??document.body).appendChild(this._emojiContainer),!this._emojiPickerEl){let[{default:e},{Picker:t}]=await Promise.all([Sk(()=>import(`./chunks/native-DpcrFAPh.js`),[]),Sk(()=>import(`./chunks/module-DcsAZQZ_.js`),[])]);if(!this._showEmojiPicker)return;this._emojiPickerEl=new t({data:e,onEmojiSelect:e=>{this._insertEmoji(e.native),this.closeEmojiPicker()},theme:`auto`,previewPosition:`none`,skinTonePosition:`none`})}this._emojiContainer.innerHTML=``,this._emojiContainer.appendChild(this._emojiPickerEl);let t=this.querySelector(`.compose-emoji-btn`);if(t&&e){let n=t.getBoundingClientRect(),r=e.getBoundingClientRect(),i=n.left-r.left,a=n.top-r.top,o=i+n.width/2-352/2;o=Math.max(-r.left+8,Math.min(o,r.width-8));let s=a-435-8;r.top+s<8&&(s=a+n.height+8),this._emojiContainer.style.left=`${o}px`,this._emojiContainer.style.top=`${s}px`}}_insertEmoji(e){let t=this._lastFocusedField;if(!t){this._editor&&this._editor.chain().focus().insertContent(e).run();return}let n=t.selectionStart??t.value.length,r=t.selectionEnd??n,i=t.value.slice(0,n),a=t.value.slice(r);t.value=i+e+a,t.dispatchEvent(new Event(`input`,{bubbles:!0}));let o=n+e.length;globalThis.requestAnimationFrame(()=>{t.focus(),t.setSelectionRange(o,o)})}_getCategory(e){return TS(e.file.type)}_formatSize(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}_formatChars(e){return e<1e3?`${e} chars`:e<1e6?`${parseFloat((e/1e3).toFixed(1))}k chars`:`${parseFloat((e/1e6).toFixed(1))}M chars`}_renderFileIcon(e,t){let n;return n=e===`application/pdf`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`:e===`text/markdown`?`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`:e===`text/csv`?`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`:TS(e)===`archive`?`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`:e===`text/html; charset=utf-8`?`<line x1="16" y1="11" x2="8" y2="11"/><line x1="16" y1="14" x2="8" y2="14"/><line x1="12" y1="17" x2="8" y2="17"/>`:`<line x1="16" y1="13" x2="8" y2="13"/><line x1="16" y1="17" x2="8" y2="17"/><line x1="10" y1="9" x2="8" y2="9"/>`,u`<svg
1463
1463
  width="${t}"
1464
1464
  height="${t}"
1465
1465
  viewBox="0 0 24 24"
@@ -1542,7 +1542,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1542
1542
  class="compose-input compose-url-input"
1543
1543
  placeholder=${this.labels.urlPlaceholder}
1544
1544
  aria-invalid=${e?`true`:`false`}
1545
- aria-describedby=${vE(e?this._urlStatusId:void 0)}
1545
+ aria-describedby=${DE(e?this._urlStatusId:void 0)}
1546
1546
  />
1547
1547
  </div>
1548
1548
  ${e?u`<p
@@ -1581,7 +1581,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1581
1581
  `}_renderQuoteFields(){let e=this._showUrlValidation?this.getUrlValidationMessage():null;return u`
1582
1582
  <div class="compose-field-enter">
1583
1583
  <div class="compose-quote-wrap">
1584
- ${gk(`compose-quote-mark`)}
1584
+ ${Tk(`compose-quote-mark`)}
1585
1585
  <textarea
1586
1586
  .value=${this._quoteText}
1587
1587
  @input=${e=>this._onInput(`_quoteText`,e)}
@@ -1612,7 +1612,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1612
1612
  class="compose-input compose-url-input compose-quote-source-input"
1613
1613
  placeholder=${this.labels.sourcePlaceholder}
1614
1614
  aria-invalid=${e?`true`:`false`}
1615
- aria-describedby=${vE(e?this._urlStatusId:void 0)}
1615
+ aria-describedby=${DE(e?this._urlStatusId:void 0)}
1616
1616
  />
1617
1617
  ${e?u`<p
1618
1618
  id=${this._urlStatusId}
@@ -1893,7 +1893,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1893
1893
  title=${this._attachments.length>0?``:this.labels.media}
1894
1894
  @click=${()=>this._openFilePicker()}
1895
1895
  >
1896
- ${hk(mk.media)}
1896
+ ${wk(Ck.media)}
1897
1897
  ${this._attachments.length>0?u`<span class="compose-tool-label"
1898
1898
  >${this.labels.addMore}</span
1899
1899
  >`:m}
@@ -1905,7 +1905,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1905
1905
  title=${e?``:this.labels.attachedText}
1906
1906
  @click=${()=>this._openAttachedText()}
1907
1907
  >
1908
- ${hk(mk.attachedText)}
1908
+ ${wk(Ck.attachedText)}
1909
1909
  ${e?u`<span class="compose-tool-label"
1910
1910
  >${this.labels.addMore}</span
1911
1911
  >`:m}
@@ -1917,7 +1917,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1917
1917
  title=${this.labels.emoji}
1918
1918
  @click=${()=>this._toggleEmojiPicker()}
1919
1919
  >
1920
- ${hk(mk.emoji)}
1920
+ ${wk(Ck.emoji)}
1921
1921
  </button>
1922
1922
 
1923
1923
  <div class="compose-tool-sep"></div>
@@ -1928,7 +1928,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1928
1928
  title=${this.labels.rate}
1929
1929
  @click=${()=>{let e=!this._showRating;this._showRating=e,e&&this.updateComplete.then(()=>{this.querySelector(`.compose-star-rating`)?.scrollIntoView({block:`nearest`,behavior:`smooth`})})}}
1930
1930
  >
1931
- ${hk(mk.rate)}
1931
+ ${wk(Ck.rate)}
1932
1932
  </button>
1933
1933
 
1934
1934
  ${this.format===`note`?u`
@@ -1938,7 +1938,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1938
1938
  title=${this.labels.title}
1939
1939
  @click=${()=>{let e=!this._showTitle;this._showTitle=e,e&&this.updateComplete.then(()=>{this.querySelector(`.compose-note-title`)?.focus()})}}
1940
1940
  >
1941
- ${hk(mk.title)}
1941
+ ${wk(Ck.title)}
1942
1942
  </button>
1943
1943
  `:m}
1944
1944
  ${this.format===`note`?u`
@@ -1950,7 +1950,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1950
1950
  aria-label=${this.labels.fullscreen}
1951
1951
  @click=${()=>this.openFullscreen()}
1952
1952
  >
1953
- ${hk(mk.fullscreen)}
1953
+ ${wk(Ck.fullscreen)}
1954
1954
  </button>
1955
1955
  </div>
1956
1956
  `:m}
@@ -1998,7 +1998,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
1998
1998
  </section>
1999
1999
  ${this._renderAttachmentDock()} ${this._renderStarRating()}
2000
2000
  ${this._renderToolsRow()}
2001
- `}};customElements.define(`jant-compose-editor`,vk);var yk=`.tiptap-slash-menu, .tiptap-link-input`,bk=class extends _{static properties={labels:{type:Object},_open:{state:!0},_title:{state:!0},_showTitle:{state:!0},_replyContext:{state:!0},_replyExpanded:{state:!0}};_editor=null;_content=null;_selection=null;_fileInput=null;#e=new Set;createRenderRoot(){return this}constructor(){super(),this.labels={},this._open=!1,this._title=``,this._showTitle=!1,this._replyContext=null,this._replyExpanded=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:fullscreen-open`,this._onOpen),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`keydown`,this._onDocumentKeydown,!0)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`jant:fullscreen-open`,this._onOpen),document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`keydown`,this._onDocumentKeydown,!0),this._fileInput?.remove(),this._destroyEditor()}_onSlashImage=()=>{!this._open||!this._editor||this._triggerImagePicker()};_triggerImagePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`image/*`,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>{let e=this._fileInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._fileInput&&(this._fileInput.value=``)}),document.body.appendChild(this._fileInput)),this._fileInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=gw(t,e).finally(()=>{this.#e.delete(n)});return this.#e.add(n),n}_onOpen=e=>{this._content=e.detail.json,this._selection=e.detail.selection??null,this._title=e.detail.title,e.detail.labels&&(this.labels=e.detail.labels),this._showTitle=e.detail.showTitle||e.detail.title.trim().length>0,this._replyContext=e.detail.replyContext??null,this._replyExpanded=e.detail.replyContext?.expanded??!1,this._open=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-fullscreen-dialog`);e&&!e.open&&e.showModal(),this._initEditor()})};_initEditor(){let e=this.querySelector(`.compose-fullscreen .compose-tiptap-body`);if(!e||this._editor)return;this._editor=JT({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._content,toolbarMode:`compose`,onUpdate:e=>{this._content=e},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`),uploadInlineImage:e=>this._uploadAndInsertImage(e)}});let t=this._selection;if(t){let e=this._editor.state.doc.content.size,n=Math.max(1,Math.min(t.from,e)),r=Math.max(n,Math.min(t.to,e));this._selection={from:n,to:r},this._editor.chain().focus().setTextSelection({from:n,to:r}).run();return}this._editor.commands.focus()}_destroyEditor(){this.#e.clear(),this._editor?.destroy(),this._editor=null}_onDialogCancel=e=>{e.preventDefault(),this._close()};_onDocumentKeydown=e=>{!this._open||e.key!==`Escape`||e.isComposing||e.keyCode===229||this._hasActiveEscapeOverlay()||(e.preventDefault(),e.stopPropagation(),this._close())};_hasActiveEscapeOverlay(){let e=this.querySelector(`.compose-fullscreen-dialog[open]`);return e?Array.from(e.querySelectorAll(yk)).some(e=>getComputedStyle(e).display!==`none`):!1}_finishClose(){let e=this._editor?.getJSON()??this._content,t=this._editor?{from:this._editor.state.selection.from,to:this._editor.state.selection.to}:this._selection;this._destroyEditor(),this.querySelector(`.compose-fullscreen-dialog`)?.close(),this._open=!1,this._replyContext=null,document.dispatchEvent(new CustomEvent(`jant:fullscreen-close`,{bubbles:!0,detail:{json:e,title:this._title,showTitle:this._showTitle||this._title.trim().length>0,selection:t,replyExpanded:this._replyExpanded}}))}_close(){this._open&&this._finishClose()}_revealTitle(){this._showTitle=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-fullscreen-title`)?.focus()})}_renderTitleField(e){let t=T({"compose-fullscreen-title":!0,"compose-fullscreen-title-reply":e===`reply`}),n=T({"compose-fullscreen-title-placeholder":!0,"compose-fullscreen-title-placeholder-reply":e===`reply`});return this._showTitle?u`
2001
+ `}};customElements.define(`jant-compose-editor`,Dk);var Ok=`.tiptap-slash-menu, .tiptap-link-input`,kk=class extends _{static properties={labels:{type:Object},_open:{state:!0},_title:{state:!0},_showTitle:{state:!0},_replyContext:{state:!0},_replyExpanded:{state:!0}};_editor=null;_content=null;_selection=null;_fileInput=null;#e=new Set;createRenderRoot(){return this}constructor(){super(),this.labels={},this._open=!1,this._title=``,this._showTitle=!1,this._replyContext=null,this._replyExpanded=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`jant:fullscreen-open`,this._onOpen),document.addEventListener(`jant:slash-image`,this._onSlashImage),document.addEventListener(`keydown`,this._onDocumentKeydown,!0)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`jant:fullscreen-open`,this._onOpen),document.removeEventListener(`jant:slash-image`,this._onSlashImage),document.removeEventListener(`keydown`,this._onDocumentKeydown,!0),this._fileInput?.remove(),this._destroyEditor()}_onSlashImage=()=>{!this._open||!this._editor||this._triggerImagePicker()};_triggerImagePicker(){this._fileInput||(this._fileInput=document.createElement(`input`),this._fileInput.type=`file`,this._fileInput.accept=`image/*`,this._fileInput.style.display=`none`,this._fileInput.addEventListener(`change`,()=>{let e=this._fileInput?.files?.[0];e&&this._editor&&this._uploadAndInsertImage(e),this._fileInput&&(this._fileInput.value=``)}),document.body.appendChild(this._fileInput)),this._fileInput.click()}_uploadAndInsertImage(e){let t=this._editor;if(!t)return Promise.resolve();let n=_w(t,e).finally(()=>{this.#e.delete(n)});return this.#e.add(n),n}_onOpen=e=>{this._content=e.detail.json,this._selection=e.detail.selection??null,this._title=e.detail.title,e.detail.labels&&(this.labels=e.detail.labels),this._showTitle=e.detail.showTitle||e.detail.title.trim().length>0,this._replyContext=e.detail.replyContext??null,this._replyExpanded=e.detail.replyContext?.expanded??!1,this._open=!0,this.updateComplete.then(()=>{let e=this.querySelector(`.compose-fullscreen-dialog`);e&&!e.open&&e.showModal(),this._initEditor()})};_initEditor(){let e=this.querySelector(`.compose-fullscreen .compose-tiptap-body`);if(!e||this._editor)return;this._editor=rE({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._content,toolbarMode:`compose`,onUpdate:e=>{this._content=e},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`),uploadInlineImage:e=>this._uploadAndInsertImage(e)}});let t=this._selection;if(t){let e=this._editor.state.doc.content.size,n=Math.max(1,Math.min(t.from,e)),r=Math.max(n,Math.min(t.to,e));this._selection={from:n,to:r},this._editor.chain().focus().setTextSelection({from:n,to:r}).run();return}this._editor.commands.focus()}_destroyEditor(){this.#e.clear(),this._editor?.destroy(),this._editor=null}_onDialogCancel=e=>{e.preventDefault(),this._close()};_onDocumentKeydown=e=>{!this._open||e.key!==`Escape`||e.isComposing||e.keyCode===229||this._hasActiveEscapeOverlay()||(e.preventDefault(),e.stopPropagation(),this._close())};_hasActiveEscapeOverlay(){let e=this.querySelector(`.compose-fullscreen-dialog[open]`);return e?Array.from(e.querySelectorAll(Ok)).some(e=>getComputedStyle(e).display!==`none`):!1}_finishClose(){let e=this._editor?.getJSON()??this._content,t=this._editor?{from:this._editor.state.selection.from,to:this._editor.state.selection.to}:this._selection;this._destroyEditor(),this.querySelector(`.compose-fullscreen-dialog`)?.close(),this._open=!1,this._replyContext=null,document.dispatchEvent(new CustomEvent(`jant:fullscreen-close`,{bubbles:!0,detail:{json:e,title:this._title,showTitle:this._showTitle||this._title.trim().length>0,selection:t,replyExpanded:this._replyExpanded}}))}_close(){this._open&&this._finishClose()}_revealTitle(){this._showTitle=!0,this.updateComplete.then(()=>{this.querySelector(`.compose-fullscreen-title`)?.focus()})}_renderTitleField(e){let t=T({"compose-fullscreen-title":!0,"compose-fullscreen-title-reply":e===`reply`}),n=T({"compose-fullscreen-title-placeholder":!0,"compose-fullscreen-title-placeholder-reply":e===`reply`});return this._showTitle?u`
2002
2002
  <div class="compose-fullscreen-title-shell">
2003
2003
  <input
2004
2004
  type="text"
@@ -2098,7 +2098,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
2098
2098
  </div>
2099
2099
  </div>
2100
2100
  </dialog>
2101
- `}};customElements.define(`jant-compose-fullscreen`,bk);function U(e){if(!e)throw Error(`Assertion failed.`)}var xk=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},Sk=e=>e&&e[e.length-1],Ck=e=>e>=0&&e<2**32,W=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},wk=e=>{let t=W(e);return t&1?t+1>>1:-(t>>1)},Tk=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),Ek=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Dk=new TextDecoder,Ok=new TextEncoder,kk=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),Ak={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},jk=kk(Ak),Mk={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Nk=kk(Mk),Pk={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Fk=kk(Pk),Ik=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,Lk=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),Rk=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},zk=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Bk=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),Vk=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},Hk=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},Uk=(e,t,n)=>{let r=Hk(e,n(t),n);e.splice(r+1,0,t)},Wk=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},Gk=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},Kk=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},qk=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},Jk=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},Yk=e=>{throw Error(`Unexpected value: ${e}`)},Xk=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},Zk=(e,t,n)=>Xk(e,t,n)<<8>>8,Qk=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},$k=(e,t,n,r)=>{n=tA(n,-8388608,8388607),n<0&&(n=n+16777216&16777215),Qk(e,t,n,r)},eA=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return(){return e.return()},throw(t){return e.throw(t)},[Symbol.asyncIterator](){return this}}),tA=(e,t,n)=>Math.max(t,Math.min(n,e)),nA=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},rA=(e,t)=>Math.round(e/t)*t,iA=(e,t)=>Math.floor(e/t)*t,aA=e=>{let t=0;for(;e;)t++,e>>=1;return t},oA=/^[a-z]{3}$/,sA=e=>oA.test(e),cA=1e6*(1+2**-52),lA=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{numerator:n*a,denominator:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{numerator:n*a,denominator:o}},uA=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},dA=null,fA=()=>dA===null?dA=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):dA,pA=null,mA=()=>pA===null?pA=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):pA,hA=null,gA=()=>hA===null?hA=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):hA,_A=null,vA=()=>{if(_A!==null)return _A;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?_A=Number(e[1]):null},yA=(e,t)=>e===-1?t:e,bA=(e,t,n,r)=>e<=r&&n<=t,xA=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},SA=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},CA=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},wA=e=>typeof e==`number`&&!Number.isNaN(e),TA=e=>{U(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},EA=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},DA=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},OA=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},kA=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(t instanceof Uint8Array)&&!(t instanceof DA)&&!(t instanceof OA))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.`)}},AA={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},jA=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},MA=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},NA=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],PA=[-1,1,2,3,4,5,6,8],FA=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new MA(e),n=t.readBits(5);n===31&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;r===15?i=t.readBits(24):r<NA.length&&(i=NA[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=PA[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},IA=e=>{let t=NA.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=PA.indexOf(e.numberOfChannels);if(r===-1)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let i=13;e.objectType>=32&&(i+=6),t===15&&(i+=24);let a=Math.ceil(i/8),o=new Uint8Array(a),s=new MA(o);return e.objectType<32?s.writeBits(5,e.objectType):(s.writeBits(5,31),s.writeBits(6,e.objectType-32)),s.writeBits(4,t),t===15&&s.writeBits(24,n),s.writeBits(4,r),o},LA=[`avc`,`hevc`,`vp9`,`av1`,`vp8`],RA=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],zA=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`],BA=[...zA,...RA],VA=[`webvtt`],HA=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],UA=[{maxPictureSize:36864,maxBitrate:128e3,tier:`L`,level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:`L`,level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:`L`,level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:`L`,level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:`L`,level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:`L`,level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:`H`,level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:`L`,level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:`H`,level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:`L`,level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:`H`,level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:`L`,level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:`H`,level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:`L`,level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:`H`,level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:`L`,level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:`L`,level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:`H`,level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:`L`,level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:186}],WA=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],GA=[{maxPictureSize:147456,maxBitrate:15e5,tier:`M`,level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:`M`,level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:`M`,level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:`M`,level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:`M`,level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:`H`,level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:`M`,level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:`H`,level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:`M`,level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:`H`,level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:`M`,level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:`H`,level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:`M`,level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:`H`,level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:`M`,level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:`M`,level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:`M`,level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:`H`,level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:`M`,level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:`M`,level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:19}],KA=`.01.01.01.01.00`,qA=`.0.110.01.01.01.0`,JA=(e,t,n,r)=>{if(e===`avc`){let e=Math.ceil(t/16)*Math.ceil(n/16),i=HA.find(t=>e<=t.maxMacroblocks&&r<=t.maxBitrate)??Sk(HA),a=i?i.level:0;return`avc1.${`64`.padStart(2,`0`)}00${a.toString(16).padStart(2,`0`)}`}else if(e===`hevc`){let e=t*n,i=UA.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??Sk(UA);return`hev1.1.6.${i.tier}${i.level}.B0`}else if(e===`vp8`)return`vp8`;else if(e===`vp9`){let e=t*n;return`vp09.00.${(WA.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??Sk(WA)).level.toString().padStart(2,`0`)}.08`}else if(e===`av1`){let e=t*n,i=GA.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??Sk(GA);return`av01.0.${i.level.toString().padStart(2,`0`)}${i.tier}.08`}throw TypeError(`Unhandled codec '${e}'.`)},YA=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=r.slice(-1)===`H`?1:0,s=Number(t[3])===8?0:1,c=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1,u=t[5]?Number(t[5][1]):1,d=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(s<<6)+0+(c<<4)+(l<<3)+(u<<2)+d,0]},XA=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s}=e;if(t===`avc`){if(U(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${zk(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${zk(n.subarray(1,4))}`}else if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Bk(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=Ek(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Bk(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}else if(t===`vp8`)return`vp8`;else if(t===`vp9`){if(!o){let t=e.width*e.height,n=Sk(WA).level;for(let e of WA)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(KA)&&(u=u.slice(0,-15)),u}else if(t===`av1`){if(!s){let t=e.width*e.height,n=Sk(WA).level;for(let e of WA)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?Ak[r.primaries]:1,u=r?.transfer?Mk[r.transfer]:1,d=r?.matrix?Pk[r.matrix]:1,f=r?.fullRange?1:0,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(qA)&&(p=p.slice(0,-17)),p}throw TypeError(`Unhandled codec '${t}'.`)},ZA=(e,t,n)=>{if(e===`aac`)return t>=2&&n<=24e3?`mp4a.40.29`:n<=24e3?`mp4a.40.5`:`mp4a.40.2`;if(e===`mp3`)return`mp3`;if(e===`opus`)return`opus`;if(e===`vorbis`)return`vorbis`;if(e===`flac`)return`flac`;if(e===`ac3`)return`ac-3`;if(e===`eac3`)return`ec-3`;if(RA.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},QA=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?FA(n).objectType:r.objectType,`mp4a.40.${e}`}}else if(t===`mp3`)return`mp3`;else if(t===`opus`)return`opus`;else if(t===`vorbis`)return`vorbis`;else if(t===`flac`)return`flac`;else if(t===`ac3`)return`ac-3`;else if(t===`eac3`)return`ec-3`;else if(t&&RA.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},$A=48e3,ej=/^pcm-([usf])(\d+)+(be)?$/,tj=e=>{if(U(RA.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=ej.exec(e);U(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?2**7:0}},nj=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:e.startsWith(`mp4a.40`)||e===`mp4a.67`?`aac`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`?`mp3`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:ej.test(e)?e:e===`webvtt`?`webvtt`:null,rj=e=>e===`avc`?{avc:{format:`avc`}}:e===`hevc`?{hevc:{format:`hevc`}}:{},ij=e=>e===`aac`?{aac:{format:`aac`}}:e===`opus`?{opus:{format:`opus`}}:{},aj=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`],oj=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,sj=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,cj=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,lj=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,uj=e=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!aj.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.description!==void 0&&!Lk(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(Ak);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(Mk);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(Pk);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!oj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!sj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!cj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)&&!lj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)},dj=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`],fj=e=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!dj.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!Lk(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!RA.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${RA.join(`, `)}).`)},pj=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},mj=[44100,48e3,32e3],hj=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],gj=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,_j=(e,t)=>e===3?t===3?21:36:t===3?13:21,vj=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=hj[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=mj[d]>>o+s,x=gj(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},yj=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},bj=[48e3,44100,32e3],xj=[24e3,22050,16e3],Sj;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(Sj||={});var Cj;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(Cj||={});var wj=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Tj=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=Xk(r,n,!1):(U(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},Ej=(e,t)=>t.description?Tj(e,(Tk(t.description)[4]&3)+1):wj(e),Dj=e=>e&31,Oj=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},kj=new Uint8Array([0,0,0,1]),Aj=e=>{let t=e.reduce((e,t)=>e+kj.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(kj,r),r+=kj.byteLength,n.set(t,r),r+=t.byteLength;return n},jj=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:Qk(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1);break}i+=t,r.set(n,i),i+=n.byteLength}return r},Mj=(e,t)=>t.description?jj(e,(Tk(t.description)[4]&3)+1):Aj(e),Nj=e=>{try{let t=[],n=[],r=[];for(let i of wj(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Dj(a[0]);o===Sj.SPS?t.push(a):o===Sj.PPS?n.push(a):o===Sj.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Lj(i);U(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return console.error(`Error building AVC Decoder Configuration Record:`,e),null}},Pj=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if(e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144){U(e.chromaFormat!==null),U(e.bitDepthLumaMinus8!==null),U(e.bitDepthChromaMinus8!==null),U(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},Fj=e=>{try{let t=Ek(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return console.error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Ij={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Lj=e=>{try{let t=new MA(Oj(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();W(t);let a=1,o=0,s=0,c=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=W(t),a===3&&(c=t.readBits(1)),o=W(t),s=W(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(a===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=wk(t);i=(r+e+256)%256}r=i===0?r:i}}}W(t);let l=W(t);if(l===0)W(t);else if(l===1){t.skipBits(1),wk(t),wk(t);let e=W(t);for(let n=0;n<e;n++)wk(t)}W(t),t.skipBits(1);let u=W(t),d=W(t),f=16*(u+1),p=16*(d+1),m=f,h=p,g=t.readBits(1);if(g||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=W(t),n=W(t),r=W(t),i=W(t),o,s;if((c===0?a:0)===0)o=1,s=2-g;else{let e=a===3?1:2,t=a===1?2:1;o=e,s=t*(2-g)}m-=o*(e+n),h-=s*(r+i)}let _=2,v=2,y=2,b=0,x={num:1,den:1},S=null,C=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)x={num:t.readBits(16),den:t.readBits(16)};else{let t=Ij[e];t&&(x=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),b=t.readBits(1),t.readBits(1)&&(_=t.readBits(8),v=t.readBits(8),y=t.readBits(8))),t.readBits(1)&&(W(t),W(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&Rj(t);let n=t.readBits(1);n&&Rj(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),W(t),W(t),W(t),W(t),S=W(t),C=W(t))}if(S===null){U(C===null);let e=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&e)S=0,C=0;else{let e=u+1,t=d+1,n=(2-g)*t,r=HA.find(e=>e.level>=i)??Sk(HA),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return U(C!==null),{profileIdc:n,constraintFlags:r,levelIdc:i,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:h,pixelAspectRatio:x,colourPrimaries:_,matrixCoefficients:y,transferCharacteristics:v,fullRangeFlag:b,numReorderFrames:S,maxDecFrameBuffering:C}}catch(e){return console.error(`Error parsing AVC SPS:`,e),null}},Rj=e=>{let t=W(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)W(e),W(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},zj=(e,t)=>t.description?Tj(e,(Tk(t.description)[21]&3)+1):wj(e),Bj=e=>e>>1&63,Vj=e=>{try{let t=new MA(Oj(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=Uj(t,n);W(t);let u=W(t),d=0;u===3&&(d=t.readBits(1));let f=W(t),p=W(t),m=f,h=p;if(t.readBits(1)){let e=W(t),n=W(t),r=W(t),i=W(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=W(t),_=W(t);W(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)W(t),y=W(t),W(t);if(W(t),W(t),W(t),W(t),W(t),W(t),t.readBits(1)&&t.readBits(1)&&Wj(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),W(t),W(t),t.skipBits(1)),Gj(t,W(t)),t.readBits(1)){let e=W(t);for(let n=0;n<e;n++)W(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,ee=0,te={num:1,den:1};if(t.readBits(1)){let e=qj(t,n);te=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,ee=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:te,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:ee}}catch(e){return console.error(`Error parsing HEVC SPS:`,e),null}},Hj=e=>{try{let t=[],n=[],r=[],i=[];for(let a of wj(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Bj(o[0]);s===Cj.VPS_NUT?t.push(o):s===Cj.SPS_NUT?n.push(o):s===Cj.PPS_NUT?r.push(o):(s===Cj.PREFIX_SEI_NUT||s===Cj.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Vj(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new MA(Oj(e));t.skipBits(16),W(t),W(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),W(t),W(t),wk(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&W(t),wk(t),wk(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:Cj.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Cj.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Cj.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Bj(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return console.error(`Error building HEVC Decoder Configuration Record:`,e),null}},Uj=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},Wj=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))W(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&wk(e);for(let t=0;t<n;t++)wk(e)}},Gj=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=Kj(e,r,t,n)},Kj=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(W(e)+1):t-1,e.readBits(1),W(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=W(e),n=W(e);for(let n=0;n<t;n++)W(e),e.readBits(1);for(let t=0;t<n;t++)W(e),e.readBits(1);i=t+n}return i},qj=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=Ij[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(W(e),W(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(W(e),W(e),W(e),W(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&W(e),e.readBits(1)&&Jj(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=W(e),W(e),W(e),W(e),W(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},Jj=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?W(e):o=e.readBits(1)===1;let s=1;o||(s=W(e)+1),r&&Yj(e,s,a),i&&Yj(e,s,a)}},Yj=(e,t,n)=>{for(let r=0;r<t;r++)W(e),W(e),n&&(W(e),W(e)),e.readBits(1)},Xj=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},Zj=e=>{let t=new MA(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7)if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1;else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=Sk(WA).level;for(let e of WA)if(u<=e.maxPictureSize){d=e.level;break}return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:a===2?1:a===1?6:2,transferCharacteristics:a===2?1:a===1?6:2,matrixCoefficients:a===7?0:a===2?1:a===1?6:2}},Qj=function*(e){let t=new MA(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(r&127)<<n*7,!(r&128))break;if(n===7&&r&128)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);U(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},$j=e=>{for(let{type:t,data:n}of Qj(e)){if(t!==1)continue;let e=new MA(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(r===0&&(a=n),n>7){let t=e.readBits(1);r===0&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=1,_=1,v=0;return h||(r===0?(g=1,_=1):r===1?(g=0,_=0):m===12&&(g=e.readBits(1),g&&(_=e.readBits(1))),g&&_&&(v=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:g,chromaSubsamplingY:_,chromaSamplePosition:v}}return null},eM=e=>{let t=Ek(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},tM=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],nM=e=>({durationInSamples:tM[e[0]>>3]}),rM=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new MA(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},iM=(e,t,n)=>{switch(e){case`avc`:for(let e of Ej(n,t)){let t=n[e.offset],r=Dj(t);if(r>=Sj.NON_IDR_SLICE&&r<=Sj.SLICE_DPC)return`delta`;if(r===Sj.IDR)return`key`;if(r===Sj.SEI&&(!gA()||vA()>=144)){let t=Oj(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new MA(t);e.pos=8*r;let n=W(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of zj(n,t)){let t=Bj(n[e.offset]);if(t<Cj.BLA_W_LP)return`delta`;if(t<=Cj.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new MA(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of Qj(n))if(t===1){let t=new MA(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new MA(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}default:Yk(e),U(!1)}},aM;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(aM||={});var oM=(e,t)=>{let n=Ek(e),r=0,i=n.getUint32(r,!0);r+=4;let a=Dk.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=Dk.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:{let e=SA(c),n=Ek(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=Dk.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:u,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}break}}},sM=[2,1,2,3,3,4,4,5],cM=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new MA(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},lM=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],uM=1536;new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var dM=[1,2,3,6],fM=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new MA(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=dM[o],d;return d=i<3?bj[i]/1e3:xj[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},pM=e=>{if(e.length<2)return null;let t=new MA(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},mM=e=>{let t=e.substreams[0];return U(t),t.fscod<3?bj[t.fscod]:t.fscod2!==null&&t.fscod2<3?xj[t.fscod2]:null},hM=e=>{let t=e.substreams[0];U(t);let n=sM[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},gM=class{constructor(e){this.input=e}},_M=[],vM=[],yM=[],bM=[],xM=new Uint8Array,SM=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===xM&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===xM}get microsecondTimestamp(){return Math.trunc(cA*this.timestamp)}get microsecondDuration(){return Math.trunc(cA*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`Your browser does not support EncodedAudioChunk.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},CM=e=>{let t=8191,n=e,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},wM=e=>{let t=0,n=0,r=~e;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+5;let i=(1<<n|(r&15)<<n-4|1<<n-5)-33;return t===0?i:-i},TM=e=>{let t=4095,n=2048,r=0,i=11,a=0,o=e;for(o<0&&(o=-o,r=128),o>t&&(o=t);(o&n)!==n&&i>=5;)n>>=1,i--;return a=o>>(i===4?1:i-4)&15,(r|i-4<<4|a)^85},EM=e=>{let t=0,n=0,r=e^85;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+4;let i=0;return i=n===4?r<<1|1:1<<n|(r&15)<<n-4|1<<n-5,t===0?i:-i};CA();var DM=-1/0,OM=-1/0,kM=null;typeof FinalizationRegistry<`u`&&(kM=new FinalizationRegistry(e=>{let t=Date.now();e.type===`video`?(t-DM>=1e3&&(console.error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`),DM=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-OM>=1e3&&(console.error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`),OM=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var AM=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],jM=new Set(AM),MM=class e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(cA*this.timestamp)}get microsecondDuration(){return Math.trunc(cA*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!jM.has(n.format))throw TypeError(`init.format must be one of: `+AM.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&EA(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this._data=Tk(t).slice(),this._layout=n.layout??RM(n.format,n.codedWidth,n.codedHeight),this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new NM(n.colorSpace),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&EA(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6,this.colorSpace=new NM(t.colorSpace)}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*cA),duration:Math.trunc((n.duration??0)*cA)||void 0}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=new OffscreenCanvas(r,i),o=a.getContext(`2d`,{alpha:mA(),willReadFrequently:!0});U(o),o.drawImage(t,0,0),this._data=a,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:r,height:i},this.squarePixelWidth=r,this.squarePixelHeight=i,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new NM({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else throw TypeError(`Invalid data type: Must be a BufferSource or CanvasImageSource.`);this.pixelAspectRatio=TA({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),kM?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return U(this._data!==null),PM(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(U(this._layout),new e(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||=(kM?.unregister(this),PM(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(LM(e),this._closed)throw Error(`VideoSample is closed.`);if(this.format===null)throw Error(`Cannot get allocation size when format is null. Sorry!`);if(U(this._data!==null),!PM(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return PM(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!Lk(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(LM(t),this._closed)throw Error(`VideoSample is closed.`);if(this.format===null)throw Error(`Cannot copy video sample data when format is null. Sorry!`);if(U(this._data!==null),!PM(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),r=await n.copyTo(e,t);return n.close(),r}if(PM(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return U(this._layout),Tk(e).set(this._data),this._layout;{let t=this._data.getContext(`2d`);U(t);let n=t.getImageData(0,0,this.codedWidth,this.codedHeight);return Tk(e).set(n.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);return U(this._data!==null),PM(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._rotateSourceRegion(l,u,d,f,this.rotation));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);t.crop!==void 0&&IM(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];t.crop&&FM(t.crop,a,o);let s,c,l,u,{sx:d,sy:f,sWidth:p,sHeight:m}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,i);if(t.fit===`fill`)s=0,c=0,l=n,u=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[a,o],d=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);l=e*d,u=i*d,s=(n-l)/2,c=(r-u)/2}e.save();let h=i%180==0?1:l/u;e.translate(n/2,r/2),e.rotate(i*Math.PI/180),e.scale(1/h,h),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,p,m,s,c,l,u),e.restore()}_rotateSourceRegion(e,t,n,r,i){return i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(U(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}[Symbol.dispose](){this.close()}},NM=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(Ak);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(Mk);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(Pk);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw TypeError(`init.colorSpace.fullRange, when provided, must be a boolean.`)}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},PM=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,FM=(e,t,n)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,n),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,n-e.top),U(e.width>=0),U(e.height>=0)},IM=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},LM=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},RM=(e,t,n)=>{let r=zM(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},zM=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Yk(e),U(!1)}},BM=new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]),VM=class e{get microsecondTimestamp(){return Math.trunc(cA*this.timestamp)}get microsecondDuration(){return Math.trunc(cA*this.duration)}constructor(e){if(this._closed=!1,KM(e)){if(e.format===null)throw TypeError(`AudioData with null format is not supported.`);this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!=`object`)throw TypeError(`Invalid AudioDataInit: must be an object.`);if(!BM.has(e.format))throw TypeError(`Invalid AudioDataInit: invalid format.`);if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError(`Invalid AudioDataInit: sampleRate must be > 0.`);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw TypeError(`Invalid AudioDataInit: numberOfChannels must be an integer > 0.`);if(!Number.isFinite(e?.timestamp))throw TypeError(`init.timestamp must be a number.`);let t=e.data.byteLength/(HM(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw TypeError(`Invalid AudioDataInit: data size is not a multiple of frame size.`);this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError(`Invalid AudioDataInit: data is not a BufferSource.`);let r=this.numberOfFrames*this.numberOfChannels*HM(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}kM?.register(this,{type:`audio`,data:this._data},this)}allocationSize(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(e.format!==void 0&&!BM.has(e.format))throw TypeError(`Invalid format.`);if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError(`frameOffset out of range`);let r=e.frameCount===void 0?this.numberOfFrames-n:e.frameCount;if(r>this.numberOfFrames-n)throw RangeError(`frameCount out of range`);let i=HM(t),a=UM(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&e.planeIndex!==0)throw RangeError(`planeIndex out of range`);return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!Lk(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(t.format!==void 0&&!BM.has(t.format))throw TypeError(`Invalid format.`);if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let{planeIndex:n,format:r,frameCount:i,frameOffset:a}=t,o=this.format,s=r??this.format;if(!s)throw Error(`Destination format not determined`);let c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw RangeError(`frameOffset out of range`);let d=i===void 0?c-u:i;if(d>c-u)throw RangeError(`frameCount out of range`);let f=HM(s),p=UM(s);if(p&&n>=l||!p&&n!==0)throw RangeError(`planeIndex out of range`);let m=(p?d:d*l)*f;if(e.byteLength<m)throw RangeError(`Destination buffer is too small`);let h=Ek(e),g=GM(s);if(KM(this._data))fA()&&l>2&&s!==o?qM(this._data,h,o,s,l,n,u,d):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:d,format:s});else{let e=this._data,t=Ek(e),r=WM(o),i=HM(o),a=UM(o);for(let e=0;e<d;e++)if(p){let o=e*f,s;s=a?(n*c+(e+u))*i:((e+u)*l+n)*i,g(h,o,r(t,s))}else for(let n=0;n<l;n++){let o=(e*l+n)*f,s;s=a?(n*c+(e+u))*i:((e+u)*l+n)*i,g(h,o,r(t,s))}}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(KM(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}else return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||=(kM?.unregister(this),KM(this._data)?this._data.close():this._data=new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);if(KM(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(UM(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error(`AudioSample is closed.`);let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:`f32-planar`})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:`f32-planar`}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a;for(;c>0;){let a=Math.min(o,c),l=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*a,(e+1)*a),e,s);yield new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:l}),s+=a,c-=a}}static fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a,l=[];for(;c>0;){let a=Math.min(o,c),u=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(u.subarray(e*a,(e+1)*a),e,s);let d=new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:u});l.push(d),s+=a,c-=a}return l}},HM=e=>{switch(e){case`u8`:case`u8-planar`:return 1;case`s16`:case`s16-planar`:return 2;case`s32`:case`s32-planar`:return 4;case`f32`:case`f32-planar`:return 4;default:throw Error(`Unknown AudioSampleFormat`)}},UM=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},WM=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t)=>(e.getUint8(t)-128)/128;case`s16`:case`s16-planar`:return(e,t)=>e.getInt16(t,!0)/32768;case`s32`:case`s32-planar`:return(e,t)=>e.getInt32(t,!0)/2147483648;case`f32`:case`f32-planar`:return(e,t)=>e.getFloat32(t,!0)}},GM=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,tA((n+1)*127.5,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,tA(Math.round(n*32767),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,tA(Math.round(n*2147483647),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},KM=e=>typeof AudioData<`u`&&e instanceof AudioData,qM=(e,t,n,r,i,a,o,s)=>{let c=WM(n),l=GM(r),u=HM(n),d=HM(r),f=UM(n);if(UM(r))if(f){let r=new ArrayBuffer(s*u),i=Ek(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,e*d,c(i,n))}}else{let r=new ArrayBuffer(s*i*u),f=Ek(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;l(t,e*d,c(f,n))}}else if(f){let r=s*u,a=new ArrayBuffer(r),f=Ek(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,(e*i+r)*d,c(f,n))}}}else{let r=new ArrayBuffer(s*i*u),a=Ek(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;l(t,r*d,c(a,o))}}},JM=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`)},YM=e=>{if(!wA(e))throw TypeError(`timestamp must be a number.`)},XM=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,ZM=class{constructor(e){if(!(e instanceof cN))throw TypeError(`track must be an InputTrack.`);this._track=e}getFirstPacket(e={}){if(JM(e),this._track.input._disposed)throw new _F;return XM(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){JM(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}getPacket(e,t={}){if(YM(e),JM(t),this._track.input._disposed)throw new _F;return XM(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof SM))throw TypeError(`packet must be an EncodedPacket.`);if(JM(t),this._track.input._disposed)throw new _F;return XM(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(YM(e),JM(t),this._track.input._disposed)throw new _F;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(U(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof SM))throw TypeError(`packet must be an EncodedPacket.`);if(JM(t),this._track.input._disposed)throw new _F;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(U(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof SM))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof SM))throw TypeError(`endPacket must be an EncodedPacket.`);if(JM(n),this._track.input._disposed)throw new _F;let r=[],{promise:i,resolve:a}=Wk(),{promise:o,resolve:s}=Wk(),c=!1,l=!1,u=null,d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>f()){({promise:o,resolve:s}=Wk()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=Wk(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{u||(u=e,a())});let p=this._track;return{async next(){for(;;)if(p.input._disposed)throw new _F;else if(l)return{value:void 0,done:!0};else if(u)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},QM=class{constructor(e,t){this.onSample=e,this.onError=t}},$M=class{mediaSamplesInRange(e=0,t=1/0){YM(e),YM(t);let n=[],r=!1,i=null,{promise:a,resolve:o}=Wk(),{promise:s,resolve:c}=Wk(),l=!1,u=!1,d=!1,f=null;(async()=>{let p=await this._createDecoder(s=>{if(c(),s.timestamp>=t&&(u=!0),u){s.close();return}i&&(s.timestamp>e?(n.push(i),r=!0):i.close()),s.timestamp>=e&&(n.push(s),r=!0),i=r?null:s,n.length>0&&(o(),{promise:a,resolve:o}=Wk())},e=>{f||(f=e,o())}),m=this._createPacketSink(),h=await m.getKeyPacket(e,{verifyKeyPackets:!0})??await m.getFirstKeyPacket({verifyKeyPackets:!0}),g=h,_=m.packets(h??void 0,void 0);for(await _.next();g&&!u&&!this._track.input._disposed;){let e=eN(n.length);if(n.length+p.getDecodeQueueSize()>e){({promise:s,resolve:c}=Wk()),await s;continue}p.decode(g);let t=await _.next();if(t.done)break;g=t.value}await _.return(),!d&&!this._track.input._disposed&&await p.flush(),p.close(),!r&&i&&n.push(i),l=!0,o()})().catch(e=>{f||(f=e,o())});let p=this._track,m=()=>{i?.close();for(let e of n)e.close()};return{async next(){for(;;)if(p.input._disposed)throw m(),new _F;else if(d)return{value:void 0,done:!0};else if(f)throw m(),f;else if(n.length>0){let e=n.shift();return c(),{value:e,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}},async return(){return d=!0,u=!0,c(),o(),m(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){Jk(e);let t=qk(e),n=[],r=[],{promise:i,resolve:a}=Wk(),{promise:o,resolve:s}=Wk(),c=!1,l=!1,u=null,d=e=>{r.push(e),a(),{promise:i,resolve:a}=Wk()};(async()=>{let e=await this._createDecoder(e=>{if(s(),l){e.close();return}let t=0;for(;n.length>0&&e.timestamp-n[0]>-1e-10;)t++,n.shift();if(t>0)for(let n=0;n<t;n++)d(n<t-1?e.clone():e);else e.close()},e=>{u||(u=e,a())}),i=this._createPacketSink(),f=null,p=null,m=-1,h=async()=>{U(p);let t=p;for(e.decode(t);t.sequenceNumber<m;){let n=eN(r.length);for(;r.length+e.getDecodeQueueSize()>n&&!l;)({promise:o,resolve:s}=Wk()),await o;if(l)break;let a=await i.getNextPacket(t);U(a),e.decode(a),t=a}m=-1},g=async()=>{await e.flush();for(let e=0;e<n.length;e++)d(null);n.length=0};for await(let e of t){if(YM(e),l||this._track.input._disposed)break;let t=await i.getPacket(e),r=t&&await i.getKeyPacket(e,{verifyKeyPackets:!0});if(!r){m!==-1&&(await h(),await g()),d(null),f=null;continue}f&&(r.sequenceNumber!==p.sequenceNumber||t.timestamp<f.timestamp)&&(await h(),await g()),n.push(t.timestamp),m=Math.max(t.sequenceNumber,m),f=t,p=r}!l&&!this._track.input._disposed&&(m!==-1&&await h(),await g()),e.close(),c=!0,a()})().catch(e=>{u||(u=e,a())});let f=this._track,p=()=>{for(let e of r)e?.close()};return{async next(){for(;;)if(f.input._disposed)throw p(),new _F;else if(l)return{value:void 0,done:!0};else if(u)throw p(),u;else if(r.length>0){let e=r.shift();return U(e!==void 0),s(),{value:e,done:!1}}else if(!c)await i;else return{value:void 0,done:!0}},async return(){return l=!0,s(),a(),p(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},eN=e=>e===0?40:8,tN=class extends QM{constructor(e,t,n,r,i,a){super(e,t),this.codec=n,this.decoderConfig=r,this.rotation=i,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new uA,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let o=_M.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof MM))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();U(t!==void 0),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(n===`avc`&&this.decoderConfig.description&&gA()){let e=Fj(Tk(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=Lj(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`})}}let t=Error(`Decoding error`).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(U(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(U(this.decoder),fA()||Uk(this.inputTimestamps,e.timestamp,e=>e),gA()&&this.currentPacketIndex===0&&this.codec===`avc`){let t=[];for(let n of Ej(e.data,this.decoderConfig)){let r=Dj(e.data[n.offset]);r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}e=new SM(Mj(t,this.decoderConfig),e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new nN}catch(t){console.error(`Due to an error, only color data will be decoded.`,t),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let t=this.colorQueue.shift();U(t!==void 0),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();U(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=Error(`Decoding error`).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=iM(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of zj(e,this.decoderConfig)){let n=Bj(e[t.offset]);if(n===Cj.RASL_N||n===Cj.RASL_R)return!0}return!1}sampleHandler(e){if(fA()){if(this.sampleQueue.length>0&&e.timestamp>=Sk(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Uk(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();U(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){let t=new MM(e);this.sampleHandler(t);return}U(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new MM(new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}));this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(U(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),fA()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(U(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},nN=class{constructor(){typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement(`canvas`);let e=this.canvas.getContext(`webgl2`,{premultipliedAlpha:!1});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_colorTexture`),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_alphaTexture`),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2101
+ `}};customElements.define(`jant-compose-fullscreen`,kk);function U(e){if(!e)throw Error(`Assertion failed.`)}var Ak=e=>{let t=(e%360+360)%360;if(t===0||t===90||t===180||t===270)return t;throw Error(`Invalid rotation ${e}.`)},jk=e=>e&&e[e.length-1],Mk=e=>e>=0&&e<2**32,W=e=>{let t=0;for(;e.readBits(1)===0&&t<32;)t++;if(t>=32)throw Error(`Invalid exponential-Golomb code.`);return(1<<t)-1+e.readBits(t)},Nk=e=>{let t=W(e);return t&1?t+1>>1:-(t>>1)},Pk=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),Fk=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Ik=new TextDecoder,Lk=new TextEncoder,Rk=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),zk={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Bk=Rk(zk),Vk={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Hk=Rk(Vk),Uk={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},Wk=Rk(Uk),Gk=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&e.fullRange!==void 0,Kk=e=>e instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),qk=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let n=!1;e=()=>{n||=(t(),this.pending--,!0)}}),n=this.currentPromise;return this.currentPromise=t,this.pending++,await n,e}},Jk=e=>[...e].map(e=>e.toString(16).padStart(2,`0`)).join(``),Yk=e=>(e=e>>1&1431655765|(e&1431655765)<<1,e=e>>2&858993459|(e&858993459)<<2,e=e>>4&252645135|(e&252645135)<<4,e=e>>8&16711935|(e&16711935)<<8,e=e>>16&65535|(e&65535)<<16,e>>>0),Xk=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+i>>1,s=n(e[o]);s===t?(a=o,i=o-1):s<t?r=o+1:i=o-1}return a},Zk=(e,t,n)=>{let r=0,i=e.length-1,a=-1;for(;r<=i;){let o=r+(i-r+1)/2|0;n(e[o])<=t?(a=o,r=o+1):i=o-1}return a},Qk=(e,t,n)=>{let r=Zk(e,n(t),n);e.splice(r+1,0,t)},$k=()=>{let e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}},eA=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return e[n]},tA=(e,t)=>{for(let n=e.length-1;n>=0;n--)if(t(e[n]))return n;return-1},nA=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},rA=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError(`Argument must be an iterable or async iterable.`)},iA=e=>{throw Error(`Unexpected value: ${e}`)},aA=(e,t,n)=>{let r=e.getUint8(t),i=e.getUint8(t+1),a=e.getUint8(t+2);return n?r|i<<8|a<<16:r<<16|i<<8|a},oA=(e,t,n)=>aA(e,t,n)<<8>>8,sA=(e,t,n,r)=>{n>>>=0,n&=16777215,r?(e.setUint8(t,n&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n>>>16&255)):(e.setUint8(t,n>>>16&255),e.setUint8(t+1,n>>>8&255),e.setUint8(t+2,n&255))},cA=(e,t,n,r)=>{n=uA(n,-8388608,8388607),n<0&&(n=n+16777216&16777215),sA(e,t,n,r)},lA=(e,t)=>({async next(){let n=await e.next();return n.done?{value:void 0,done:!0}:{value:t(n.value),done:!1}},return(){return e.return()},throw(t){return e.throw(t)},[Symbol.asyncIterator](){return this}}),uA=(e,t,n)=>Math.max(t,Math.min(n,e)),dA=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*2**-52?t:e},fA=(e,t)=>Math.round(e/t)*t,pA=(e,t)=>Math.floor(e/t)*t,mA=e=>{let t=0;for(;e;)t++,e>>=1;return t},hA=/^[a-z]{3}$/,gA=e=>hA.test(e),_A=1e6*(1+2**-52),vA=(e,t)=>{let n=e<0?-1:1;e=Math.abs(e);let r=0,i=1,a=1,o=0,s=e;for(;;){let e=Math.floor(s),c=e*a+r,l=e*o+i;if(l>t)return{numerator:n*a,denominator:o};if(r=a,i=o,a=c,o=l,s=1/(s-e),!isFinite(s))break}return{numerator:n*a,denominator:o}},yA=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},bA=null,xA=()=>bA===null?bA=!!(typeof navigator<`u`&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))):bA,SA=null,CA=()=>SA===null?SA=typeof navigator<`u`&&navigator.userAgent?.includes(`Firefox`):SA,wA=null,TA=()=>wA===null?wA=!!(typeof navigator<`u`&&(navigator.vendor?.includes(`Google Inc`)||/Chrome/.test(navigator.userAgent))):wA,EA=null,DA=()=>{if(EA!==null)return EA;if(typeof navigator>`u`)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?EA=Number(e[1]):null},OA=(e,t)=>e===-1?t:e,kA=(e,t,n,r)=>e<=r&&n<=t,AA=function*(e){for(let t in e){let n=e[t];n!==void 0&&(yield{key:t,value:n})}},jA=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},MA=()=>{Symbol.dispose??=Symbol(`Symbol.dispose`)},NA=e=>typeof e==`number`&&!Number.isNaN(e),PA=e=>{U(e.den!==0);let t=Math.abs(e.num),n=Math.abs(e.den);for(;n!==0;){let e=t%n;t=n,n=e}let r=t||1;return{num:e.num/r,den:e.den/r}},FA=(e,t)=>{if(typeof e!=`object`||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},IA=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(typeof t!=`string`)throw TypeError(`mimeType must be a string.`)}},LA=class{constructor(e,t,n,r){if(this.data=e,this.mimeType=t,this.name=n,this.description=r,!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==void 0&&typeof t!=`string`)throw TypeError(`mimeType, when provided, must be a string.`);if(n!==void 0&&typeof n!=`string`)throw TypeError(`name, when provided, must be a string.`);if(r!==void 0&&typeof r!=`string`)throw TypeError(`description, when provided, must be a string.`)}},RA=e=>{if(!e||typeof e!=`object`)throw TypeError(`tags must be an object.`);if(e.title!==void 0&&typeof e.title!=`string`)throw TypeError(`tags.title, when provided, must be a string.`);if(e.description!==void 0&&typeof e.description!=`string`)throw TypeError(`tags.description, when provided, must be a string.`);if(e.artist!==void 0&&typeof e.artist!=`string`)throw TypeError(`tags.artist, when provided, must be a string.`);if(e.album!==void 0&&typeof e.album!=`string`)throw TypeError(`tags.album, when provided, must be a string.`);if(e.albumArtist!==void 0&&typeof e.albumArtist!=`string`)throw TypeError(`tags.albumArtist, when provided, must be a string.`);if(e.trackNumber!==void 0&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError(`tags.trackNumber, when provided, must be a positive integer.`);if(e.tracksTotal!==void 0&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError(`tags.tracksTotal, when provided, must be a positive integer.`);if(e.discNumber!==void 0&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError(`tags.discNumber, when provided, must be a positive integer.`);if(e.discsTotal!==void 0&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError(`tags.discsTotal, when provided, must be a positive integer.`);if(e.genre!==void 0&&typeof e.genre!=`string`)throw TypeError(`tags.genre, when provided, must be a string.`);if(e.date!==void 0&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError(`tags.date, when provided, must be a valid Date.`);if(e.lyrics!==void 0&&typeof e.lyrics!=`string`)throw TypeError(`tags.lyrics, when provided, must be a string.`);if(e.images!==void 0){if(!Array.isArray(e.images))throw TypeError(`tags.images, when provided, must be an array.`);for(let t of e.images){if(!t||typeof t!=`object`)throw TypeError(`Each image in tags.images must be an object.`);if(!(t.data instanceof Uint8Array))throw TypeError(`Each image.data must be a Uint8Array.`);if(typeof t.mimeType!=`string`)throw TypeError(`Each image.mimeType must be a string.`);if(![`coverFront`,`coverBack`,`unknown`].includes(t.kind))throw TypeError(`Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.`)}}if(e.comment!==void 0&&typeof e.comment!=`string`)throw TypeError(`tags.comment, when provided, must be a string.`);if(e.raw!==void 0){if(!e.raw||typeof e.raw!=`object`)throw TypeError(`tags.raw, when provided, must be an object.`);for(let t of Object.values(e.raw))if(t!==null&&typeof t!=`string`&&!(t instanceof Uint8Array)&&!(t instanceof IA)&&!(t instanceof LA))throw TypeError(`Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.`)}},zA={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},BA=e=>{if(!e||typeof e!=`object`)throw TypeError(`disposition must be an object.`);if(e.default!==void 0&&typeof e.default!=`boolean`)throw TypeError(`disposition.default must be a boolean.`);if(e.forced!==void 0&&typeof e.forced!=`boolean`)throw TypeError(`disposition.forced must be a boolean.`);if(e.original!==void 0&&typeof e.original!=`boolean`)throw TypeError(`disposition.original must be a boolean.`);if(e.commentary!==void 0&&typeof e.commentary!=`boolean`)throw TypeError(`disposition.commentary must be a boolean.`);if(e.hearingImpaired!==void 0&&typeof e.hearingImpaired!=`boolean`)throw TypeError(`disposition.hearingImpaired must be a boolean.`);if(e.visuallyImpaired!==void 0&&typeof e.visuallyImpaired!=`boolean`)throw TypeError(`disposition.visuallyImpaired must be a boolean.`)},VA=class e{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,n=7-(this.pos&7),r=(t&1<<n)>>n;return this.pos++,r}readBits(e){if(e===1)return this.readBit();let t=0;for(let n=0;n<e;n++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let n=this.pos+e;for(let e=this.pos;e<n;e++){let r=Math.floor(e/8),i=this.bytes[r],a=7-(e&7);i&=~(1<<a),i|=(t&1<<n-e-1)>>n-e-1<<a,this.bytes[r]=i}this.pos=n}readAlignedByte(){if(this.pos%8!=0)throw Error(`Bitstream is not byte-aligned.`);let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return this.bytes.length*8-this.pos}clone(){let t=new e(this.bytes);return t.pos=this.pos,t}},HA=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],UA=[-1,1,2,3,4,5,6,8],WA=e=>{if(!e||e.byteLength<2)throw TypeError(`AAC description must be at least 2 bytes long.`);let t=new VA(e),n=t.readBits(5);n===31&&(n=32+t.readBits(6));let r=t.readBits(4),i=null;r===15?i=t.readBits(24):r<HA.length&&(i=HA[r]);let a=t.readBits(4),o=null;return a>=1&&a<=7&&(o=UA[a]),{objectType:n,frequencyIndex:r,sampleRate:i,channelConfiguration:a,numberOfChannels:o}},GA=e=>{let t=HA.indexOf(e.sampleRate),n=null;t===-1&&(t=15,n=e.sampleRate);let r=UA.indexOf(e.numberOfChannels);if(r===-1)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let i=13;e.objectType>=32&&(i+=6),t===15&&(i+=24);let a=Math.ceil(i/8),o=new Uint8Array(a),s=new VA(o);return e.objectType<32?s.writeBits(5,e.objectType):(s.writeBits(5,31),s.writeBits(6,e.objectType-32)),s.writeBits(4,t),t===15&&s.writeBits(24,n),s.writeBits(4,r),o},KA=[`avc`,`hevc`,`vp9`,`av1`,`vp8`],qA=[`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,`pcm-u8`,`pcm-s8`,`ulaw`,`alaw`],JA=[`aac`,`opus`,`mp3`,`vorbis`,`flac`,`ac3`,`eac3`],YA=[...JA,...qA],XA=[`webvtt`],ZA=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],QA=[{maxPictureSize:36864,maxBitrate:128e3,tier:`L`,level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:`L`,level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:`L`,level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:`L`,level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:`L`,level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:`L`,level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:`H`,level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:`L`,level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:`H`,level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:`L`,level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:`H`,level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:`L`,level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:`H`,level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:`L`,level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:`H`,level:156},{maxPictureSize:35651584,maxBitrate:6e7,tier:`L`,level:180},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:180},{maxPictureSize:35651584,maxBitrate:12e7,tier:`L`,level:183},{maxPictureSize:35651584,maxBitrate:48e7,tier:`H`,level:183},{maxPictureSize:35651584,maxBitrate:24e7,tier:`L`,level:186},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:186}],$A=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],ej=[{maxPictureSize:147456,maxBitrate:15e5,tier:`M`,level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:`M`,level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:`M`,level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:`M`,level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:`M`,level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:`H`,level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:`M`,level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:`H`,level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:`M`,level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:`H`,level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:`M`,level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:`H`,level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:`M`,level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:`H`,level:14},{maxPictureSize:35651584,maxBitrate:6e7,tier:`M`,level:15},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:15},{maxPictureSize:35651584,maxBitrate:6e7,tier:`M`,level:16},{maxPictureSize:35651584,maxBitrate:24e7,tier:`H`,level:16},{maxPictureSize:35651584,maxBitrate:1e8,tier:`M`,level:17},{maxPictureSize:35651584,maxBitrate:48e7,tier:`H`,level:17},{maxPictureSize:35651584,maxBitrate:16e7,tier:`M`,level:18},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:18},{maxPictureSize:35651584,maxBitrate:16e7,tier:`M`,level:19},{maxPictureSize:35651584,maxBitrate:8e8,tier:`H`,level:19}],tj=`.01.01.01.01.00`,nj=`.0.110.01.01.01.0`,rj=(e,t,n,r)=>{if(e===`avc`){let e=Math.ceil(t/16)*Math.ceil(n/16),i=ZA.find(t=>e<=t.maxMacroblocks&&r<=t.maxBitrate)??jk(ZA),a=i?i.level:0;return`avc1.${`64`.padStart(2,`0`)}00${a.toString(16).padStart(2,`0`)}`}else if(e===`hevc`){let e=t*n,i=QA.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??jk(QA);return`hev1.1.6.${i.tier}${i.level}.B0`}else if(e===`vp8`)return`vp8`;else if(e===`vp9`){let e=t*n;return`vp09.00.${($A.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??jk($A)).level.toString().padStart(2,`0`)}.08`}else if(e===`av1`){let e=t*n,i=ej.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??jk(ej);return`av01.0.${i.level.toString().padStart(2,`0`)}${i.tier}.08`}throw TypeError(`Unhandled codec '${e}'.`)},ij=e=>{let t=e.split(`.`),n=Number(t[1]),r=t[2],i=Number(r.slice(0,-1)),a=(n<<5)+i,o=r.slice(-1)===`H`?1:0,s=Number(t[3])===8?0:1,c=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1,u=t[5]?Number(t[5][1]):1,d=t[5]?Number(t[5][2]):0;return[129,a,(o<<7)+(s<<6)+0+(c<<4)+(l<<3)+(u<<2)+d,0]},aj=e=>{let{codec:t,codecDescription:n,colorSpace:r,avcCodecInfo:i,hevcCodecInfo:a,vp9CodecInfo:o,av1CodecInfo:s}=e;if(t===`avc`){if(U(e.avcType!==null),i){let t=new Uint8Array([i.avcProfileIndication,i.profileCompatibility,i.avcLevelIndication]);return`avc${e.avcType}.${Jk(t)}`}if(!n||n.byteLength<4)throw TypeError(`AVC decoder description is not provided or is not at least 4 bytes long.`);return`avc${e.avcType}.${Jk(n.subarray(1,4))}`}else if(t===`hevc`){let e,t,r,i,o,s;if(a)e=a.generalProfileSpace,t=a.generalProfileIdc,r=Yk(a.generalProfileCompatibilityFlags),i=a.generalTierFlag,o=a.generalLevelIdc,s=[...a.generalConstraintIndicatorFlags];else{if(!n||n.byteLength<23)throw TypeError(`HEVC decoder description is not provided or is not at least 23 bytes long.`);let a=Fk(n),c=a.getUint8(1);e=c>>6&3,t=c&31,r=Yk(a.getUint32(2)),i=c>>5&1,o=a.getUint8(12),s=[];for(let e=0;e<6;e++)s.push(a.getUint8(6+e))}let c=`hev1.`;for(c+=[``,`A`,`B`,`C`][e]+t,c+=`.`,c+=r.toString(16).toUpperCase(),c+=`.`,c+=i===0?`L`:`H`,c+=o;s.length>0&&s[s.length-1]===0;)s.pop();return s.length>0&&(c+=`.`,c+=s.map(e=>e.toString(16).toUpperCase()).join(`.`)),c}else if(t===`vp8`)return`vp8`;else if(t===`vp9`){if(!o){let t=e.width*e.height,n=jk($A).level;for(let e of $A)if(t<=e.maxPictureSize){n=e.level;break}return`vp09.00.${n.toString().padStart(2,`0`)}.08`}let t=o.profile.toString().padStart(2,`0`),n=o.level.toString().padStart(2,`0`),r=o.bitDepth.toString().padStart(2,`0`),i=o.chromaSubsampling.toString().padStart(2,`0`),a=o.colourPrimaries.toString().padStart(2,`0`),s=o.transferCharacteristics.toString().padStart(2,`0`),c=o.matrixCoefficients.toString().padStart(2,`0`),l=o.videoFullRangeFlag.toString().padStart(2,`0`),u=`vp09.${t}.${n}.${r}.${i}`;return u+=`.${a}.${s}.${c}.${l}`,u.endsWith(tj)&&(u=u.slice(0,-15)),u}else if(t===`av1`){if(!s){let t=e.width*e.height,n=jk($A).level;for(let e of $A)if(t<=e.maxPictureSize){n=e.level;break}return`av01.0.${n.toString().padStart(2,`0`)}M.08`}let t=s.profile,n=s.level.toString().padStart(2,`0`),i=s.tier?`H`:`M`,a=s.bitDepth.toString().padStart(2,`0`),o=s.monochrome?`1`:`0`,c=100*s.chromaSubsamplingX+10*s.chromaSubsamplingY+1*(s.chromaSubsamplingX&&s.chromaSubsamplingY?s.chromaSamplePosition:0),l=r?.primaries?zk[r.primaries]:1,u=r?.transfer?Vk[r.transfer]:1,d=r?.matrix?Uk[r.matrix]:1,f=r?.fullRange?1:0,p=`av01.${t}.${n}${i}.${a}`;return p+=`.${o}.${c.toString().padStart(3,`0`)}`,p+=`.${l.toString().padStart(2,`0`)}`,p+=`.${u.toString().padStart(2,`0`)}`,p+=`.${d.toString().padStart(2,`0`)}`,p+=`.${f}`,p.endsWith(nj)&&(p=p.slice(0,-17)),p}throw TypeError(`Unhandled codec '${t}'.`)},oj=(e,t,n)=>{if(e===`aac`)return t>=2&&n<=24e3?`mp4a.40.29`:n<=24e3?`mp4a.40.5`:`mp4a.40.2`;if(e===`mp3`)return`mp3`;if(e===`opus`)return`opus`;if(e===`vorbis`)return`vorbis`;if(e===`flac`)return`flac`;if(e===`ac3`)return`ac-3`;if(e===`eac3`)return`ec-3`;if(qA.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},sj=e=>{let{codec:t,codecDescription:n,aacCodecInfo:r}=e;if(t===`aac`){if(!r)throw TypeError(`AAC codec info must be provided.`);if(r.isMpeg2)return`mp4a.67`;{let e;return e=r.objectType===null?WA(n).objectType:r.objectType,`mp4a.40.${e}`}}else if(t===`mp3`)return`mp3`;else if(t===`opus`)return`opus`;else if(t===`vorbis`)return`vorbis`;else if(t===`flac`)return`flac`;else if(t===`ac3`)return`ac-3`;else if(t===`eac3`)return`ec-3`;else if(t&&qA.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},cj=48e3,lj=/^pcm-([usf])(\d+)+(be)?$/,uj=e=>{if(U(qA.includes(e)),e===`ulaw`)return{dataType:`ulaw`,sampleSize:1,littleEndian:!0,silentValue:255};if(e===`alaw`)return{dataType:`alaw`,sampleSize:1,littleEndian:!0,silentValue:213};let t=lj.exec(e);U(t);let n;n=t[1]===`u`?`unsigned`:t[1]===`s`?`signed`:`float`;let r=Number(t[2])/8,i=t[3]!==`be`;return{dataType:n,sampleSize:r,littleEndian:i,silentValue:e===`pcm-u8`?2**7:0}},dj=e=>e.startsWith(`avc1`)||e.startsWith(`avc3`)?`avc`:e.startsWith(`hev1`)||e.startsWith(`hvc1`)?`hevc`:e===`vp8`?`vp8`:e.startsWith(`vp09`)?`vp9`:e.startsWith(`av01`)?`av1`:e.startsWith(`mp4a.40`)||e===`mp4a.67`?`aac`:e===`mp3`||e===`mp4a.69`||e===`mp4a.6B`||e===`mp4a.6b`?`mp3`:e===`opus`?`opus`:e===`vorbis`?`vorbis`:e===`flac`?`flac`:e===`ac-3`||e===`ac3`?`ac3`:e===`ec-3`||e===`eac3`?`eac3`:e===`ulaw`?`ulaw`:e===`alaw`?`alaw`:lj.test(e)?e:e===`webvtt`?`webvtt`:null,fj=e=>e===`avc`?{avc:{format:`avc`}}:e===`hevc`?{hevc:{format:`hevc`}}:{},pj=e=>e===`aac`?{aac:{format:`aac`}}:e===`opus`?{opus:{format:`opus`}}:{},mj=[`avc1`,`avc3`,`hev1`,`hvc1`,`vp8`,`vp09`,`av01`],hj=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,gj=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,_j=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,vj=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,yj=e=>{if(!e)throw TypeError(`Video chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Video chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Video chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Video chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Video chunk metadata decoder configuration must specify a codec string.`);if(!mj.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).`);if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError(`Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).`);if(e.decoderConfig.description!==void 0&&!Kk(e.decoderConfig.description))throw TypeError(`Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.colorSpace!==void 0){let{colorSpace:t}=e.decoderConfig;if(typeof t!=`object`)throw TypeError(`Video chunk metadata decoder configuration colorSpace, when provided, must be an object.`);let n=Object.keys(zk);if(t.primaries!=null&&!n.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${n.join(`, `)}.`);let r=Object.keys(Vk);if(t.transfer!=null&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(`, `)}.`);let i=Object.keys(Uk);if(t.matrix!=null&&!i.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${i.join(`, `)}.`);if(t.fullRange!=null&&typeof t.fullRange!=`boolean`)throw TypeError(`Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.`)}if(e.decoderConfig.codec.startsWith(`avc1`)||e.decoderConfig.codec.startsWith(`avc3`)){if(!hj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.`)}else if(e.decoderConfig.codec.startsWith(`hev1`)||e.decoderConfig.codec.startsWith(`hvc1`)){if(!gj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.`)}else if(e.decoderConfig.codec.startsWith(`vp8`)){if(e.decoderConfig.codec!==`vp8`)throw TypeError(`Video chunk metadata decoder configuration codec string for VP8 must be "vp8".`)}else if(e.decoderConfig.codec.startsWith(`vp09`)){if(!_j.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.`)}else if(e.decoderConfig.codec.startsWith(`av01`)&&!vj.test(e.decoderConfig.codec))throw TypeError(`Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.`)},bj=[`mp4a`,`mp3`,`opus`,`vorbis`,`flac`,`ulaw`,`alaw`,`pcm`,`ac-3`,`ec-3`],xj=e=>{if(!e)throw TypeError(`Audio chunk metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Audio chunk metadata must be an object.`);if(!e.decoderConfig)throw TypeError(`Audio chunk metadata must include a decoder configuration.`);if(typeof e.decoderConfig!=`object`)throw TypeError(`Audio chunk metadata decoder configuration must be an object.`);if(typeof e.decoderConfig.codec!=`string`)throw TypeError(`Audio chunk metadata decoder configuration must specify a codec string.`);if(!bj.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError(`Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.`);if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).`);if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError(`Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).`);if(e.decoderConfig.description!==void 0&&!Kk(e.decoderConfig.description))throw TypeError(`Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.`);if(e.decoderConfig.codec.startsWith(`mp4a`)&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`){if(![`mp4a.40.2`,`mp4a.40.02`,`mp4a.40.5`,`mp4a.40.05`,`mp4a.40.29`,`mp4a.67`].includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`mp3`)||e.decoderConfig.codec.startsWith(`mp4a`)){if(e.decoderConfig.codec!==`mp3`&&e.decoderConfig.codec!==`mp4a.69`&&e.decoderConfig.codec!==`mp4a.6B`&&e.decoderConfig.codec!==`mp4a.6b`)throw TypeError(`Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".`)}else if(e.decoderConfig.codec.startsWith(`opus`)){if(e.decoderConfig.codec!==`opus`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Opus must be "opus".`);if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError(`Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.`)}else if(e.decoderConfig.codec.startsWith(`vorbis`)){if(e.decoderConfig.codec!==`vorbis`)throw TypeError(`Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".`);if(!e.decoderConfig.description)throw TypeError(`Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`flac`)){if(e.decoderConfig.codec!==`flac`)throw TypeError(`Audio chunk metadata decoder configuration codec string for FLAC must be "flac".`);if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError(`Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.`)}else if(e.decoderConfig.codec.startsWith(`ac-3`)||e.decoderConfig.codec.startsWith(`ac3`)){if(e.decoderConfig.codec!==`ac-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".`)}else if(e.decoderConfig.codec.startsWith(`ec-3`)||e.decoderConfig.codec.startsWith(`eac3`)){if(e.decoderConfig.codec!==`ec-3`)throw TypeError(`Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".`)}else if((e.decoderConfig.codec.startsWith(`pcm`)||e.decoderConfig.codec.startsWith(`ulaw`)||e.decoderConfig.codec.startsWith(`alaw`))&&!qA.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${qA.join(`, `)}).`)},Sj=e=>{if(!e)throw TypeError(`Subtitle metadata must be provided.`);if(typeof e!=`object`)throw TypeError(`Subtitle metadata must be an object.`);if(!e.config)throw TypeError(`Subtitle metadata must include a config object.`);if(typeof e.config!=`object`)throw TypeError(`Subtitle metadata config must be an object.`);if(typeof e.config.description!=`string`)throw TypeError(`Subtitle metadata config description must be a string.`)},Cj=[44100,48e3,32e3],wj=[-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,32,40,48,56,64,80,96,112,128,160,192,224,256,320,-1,-1,32,48,56,64,80,96,112,128,160,192,224,256,320,384,-1,-1,32,64,96,128,160,192,224,256,288,320,352,384,416,448,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,8,16,24,32,40,48,56,64,80,96,112,128,144,160,-1,-1,32,48,56,64,80,96,112,128,144,160,176,192,224,256,-1],Tj=(e,t,n,r,i)=>t===0?0:t===1?Math.floor(144*n/(r<<e))+i:t===2?Math.floor(144*n/r)+i:(Math.floor(12*n/r)+i)*4,Ej=(e,t)=>e===3?t===3?21:36:t===3?13:21,Dj=(e,t)=>{let n=e>>>24,r=e>>>16&255,i=e>>>8&255,a=e&255;if(n!==255&&r!==255&&i!==255&&a!==255)return{header:null,bytesAdvanced:4};if(n!==255||(r&224)!=224)return{header:null,bytesAdvanced:1};let o=0,s=0;r&16?o=r&8?0:1:(o=1,s=1);let c=r>>3&3,l=r>>1&3,u=i>>4&15,d=(i>>2&3)%3,f=i>>1&1,p=a>>6&3,m=a>>4&3,h=a>>3&1,g=a>>2&1,_=a&3,v=wj[o*16*4+l*16+u];if(v===-1)return{header:null,bytesAdvanced:1};let y=v*1e3,b=Cj[d]>>o+s,x=Tj(o,l,y,b,f);if(t!==null&&t<x)return{header:null,bytesAdvanced:1};let S;return S=c===3?l===3?384:1152:l===3?384:l===2?1152:576,{header:{totalSize:x,mpegVersionId:c,layer:l,bitrate:y,frequencyIndex:d,sampleRate:b,channel:p,modeExtension:m,copyright:h,original:g,emphasis:_,audioSamplesInFrame:S},bytesAdvanced:1}},Oj=e=>{let t=2130706432,n=0;for(;t!==0;)n>>=1,n|=e&t,t>>=8;return n},kj=[48e3,44100,32e3],Aj=[24e3,22050,16e3],jj;(function(e){e[e.NON_IDR_SLICE=1]=`NON_IDR_SLICE`,e[e.SLICE_DPA=2]=`SLICE_DPA`,e[e.SLICE_DPB=3]=`SLICE_DPB`,e[e.SLICE_DPC=4]=`SLICE_DPC`,e[e.IDR=5]=`IDR`,e[e.SEI=6]=`SEI`,e[e.SPS=7]=`SPS`,e[e.PPS=8]=`PPS`,e[e.AUD=9]=`AUD`,e[e.SPS_EXT=13]=`SPS_EXT`})(jj||={});var Mj;(function(e){e[e.RASL_N=8]=`RASL_N`,e[e.RASL_R=9]=`RASL_R`,e[e.BLA_W_LP=16]=`BLA_W_LP`,e[e.RSV_IRAP_VCL23=23]=`RSV_IRAP_VCL23`,e[e.VPS_NUT=32]=`VPS_NUT`,e[e.SPS_NUT=33]=`SPS_NUT`,e[e.PPS_NUT=34]=`PPS_NUT`,e[e.AUD_NUT=35]=`AUD_NUT`,e[e.PREFIX_SEI_NUT=39]=`PREFIX_SEI_NUT`,e[e.SUFFIX_SEI_NUT=40]=`SUFFIX_SEI_NUT`})(Mj||={});var Nj=function*(e){let t=0,n=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(r===-1||r>=e.length-2)break;t=r;let i=0;if(t+3<e.length&&e[t+1]===0&&e[t+2]===0&&e[t+3]===1?i=4:e[t+1]===0&&e[t+2]===1&&(i=3),i===0){t++;continue}n!==-1&&t>n&&(yield{offset:n,length:t-n}),n=t+i,t=n}n!==-1&&n<e.length&&(yield{offset:n,length:e.length-n})},Pj=function*(e,t){let n=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;n+t<=e.length;){let e;t===1?e=r.getUint8(n):t===2?e=r.getUint16(n,!1):t===3?e=aA(r,n,!1):(U(t===4),e=r.getUint32(n,!1)),n+=t,yield{offset:n,length:e},n+=e}},Fj=(e,t)=>t.description?Pj(e,(Pk(t.description)[4]&3)+1):Nj(e),Ij=e=>e&31,Lj=e=>{let t=[],n=e.length;for(let r=0;r<n;r++)r+2<n&&e[r]===0&&e[r+1]===0&&e[r+2]===3?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},Rj=new Uint8Array([0,0,0,1]),zj=e=>{let t=e.reduce((e,t)=>e+Rj.byteLength+t.byteLength,0),n=new Uint8Array(t),r=0;for(let t of e)n.set(Rj,r),r+=Rj.byteLength,n.set(t,r),r+=t.byteLength;return n},Bj=(e,t)=>{let n=e.reduce((e,n)=>e+t+n.byteLength,0),r=new Uint8Array(n),i=0;for(let n of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,n.byteLength);break;case 2:e.setUint16(i,n.byteLength,!1);break;case 3:sA(e,i,n.byteLength,!1);break;case 4:e.setUint32(i,n.byteLength,!1);break}i+=t,r.set(n,i),i+=n.byteLength}return r},Vj=(e,t)=>t.description?Bj(e,(Pk(t.description)[4]&3)+1):zj(e),Hj=e=>{try{let t=[],n=[],r=[];for(let i of Nj(e)){let a=e.subarray(i.offset,i.offset+i.length),o=Ij(a[0]);o===jj.SPS?t.push(a):o===jj.PPS?n.push(a):o===jj.SPS_EXT&&r.push(a)}if(t.length===0||n.length===0)return null;let i=t[0],a=Kj(i);U(a!==null);let o=a.profileIdc===100||a.profileIdc===110||a.profileIdc===122||a.profileIdc===144;return{configurationVersion:1,avcProfileIndication:a.profileIdc,profileCompatibility:a.constraintFlags,avcLevelIndication:a.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:n,chromaFormat:o?a.chromaFormatIdc:null,bitDepthLumaMinus8:o?a.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?a.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return console.error(`Error building AVC Decoder Configuration Record:`,e),null}},Uj=e=>{let t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|e.lengthSizeMinusOne&3),t.push(224|e.sequenceParameterSets.length&31);for(let n of e.sequenceParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}t.push(e.pictureParameterSets.length);for(let n of e.pictureParameterSets){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}if(e.avcProfileIndication===100||e.avcProfileIndication===110||e.avcProfileIndication===122||e.avcProfileIndication===144){U(e.chromaFormat!==null),U(e.bitDepthLumaMinus8!==null),U(e.bitDepthChromaMinus8!==null),U(e.sequenceParameterSetExt!==null),t.push(252|e.chromaFormat&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.sequenceParameterSetExt.length);for(let n of e.sequenceParameterSetExt){let e=n.byteLength;t.push(e>>8),t.push(e&255);for(let r=0;r<e;r++)t.push(n[r])}}return new Uint8Array(t)},Wj=e=>{try{let t=Fk(e),n=0,r=t.getUint8(n++),i=t.getUint8(n++),a=t.getUint8(n++),o=t.getUint8(n++),s=t.getUint8(n++)&3,c=t.getUint8(n++)&31,l=[];for(let r=0;r<c;r++){let r=t.getUint16(n,!1);n+=2,l.push(e.subarray(n,n+r)),n+=r}let u=t.getUint8(n++),d=[];for(let r=0;r<u;r++){let r=t.getUint16(n,!1);n+=2,d.push(e.subarray(n,n+r)),n+=r}let f={configurationVersion:r,avcProfileIndication:i,profileCompatibility:a,avcLevelIndication:o,lengthSizeMinusOne:s,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((i===100||i===110||i===122||i===144)&&n+4<=e.length){let r=t.getUint8(n++)&3,i=t.getUint8(n++)&7,a=t.getUint8(n++)&7,o=t.getUint8(n++);f.chromaFormat=r,f.bitDepthLumaMinus8=i,f.bitDepthChromaMinus8=a;let s=[];for(let r=0;r<o;r++){let r=t.getUint16(n,!1);n+=2,s.push(e.subarray(n,n+r)),n+=r}f.sequenceParameterSetExt=s}return f}catch(e){return console.error(`Error deserializing AVC Decoder Configuration Record:`,e),null}},Gj={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Kj=e=>{try{let t=new VA(Lj(e));if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;let n=t.readAlignedByte(),r=t.readAlignedByte(),i=t.readAlignedByte();W(t);let a=1,o=0,s=0,c=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(a=W(t),a===3&&(c=t.readBits(1)),o=W(t),s=W(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(a===3?12:8);e++)if(t.readBits(1)){let n=e<6?16:64,r=8,i=8;for(let e=0;e<n;e++){if(i!==0){let e=Nk(t);i=(r+e+256)%256}r=i===0?r:i}}}W(t);let l=W(t);if(l===0)W(t);else if(l===1){t.skipBits(1),Nk(t),Nk(t);let e=W(t);for(let n=0;n<e;n++)Nk(t)}W(t),t.skipBits(1);let u=W(t),d=W(t),f=16*(u+1),p=16*(d+1),m=f,h=p,g=t.readBits(1);if(g||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e=W(t),n=W(t),r=W(t),i=W(t),o,s;if((c===0?a:0)===0)o=1,s=2-g;else{let e=a===3?1:2,t=a===1?2:1;o=e,s=t*(2-g)}m-=o*(e+n),h-=s*(r+i)}let _=2,v=2,y=2,b=0,x={num:1,den:1},S=null,C=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(e===255)x={num:t.readBits(16),den:t.readBits(16)};else{let t=Gj[e];t&&(x=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),b=t.readBits(1),t.readBits(1)&&(_=t.readBits(8),v=t.readBits(8),y=t.readBits(8))),t.readBits(1)&&(W(t),W(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&qj(t);let n=t.readBits(1);n&&qj(t),(e||n)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),W(t),W(t),W(t),W(t),S=W(t),C=W(t))}if(S===null){U(C===null);let e=r&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&e)S=0,C=0;else{let e=u+1,t=d+1,n=(2-g)*t,r=ZA.find(e=>e.level>=i)??jk(ZA),a=Math.min(Math.floor(r.maxDpbMbs/(e*n)),16);S=a,C=a}}return U(C!==null),{profileIdc:n,constraintFlags:r,levelIdc:i,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:s,codedWidth:f,codedHeight:p,displayWidth:m,displayHeight:h,pixelAspectRatio:x,colourPrimaries:_,matrixCoefficients:y,transferCharacteristics:v,fullRangeFlag:b,numReorderFrames:S,maxDecFrameBuffering:C}}catch(e){return console.error(`Error parsing AVC SPS:`,e),null}},qj=e=>{let t=W(e);e.skipBits(4),e.skipBits(4);for(let n=0;n<=t;n++)W(e),W(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Jj=(e,t)=>t.description?Pj(e,(Pk(t.description)[21]&3)+1):Nj(e),Yj=e=>e>>1&63,Xj=e=>{try{let t=new VA(Lj(e));t.skipBits(16),t.readBits(4);let n=t.readBits(3),r=t.readBits(1),{general_profile_space:i,general_tier_flag:a,general_profile_idc:o,general_profile_compatibility_flags:s,general_constraint_indicator_flags:c,general_level_idc:l}=Qj(t,n);W(t);let u=W(t),d=0;u===3&&(d=t.readBits(1));let f=W(t),p=W(t),m=f,h=p;if(t.readBits(1)){let e=W(t),n=W(t),r=W(t),i=W(t),a=1,o=1,s=d===0?u:0;s===1?(a=2,o=2):s===2&&(a=2,o=1),m-=(e+n)*a,h-=(r+i)*o}let g=W(t),_=W(t);W(t);let v=t.readBits(1)?0:n,y=0;for(let e=v;e<=n;e++)W(t),y=W(t),W(t);if(W(t),W(t),W(t),W(t),W(t),W(t),t.readBits(1)&&t.readBits(1)&&$j(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),W(t),W(t),t.skipBits(1)),eM(t,W(t)),t.readBits(1)){let e=W(t);for(let n=0;n<e;n++)W(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let b=2,x=2,S=2,C=0,ee=0,te={num:1,den:1};if(t.readBits(1)){let e=nM(t,n);te=e.pixelAspectRatio,b=e.colourPrimaries,x=e.transferCharacteristics,S=e.matrixCoefficients,C=e.fullRangeFlag,ee=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:h,pixelAspectRatio:te,colourPrimaries:b,transferCharacteristics:x,matrixCoefficients:S,fullRangeFlag:C,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:n,spsTemporalIdNestingFlag:r,generalProfileSpace:i,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:_,minSpatialSegmentationIdc:ee}}catch(e){return console.error(`Error parsing HEVC SPS:`,e),null}},Zj=e=>{try{let t=[],n=[],r=[],i=[];for(let a of Nj(e)){let o=e.subarray(a.offset,a.offset+a.length),s=Yj(o[0]);s===Mj.VPS_NUT?t.push(o):s===Mj.SPS_NUT?n.push(o):s===Mj.PPS_NUT?r.push(o):(s===Mj.PREFIX_SEI_NUT||s===Mj.SUFFIX_SEI_NUT)&&i.push(o)}if(n.length===0||r.length===0)return null;let a=Xj(n[0]);if(!a)return null;let o=0;if(r.length>0){let e=r[0],t=new VA(Lj(e));t.skipBits(16),W(t),W(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),W(t),W(t),Nk(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&W(t),Nk(t),Nk(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let n=t.readBits(1),i=t.readBits(1);o=!n&&!i?0:n&&!i?2:!n&&i?3:0}let s=[...t.length?[{arrayCompleteness:1,nalUnitType:Mj.VPS_NUT,nalUnits:t}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Mj.SPS_NUT,nalUnits:n}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Mj.PPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Yj(i[0][0]),nalUnits:i}]:[]];return{configurationVersion:1,generalProfileSpace:a.generalProfileSpace,generalTierFlag:a.generalTierFlag,generalProfileIdc:a.generalProfileIdc,generalProfileCompatibilityFlags:a.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:a.generalConstraintIndicatorFlags,generalLevelIdc:a.generalLevelIdc,minSpatialSegmentationIdc:a.minSpatialSegmentationIdc,parallelismType:o,chromaFormatIdc:a.chromaFormatIdc,bitDepthLumaMinus8:a.bitDepthLumaMinus8,bitDepthChromaMinus8:a.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:a.spsMaxSubLayersMinus1+1,temporalIdNested:a.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:s}}catch(e){return console.error(`Error building HEVC Decoder Configuration Record:`,e),null}},Qj=(e,t)=>{let n=e.readBits(2),r=e.readBits(1),i=e.readBits(5),a=0;for(let t=0;t<32;t++)a=a<<1|e.readBits(1);let o=new Uint8Array(6);for(let t=0;t<6;t++)o[t]=e.readBits(8);let s=e.readBits(8),c=[],l=[];for(let n=0;n<t;n++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let n=t;n<8;n++)e.skipBits(2);for(let n=0;n<t;n++)c[n]&&e.skipBits(88),l[n]&&e.skipBits(8);return{general_profile_space:n,general_tier_flag:r,general_profile_idc:i,general_profile_compatibility_flags:a,general_constraint_indicator_flags:o,general_level_idc:s}},$j=e=>{for(let t=0;t<4;t++)for(let n=0;n<(t===3?2:6);n++)if(!e.readBits(1))W(e);else{let n=Math.min(64,1<<4+(t<<1));t>1&&Nk(e);for(let t=0;t<n;t++)Nk(e)}},eM=(e,t)=>{let n=[];for(let r=0;r<t;r++)n[r]=tM(e,r,t,n)},tM=(e,t,n,r)=>{let i=0,a=0,o=0;if(t!==0&&(a=e.readBits(1)),a){o=t===n?t-(W(e)+1):t-1,e.readBits(1),W(e);let a=r[o]??0;for(let t=0;t<=a;t++)e.readBits(1)||e.readBits(1);i=r[o]}else{let t=W(e),n=W(e);for(let n=0;n<t;n++)W(e),e.readBits(1);for(let t=0;t<n;t++)W(e),e.readBits(1);i=t+n}return i},nM=(e,t)=>{let n=2,r=2,i=2,a=0,o=0,s={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(t===255)s={num:e.readBits(16),den:e.readBits(16)};else{let e=Gj[t];e&&(s=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),a=e.readBits(1),e.readBits(1)&&(n=e.readBits(8),r=e.readBits(8),i=e.readBits(8))),e.readBits(1)&&(W(e),W(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(W(e),W(e),W(e),W(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&W(e),e.readBits(1)&&rM(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),o=W(e),W(e),W(e),W(e),W(e)),{pixelAspectRatio:s,colourPrimaries:n,transferCharacteristics:r,matrixCoefficients:i,fullRangeFlag:a,minSpatialSegmentationIdc:o}},rM=(e,t,n)=>{let r=!1,i=!1,a=!1;t&&(r=e.readBits(1)===1,i=e.readBits(1)===1,(r||i)&&(a=e.readBits(1)===1,a&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),a&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=n;t++){let t=e.readBits(1)===1,n=!0;t||(n=e.readBits(1)===1);let o=!1;n?W(e):o=e.readBits(1)===1;let s=1;o||(s=W(e)+1),r&&iM(e,s,a),i&&iM(e,s,a)}},iM=(e,t,n)=>{for(let r=0;r<t;r++)W(e),W(e),n&&(W(e),W(e)),e.readBits(1)},aM=e=>{let t=[];t.push(e.configurationVersion),t.push((e.generalProfileSpace&3)<<6|(e.generalTierFlag&1)<<5|e.generalProfileIdc&31),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(e.generalProfileCompatibilityFlags&255),t.push(...e.generalConstraintIndicatorFlags),t.push(e.generalLevelIdc&255),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(e.minSpatialSegmentationIdc&255),t.push(252|e.parallelismType&3),t.push(252|e.chromaFormatIdc&3),t.push(248|e.bitDepthLumaMinus8&7),t.push(248|e.bitDepthChromaMinus8&7),t.push(e.avgFrameRate>>8&255),t.push(e.avgFrameRate&255),t.push((e.constantFrameRate&3)<<6|(e.numTemporalLayers&7)<<3|(e.temporalIdNested&1)<<2|e.lengthSizeMinusOne&3),t.push(e.arrays.length&255);for(let n of e.arrays){t.push((n.arrayCompleteness&1)<<7|0|n.nalUnitType&63),t.push(n.nalUnits.length>>8&255),t.push(n.nalUnits.length&255);for(let e of n.nalUnits){t.push(e.length>>8&255),t.push(e.length&255);for(let n=0;n<e.length;n++)t.push(e[n])}}return new Uint8Array(t)},oM=e=>{let t=new VA(e);if(t.readBits(2)!==2)return null;let n=t.readBits(1),r=(t.readBits(1)<<1)+n;if(r===3&&t.skipBits(1),t.readBits(1)===1||t.readBits(1)!==0||(t.skipBits(2),t.readBits(24)!==4817730))return null;let i=8;r>=2&&(i=t.readBits(1)?12:10);let a=t.readBits(3),o=0,s=0;if(a!==7)if(s=t.readBits(1),r===1||r===3){let e=t.readBits(1),n=t.readBits(1);o=!e&&!n?3:e&&!n?2:1,t.skipBits(1)}else o=1;else o=3,s=1;let c=t.readBits(16),l=t.readBits(16),u=(c+1)*(l+1),d=jk($A).level;for(let e of $A)if(u<=e.maxPictureSize){d=e.level;break}return{profile:r,level:d,bitDepth:i,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:a===2?1:a===1?6:2,transferCharacteristics:a===2?1:a===1?6:2,matrixCoefficients:a===7?0:a===2?1:a===1?6:2}},sM=function*(e){let t=new VA(e),n=()=>{let e=0;for(let n=0;n<8;n++){let r=t.readAlignedByte();if(e|=(r&127)<<n*7,!(r&128))break;if(n===7&&r&128)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);let r=t.readBits(4),i=t.readBits(1),a=t.readBits(1);t.skipBits(1),i&&t.skipBits(8);let o;if(a){let e=n();if(e===null)return;o=e}else o=Math.floor(t.getBitsLeft()/8);U(t.pos%8==0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(o*8)}},cM=e=>{for(let{type:t,data:n}of sM(e)){if(t!==1)continue;let e=new VA(n),r=e.readBits(3);e.readBits(1);let i=e.readBits(1),a=0,o=0,s=0;if(i)a=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(s=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let n=e.readBits(5);for(let r=0;r<=n;r++){e.skipBits(12);let n=e.readBits(5);if(r===0&&(a=n),n>7){let t=e.readBits(1);r===0&&(o=t)}if(t&&e.readBits(1)){let t=s+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);let d=l+1;e.skipBits(d);let f=0;if(f=i?0:e.readBits(1),f&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!i){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let n=e.readBits(1),r=0;r=n?2:e.readBits(1),r>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let p=e.readBits(1),m=8;r===2&&p?m=e.readBits(1)?12:10:r<=2&&(m=p?10:8);let h=0;r!==1&&(h=e.readBits(1));let g=1,_=1,v=0;return h||(r===0?(g=1,_=1):r===1?(g=0,_=0):m===12&&(g=e.readBits(1),g&&(_=e.readBits(1))),g&&_&&(v=e.readBits(2))),{profile:r,level:a,tier:o,bitDepth:m,monochrome:h,chromaSubsamplingX:g,chromaSubsamplingY:_,chromaSamplePosition:v}}return null},lM=e=>{let t=Fk(e),n=t.getUint8(9),r=t.getUint16(10,!0),i=t.getUint32(12,!0),a=t.getInt16(16,!0),o=t.getUint8(18),s=null;return o&&(s=e.subarray(19,21+n)),{outputChannelCount:n,preSkip:r,inputSampleRate:i,outputGain:a,channelMappingFamily:o,channelMappingTable:s}},uM=[480,960,1920,2880,480,960,1920,2880,480,960,1920,2880,480,960,480,960,120,240,480,960,120,240,480,960,120,240,480,960,120,240,480,960],dM=e=>({durationInSamples:uM[e[0]>>3]}),fM=e=>{if(e.length<7)throw Error(`Setup header is too short.`);if(e[0]!==5)throw Error(`Wrong packet type in Setup header.`);if(String.fromCharCode(...e.slice(1,7))!==`vorbis`)throw Error(`Invalid packet signature in Setup header.`);let t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e[t-1-r];let r=new VA(n),i=0;for(;r.getBitsLeft()>97;)if(r.readBits(1)===1){i=r.pos;break}if(i===0)throw Error(`Invalid Setup header: framing bit not found.`);let a=0,o=!1,s=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),n=r.readBits(16),i=r.readBits(16);if(t>63||n!==0||i!==0){r.pos=e;break}if(r.skipBits(1),a++,a>64)break;r.clone().readBits(6)+1===a&&(o=!0,s=a)}if(!o)throw Error(`Invalid Setup header: mode header not found.`);if(s>63)throw Error(`Unsupported mode count: ${s}.`);let c=s;r.pos=0,r.skipBits(i);let l=Array(c).fill(0);for(let e=c-1;e>=0;e--)r.skipBits(40),l[e]=r.readBits(1);return{modeBlockflags:l}},pM=(e,t,n)=>{switch(e){case`avc`:for(let e of Fj(n,t)){let t=n[e.offset],r=Ij(t);if(r>=jj.NON_IDR_SLICE&&r<=jj.SLICE_DPC)return`delta`;if(r===jj.IDR)return`key`;if(r===jj.SEI&&(!TA()||DA()>=144)){let t=Lj(n.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let n=t[r++];if(n===void 0||(e+=n,n<255))break}let n=0;for(;;){let e=t[r++];if(e===void 0||(n+=e,e<255))break}if(e===6){let e=new VA(t);e.pos=8*r;let n=W(e),i=e.readBits(1);if(n===0&&i===1)return`key`}r+=n}while(r<t.length-1)}}return`delta`;case`hevc`:for(let e of Jj(n,t)){let t=Yj(n[e.offset]);if(t<Mj.BLA_W_LP)return`delta`;if(t<=Mj.RSV_IRAP_VCL23)return`key`}return`delta`;case`vp8`:return n[0]&1?`delta`:`key`;case`vp9`:{let e=new VA(n);if(e.readBits(2)!==2)return null;let t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:e.readBits(1)===0?`key`:`delta`}case`av1`:{let e=!1;for(let{type:t,data:r}of sM(n))if(t===1){let t=new VA(r);t.skipBits(4),e=!!t.readBits(1)}else if(t===3||t===6||t===7){if(e)return`key`;let t=new VA(r);return t.readBits(1)?null:t.readBits(2)===0?`key`:`delta`}return null}default:iA(e),U(!1)}},mM;(function(e){e[e.STREAMINFO=0]=`STREAMINFO`,e[e.VORBIS_COMMENT=4]=`VORBIS_COMMENT`,e[e.PICTURE=6]=`PICTURE`})(mM||={});var hM=(e,t)=>{let n=Fk(e),r=0,i=n.getUint32(r,!0);r+=4;let a=Ik.decode(e.subarray(r,r+i));r+=i,i>0&&(t.raw??={},t.raw.vendor??=a);let o=n.getUint32(r,!0);r+=4;for(let i=0;i<o;i++){let i=n.getUint32(r,!0);r+=4;let a=Ik.decode(e.subarray(r,r+i));r+=i;let o=a.indexOf(`=`);if(o===-1)continue;let s=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(t.raw??={},t.raw[s]??=c,s){case`TITLE`:t.title??=c;break;case`DESCRIPTION`:t.description??=c;break;case`ARTIST`:t.artist??=c;break;case`ALBUM`:t.album??=c;break;case`ALBUMARTIST`:t.albumArtist??=c;break;case`COMMENT`:t.comment??=c;break;case`LYRICS`:t.lyrics??=c;break;case`TRACKNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.trackNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case`TRACKTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case`DISCNUMBER`:{let e=c.split(`/`),n=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(n)&&n>0&&(t.discNumber??=n),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case`DISCTOTAL`:{let e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case`DATE`:{let e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case`GENRE`:t.genre??=c;break;case`METADATA_BLOCK_PICTURE`:{let e=jA(c),n=Fk(e),r=n.getUint32(0,!1),i=n.getUint32(4,!1),a=String.fromCharCode(...e.subarray(8,8+i)),o=n.getUint32(8+i,!1),s=Ik.decode(e.subarray(12+i,12+i+o)),l=n.getUint32(i+o+28),u=e.subarray(i+o+32,i+o+32+l);t.images??=[],t.images.push({data:u,mimeType:a,kind:r===3?`coverFront`:r===4?`coverBack`:`unknown`,name:void 0,description:s||void 0})}break}}},gM=[2,1,2,3,3,4,4,5],_M=e=>{if(e.length<7||e[0]!==11||e[1]!==119)return null;let t=new VA(e);t.skipBits(16),t.skipBits(16);let n=t.readBits(2);if(n===3)return null;let r=t.readBits(6),i=t.readBits(5);if(i>8)return null;let a=t.readBits(3),o=t.readBits(3);return o&1&&o!==1&&t.skipBits(2),o&4&&t.skipBits(2),o===2&&t.skipBits(2),{fscod:n,bsid:i,bsmod:a,acmod:o,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},vM=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],yM=1536;new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);var bM=[1,2,3,6],xM=e=>{if(e.length<6||e[0]!==11||e[1]!==119)return null;let t=new VA(e);t.skipBits(16);let n=t.readBits(2);if(t.skipBits(3),n!==0&&n!==2)return null;let r=t.readBits(11),i=t.readBits(2),a=0,o;i===3?(a=t.readBits(2),o=3):o=t.readBits(2);let s=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;let u=bM[o],d;return d=i<3?kj[i]/1e3:Aj[a]/1e3,{dataRate:Math.round((r+1)*d/(u*16)),substreams:[{fscod:i,fscod2:a,bsid:l,bsmod:0,acmod:s,lfeon:c,numDepSub:0,chanLoc:0}]}},SM=e=>{if(e.length<2)return null;let t=new VA(e),n=t.readBits(13),r=t.readBits(3),i=[];for(let n=0;n<=r&&!(Math.ceil(t.pos/8)+3>e.length);n++){let e=t.readBits(2),n=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=t.readBits(3),a=t.readBits(3),o=t.readBits(1);t.skipBits(3);let s=t.readBits(4),c=0;s>0?c=t.readBits(9):t.skipBits(1),i.push({fscod:e,fscod2:null,bsid:n,bsmod:r,acmod:a,lfeon:o,numDepSub:s,chanLoc:c})}return i.length===0?null:{dataRate:n,substreams:i}},CM=e=>{let t=e.substreams[0];return U(t),t.fscod<3?kj[t.fscod]:t.fscod2!==null&&t.fscod2<3?Aj[t.fscod2]:null},wM=e=>{let t=e.substreams[0];U(t);let n=gM[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(n+=e[r])}return n},TM=class{constructor(e){this.input=e}},EM=[],DM=[],OM=[],kM=[],AM=new Uint8Array,jM=class e{constructor(e,t,n,r,i=-1,a,o){if(this.data=e,this.type=t,this.timestamp=n,this.duration=r,this.sequenceNumber=i,e===AM&&a===void 0)throw Error(`Internal error: byteLength must be explicitly provided when constructing metadata-only packets.`);if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw TypeError(`data must be a Uint8Array.`);if(t!==`key`&&t!==`delta`)throw TypeError(`type must be either "key" or "delta".`);if(!Number.isFinite(n))throw TypeError(`timestamp must be a number.`);if(!Number.isFinite(r)||r<0)throw TypeError(`duration must be a non-negative number.`);if(!Number.isFinite(i))throw TypeError(`sequenceNumber must be a number.`);if(!Number.isInteger(a)||a<0)throw TypeError(`byteLength must be a non-negative integer.`);if(o!==void 0&&(typeof o!=`object`||!o))throw TypeError(`sideData, when provided, must be an object.`);if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw TypeError(`sideData.alpha, when provided, must be a Uint8Array.`);if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw TypeError(`sideData.alphaByteLength, when provided, must be a non-negative integer.`);this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===AM}get microsecondTimestamp(){return Math.trunc(_A*this.timestamp)}get microsecondDuration(){return Math.trunc(_A*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError(`This packet does not contain alpha side data.`);if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to a video chunk.`);if(typeof EncodedVideoChunk>`u`)throw Error(`Your browser does not support EncodedVideoChunk.`);return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be converted to an audio chunk.`);if(typeof EncodedAudioChunk>`u`)throw Error(`Your browser does not support EncodedAudioChunk.`);return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,n){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw TypeError(`chunk must be an EncodedVideoChunk or EncodedAudioChunk.`);let r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,n)}clone(t){if(t!==void 0&&(typeof t!=`object`||!t))throw TypeError(`options, when provided, must be an object.`);if(t?.data!==void 0&&!(t.data instanceof Uint8Array))throw TypeError(`options.data, when provided, must be a Uint8Array.`);if(t?.type!==void 0&&t.type!==`key`&&t.type!==`delta`)throw TypeError(`options.type, when provided, must be either "key" or "delta".`);if(t?.timestamp!==void 0&&!Number.isFinite(t.timestamp))throw TypeError(`options.timestamp, when provided, must be a number.`);if(t?.duration!==void 0&&!Number.isFinite(t.duration))throw TypeError(`options.duration, when provided, must be a number.`);if(t?.sequenceNumber!==void 0&&!Number.isFinite(t.sequenceNumber))throw TypeError(`options.sequenceNumber, when provided, must be a number.`);if(t?.sideData!==void 0&&(typeof t.sideData!=`object`||t.sideData===null))throw TypeError(`options.sideData, when provided, must be an object.`);return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},MM=e=>{let t=8191,n=e,r=4096,i=0,a=12,o=0;for(n<0&&(n=-n,i=128),n+=33,n>t&&(n=t);(n&r)!==r&&a>=5;)r>>=1,a--;return o=n>>a-4&15,~(i|a-5<<4|o)&255},NM=e=>{let t=0,n=0,r=~e;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+5;let i=(1<<n|(r&15)<<n-4|1<<n-5)-33;return t===0?i:-i},PM=e=>{let t=4095,n=2048,r=0,i=11,a=0,o=e;for(o<0&&(o=-o,r=128),o>t&&(o=t);(o&n)!==n&&i>=5;)n>>=1,i--;return a=o>>(i===4?1:i-4)&15,(r|i-4<<4|a)^85},FM=e=>{let t=0,n=0,r=e^85;r&128&&(r&=-129,t=-1),n=((r&240)>>4)+4;let i=0;return i=n===4?r<<1|1:1<<n|(r&15)<<n-4|1<<n-5,t===0?i:-i};MA();var IM=-1/0,LM=-1/0,RM=null;typeof FinalizationRegistry<`u`&&(RM=new FinalizationRegistry(e=>{let t=Date.now();e.type===`video`?(t-IM>=1e3&&(console.error(`A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them.`),IM=t),typeof VideoFrame<`u`&&e.data instanceof VideoFrame&&e.data.close()):(t-LM>=1e3&&(console.error(`An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them.`),LM=t),typeof AudioData<`u`&&e.data instanceof AudioData&&e.data.close())}));var zM=[`I420`,`I420P10`,`I420P12`,`I420A`,`I420AP10`,`I420AP12`,`I422`,`I422P10`,`I422P12`,`I422A`,`I422AP10`,`I422AP12`,`I444`,`I444P10`,`I444P12`,`I444A`,`I444AP10`,`I444AP12`,`NV12`,`RGBA`,`RGBX`,`BGRA`,`BGRX`],BM=new Set(zM),VM=class e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(_A*this.timestamp)}get microsecondDuration(){return Math.trunc(_A*this.duration)}get hasAlpha(){return this.format&&this.format.includes(`A`)}constructor(t,n){if(this._closed=!1,t instanceof ArrayBuffer||typeof SharedArrayBuffer<`u`&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.format===void 0||!BM.has(n.format))throw TypeError(`init.format must be one of: `+zM.join(`, `));if(!Number.isInteger(n.codedWidth)||n.codedWidth<=0)throw TypeError(`init.codedWidth must be a positive integer.`);if(!Number.isInteger(n.codedHeight)||n.codedHeight<=0)throw TypeError(`init.codedHeight must be a positive integer.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(n.layout!==void 0){if(!Array.isArray(n.layout))throw TypeError(`init.layout, when provided, must be an array.`);for(let e of n.layout){if(!e||typeof e!=`object`||Array.isArray(e))throw TypeError(`Each entry in init.layout must be an object.`);if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(n.visibleRect!==void 0&&FA(n.visibleRect,`init.visibleRect`),n.displayWidth!==void 0&&(!Number.isInteger(n.displayWidth)||n.displayWidth<=0))throw TypeError(`init.displayWidth, when provided, must be a positive integer.`);if(n.displayHeight!==void 0&&(!Number.isInteger(n.displayHeight)||n.displayHeight<=0))throw TypeError(`init.displayHeight, when provided, must be a positive integer.`);if(n.displayWidth!==void 0!=(n.displayHeight!==void 0))throw TypeError(`init.displayWidth and init.displayHeight must be either both provided or both omitted.`);this._data=Pk(t).slice(),this._layout=n.layout??qM(n.format,n.codedWidth,n.codedHeight),this.format=n.format,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new HM(n.colorSpace),this.visibleRect={left:n.visibleRect?.left??0,top:n.visibleRect?.top??0,width:n.visibleRect?.width??n.codedWidth,height:n.visibleRect?.height??n.codedHeight},n.displayWidth===void 0?(this.squarePixelWidth=this.codedWidth,this.squarePixelHeight=this.codedHeight):(this.squarePixelWidth=this.rotation%180==0?n.displayWidth:n.displayHeight,this.squarePixelHeight=this.rotation%180==0?n.displayHeight:n.displayWidth)}else if(typeof VideoFrame<`u`&&t instanceof VideoFrame){if(n?.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(n?.timestamp!==void 0&&!Number.isFinite(n?.timestamp))throw TypeError(`init.timestamp, when provided, must be a number.`);if(n?.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);n?.visibleRect!==void 0&&FA(n.visibleRect,`init.visibleRect`),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=n?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=n?.timestamp??t.timestamp/1e6,this.duration=n?.duration??(t.duration??0)/1e6,this.colorSpace=new HM(t.colorSpace)}else if(typeof HTMLImageElement<`u`&&t instanceof HTMLImageElement||typeof SVGImageElement<`u`&&t instanceof SVGImageElement||typeof ImageBitmap<`u`&&t instanceof ImageBitmap||typeof HTMLVideoElement<`u`&&t instanceof HTMLVideoElement||typeof HTMLCanvasElement<`u`&&t instanceof HTMLCanvasElement||typeof OffscreenCanvas<`u`&&t instanceof OffscreenCanvas){if(!n||typeof n!=`object`)throw TypeError(`init must be an object.`);if(n.rotation!==void 0&&![0,90,180,270].includes(n.rotation))throw TypeError(`init.rotation, when provided, must be 0, 90, 180, or 270.`);if(!Number.isFinite(n.timestamp))throw TypeError(`init.timestamp must be a number.`);if(n.duration!==void 0&&(!Number.isFinite(n.duration)||n.duration<0))throw TypeError(`init.duration, when provided, must be a non-negative number.`);if(typeof VideoFrame<`u`)return new e(new VideoFrame(t,{timestamp:Math.trunc(n.timestamp*_A),duration:Math.trunc((n.duration??0)*_A)||void 0}),n);let r=0,i=0;if(`naturalWidth`in t?(r=t.naturalWidth,i=t.naturalHeight):`videoWidth`in t?(r=t.videoWidth,i=t.videoHeight):`width`in t&&(r=Number(t.width),i=Number(t.height)),!r||!i)throw TypeError(`Could not determine dimensions.`);let a=new OffscreenCanvas(r,i),o=a.getContext(`2d`,{alpha:CA(),willReadFrequently:!0});U(o),o.drawImage(t,0,0),this._data=a,this._layout=null,this.format=`RGBX`,this.visibleRect={left:0,top:0,width:r,height:i},this.squarePixelWidth=r,this.squarePixelHeight=i,this.rotation=n.rotation??0,this.timestamp=n.timestamp,this.duration=n.duration??0,this.colorSpace=new HM({matrix:`rgb`,primaries:`bt709`,transfer:`iec61966-2-1`,fullRange:!0})}else throw TypeError(`Invalid data type: Must be a BufferSource or CanvasImageSource.`);this.pixelAspectRatio=PA({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),RM?.register(this,{type:`video`,data:this._data},this)}clone(){if(this._closed)throw Error(`VideoSample is closed.`);return U(this._data!==null),UM(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(U(this._layout),new e(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||=(RM?.unregister(this),UM(this._data)?this._data.close():this._data=null,!0)}allocationSize(e={}){if(KM(e),this._closed)throw Error(`VideoSample is closed.`);if(this.format===null)throw Error(`Cannot get allocation size when format is null. Sorry!`);if(U(this._data!==null),!UM(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){let t=this.toVideoFrame(),n=t.allocationSize(e);return t.close(),n}return UM(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,t={}){if(!Kk(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(KM(t),this._closed)throw Error(`VideoSample is closed.`);if(this.format===null)throw Error(`Cannot copy video sample data when format is null. Sorry!`);if(U(this._data!==null),!UM(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){let n=this.toVideoFrame(),r=await n.copyTo(e,t);return n.close(),r}if(UM(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array)return U(this._layout),Pk(e).set(this._data),this._layout;{let t=this._data.getContext(`2d`);U(t);let n=t.getImageData(0,0,this.codedWidth,this.codedHeight);return Pk(e).set(n.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw Error(`VideoSample is closed.`);return U(this._data!==null),UM(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,n,r,i,a,o,s,c){let l=0,u=0,d=this.displayWidth,f=this.displayHeight,p=0,m=0,h=this.displayWidth,g=this.displayHeight;if(a===void 0?(p=t,m=n,r!==void 0&&(h=r,g=i)):(l=t,u=n,d=r,f=i,p=a,m=o,s===void 0?(h=d,g=f):(h=s,g=c)),!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!Number.isFinite(l))throw TypeError(`sx must be a number.`);if(!Number.isFinite(u))throw TypeError(`sy must be a number.`);if(!Number.isFinite(d)||d<0)throw TypeError(`sWidth must be a non-negative number.`);if(!Number.isFinite(f)||f<0)throw TypeError(`sHeight must be a non-negative number.`);if(!Number.isFinite(p))throw TypeError(`dx must be a number.`);if(!Number.isFinite(m))throw TypeError(`dy must be a number.`);if(!Number.isFinite(h)||h<0)throw TypeError(`dWidth must be a non-negative number.`);if(!Number.isFinite(g)||g<0)throw TypeError(`dHeight must be a non-negative number.`);if(this._closed)throw Error(`VideoSample is closed.`);({sx:l,sy:u,sWidth:d,sHeight:f}=this._rotateSourceRegion(l,u,d,f,this.rotation));let _=this.toCanvasImageSource();e.save();let v=p+h/2,y=m+g/2;e.translate(v,y),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:h/g;e.scale(1/b,b),e.drawImage(_,l,u,d,f,-h/2,-g/2,h,g),e.restore()}drawWithFit(e,t){if(!(typeof CanvasRenderingContext2D<`u`&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<`u`&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError(`context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit must be 'fill', 'contain', or 'cover'.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180, or 270.`);t.crop!==void 0&&GM(t.crop,`options.`);let n=e.canvas.width,r=e.canvas.height,i=t.rotation??this.rotation,[a,o]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];t.crop&&WM(t.crop,a,o);let s,c,l,u,{sx:d,sy:f,sWidth:p,sHeight:m}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??a,t.crop?.height??o,i);if(t.fit===`fill`)s=0,c=0,l=n,u=r;else{let[e,i]=t.crop?[t.crop.width,t.crop.height]:[a,o],d=t.fit===`contain`?Math.min(n/e,r/i):Math.max(n/e,r/i);l=e*d,u=i*d,s=(n-l)/2,c=(r-u)/2}e.save();let h=i%180==0?1:l/u;e.translate(n/2,r/2),e.rotate(i*Math.PI/180),e.scale(1/h,h),e.translate(-n/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,p,m,s,c,l,u),e.restore()}_rotateSourceRegion(e,t,n,r,i){return i===90?[e,t,n,r]=[t,this.squarePixelHeight-e-n,r,n]:i===180?[e,t]=[this.squarePixelWidth-e-n,this.squarePixelHeight-t-r]:i===270&&([e,t,n,r]=[this.squarePixelWidth-t-r,e,r,n]),{sx:e,sy:t,sWidth:n,sHeight:r}}toCanvasImageSource(){if(this._closed)throw Error(`VideoSample is closed.`);if(U(this._data!==null),this._data instanceof Uint8Array){let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError(`newRotation must be 0, 90, 180, or 270.`);this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError(`newDuration must be a non-negative number.`);this.duration=e}[Symbol.dispose](){this.close()}},HM=class{constructor(e){if(e!==void 0){if(!e||typeof e!=`object`)throw TypeError(`init.colorSpace, when provided, must be an object.`);let t=Object.keys(zk);if(e.primaries!=null&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(`, `)}.`);let n=Object.keys(Vk);if(e.transfer!=null&&!n.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${n.join(`, `)}.`);let r=Object.keys(Uk);if(e.matrix!=null&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(`, `)}.`);if(e.fullRange!=null&&typeof e.fullRange!=`boolean`)throw TypeError(`init.colorSpace.fullRange, when provided, must be a boolean.`)}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}},UM=e=>typeof VideoFrame<`u`&&e instanceof VideoFrame,WM=(e,t,n)=>{e.left=Math.min(e.left,t),e.top=Math.min(e.top,n),e.width=Math.min(e.width,t-e.left),e.height=Math.min(e.height,n-e.top),U(e.width>=0),U(e.height>=0)},GM=(e,t)=>{if(!e||typeof e!=`object`)throw TypeError(t+`crop, when provided, must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+`crop.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+`crop.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+`crop.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+`crop.height must be a non-negative integer.`)},KM=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.colorSpace!==void 0&&![`display-p3`,`srgb`].includes(e.colorSpace))throw TypeError(`options.colorSpace, when provided, must be 'display-p3' or 'srgb'.`);if(e.format!==void 0&&typeof e.format!=`string`)throw TypeError(`options.format, when provided, must be a string.`);if(e.layout!==void 0){if(!Array.isArray(e.layout))throw TypeError(`options.layout, when provided, must be an array.`);for(let t of e.layout){if(!t||typeof t!=`object`)throw TypeError(`Each entry in options.layout must be an object.`);if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError(`plane.offset must be a non-negative integer.`);if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError(`plane.stride must be a non-negative integer.`)}}if(e.rect!==void 0){if(!e.rect||typeof e.rect!=`object`)throw TypeError(`options.rect, when provided, must be an object.`);if(e.rect.x!==void 0&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError(`options.rect.x, when provided, must be a non-negative integer.`);if(e.rect.y!==void 0&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError(`options.rect.y, when provided, must be a non-negative integer.`);if(e.rect.width!==void 0&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError(`options.rect.width, when provided, must be a non-negative integer.`);if(e.rect.height!==void 0&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError(`options.rect.height, when provided, must be a non-negative integer.`)}},qM=(e,t,n)=>{let r=JM(e),i=[],a=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),o=Math.ceil(n/e.heightDivisor),s=r*e.sampleBytes,c=s*o;i.push({offset:a,stride:s}),a+=c}return i},JM=e=>{let t=(e,t,n,r,i)=>{let a=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:n,heightDivisor:r},{sampleBytes:t,widthDivisor:n,heightDivisor:r}];return i&&a.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),a};switch(e){case`I420`:return t(1,1,2,2,!1);case`I420P10`:case`I420P12`:return t(2,2,2,2,!1);case`I420A`:return t(1,1,2,2,!0);case`I420AP10`:case`I420AP12`:return t(2,2,2,2,!0);case`I422`:return t(1,1,2,1,!1);case`I422P10`:case`I422P12`:return t(2,2,2,1,!1);case`I422A`:return t(1,1,2,1,!0);case`I422AP10`:case`I422AP12`:return t(2,2,2,1,!0);case`I444`:return t(1,1,1,1,!1);case`I444P10`:case`I444P12`:return t(2,2,1,1,!1);case`I444A`:return t(1,1,1,1,!0);case`I444AP10`:case`I444AP12`:return t(2,2,1,1,!0);case`NV12`:return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case`RGBA`:case`RGBX`:case`BGRA`:case`BGRX`:return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:iA(e),U(!1)}},YM=new Set([`f32`,`f32-planar`,`s16`,`s16-planar`,`s32`,`s32-planar`,`u8`,`u8-planar`]),XM=class e{get microsecondTimestamp(){return Math.trunc(_A*this.timestamp)}get microsecondDuration(){return Math.trunc(_A*this.duration)}constructor(e){if(this._closed=!1,tN(e)){if(e.format===null)throw TypeError(`AudioData with null format is not supported.`);this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||typeof e!=`object`)throw TypeError(`Invalid AudioDataInit: must be an object.`);if(!YM.has(e.format))throw TypeError(`Invalid AudioDataInit: invalid format.`);if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError(`Invalid AudioDataInit: sampleRate must be > 0.`);if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw TypeError(`Invalid AudioDataInit: numberOfChannels must be an integer > 0.`);if(!Number.isFinite(e?.timestamp))throw TypeError(`init.timestamp must be a number.`);let t=e.data.byteLength/(ZM(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw TypeError(`Invalid AudioDataInit: data size is not a multiple of frame size.`);this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let n;if(e.data instanceof ArrayBuffer)n=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))n=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError(`Invalid AudioDataInit: data is not a BufferSource.`);let r=this.numberOfFrames*this.numberOfChannels*ZM(this.format);if(n.byteLength<r)throw TypeError(`Invalid AudioDataInit: insufficient data size.`);this._data=n}RM?.register(this,{type:`audio`,data:this._data},this)}allocationSize(e){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(e.format!==void 0&&!YM.has(e.format))throw TypeError(`Invalid format.`);if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let t=e.format??this.format,n=e.frameOffset??0;if(n>=this.numberOfFrames)throw RangeError(`frameOffset out of range`);let r=e.frameCount===void 0?this.numberOfFrames-n:e.frameCount;if(r>this.numberOfFrames-n)throw RangeError(`frameCount out of range`);let i=ZM(t),a=QM(t);if(a&&e.planeIndex>=this.numberOfChannels||!a&&e.planeIndex!==0)throw RangeError(`planeIndex out of range`);return(a?r:r*this.numberOfChannels)*i}copyTo(e,t){if(!Kk(e))throw TypeError(`destination must be an ArrayBuffer or an ArrayBuffer view.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError(`planeIndex must be a non-negative integer.`);if(t.format!==void 0&&!YM.has(t.format))throw TypeError(`Invalid format.`);if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError(`frameOffset must be a non-negative integer.`);if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError(`frameCount must be a non-negative integer.`);if(this._closed)throw Error(`AudioSample is closed.`);let{planeIndex:n,format:r,frameCount:i,frameOffset:a}=t,o=this.format,s=r??this.format;if(!s)throw Error(`Destination format not determined`);let c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw RangeError(`frameOffset out of range`);let d=i===void 0?c-u:i;if(d>c-u)throw RangeError(`frameCount out of range`);let f=ZM(s),p=QM(s);if(p&&n>=l||!p&&n!==0)throw RangeError(`planeIndex out of range`);let m=(p?d:d*l)*f;if(e.byteLength<m)throw RangeError(`Destination buffer is too small`);let h=Fk(e),g=eN(s);if(tN(this._data))xA()&&l>2&&s!==o?nN(this._data,h,o,s,l,n,u,d):this._data.copyTo(e,{planeIndex:n,frameOffset:u,frameCount:d,format:s});else{let e=this._data,t=Fk(e),r=$M(o),i=ZM(o),a=QM(o);for(let e=0;e<d;e++)if(p){let o=e*f,s;s=a?(n*c+(e+u))*i:((e+u)*l+n)*i,g(h,o,r(t,s))}else for(let n=0;n<l;n++){let o=(e*l+n)*f,s;s=a?(n*c+(e+u))*i:((e+u)*l+n)*i,g(h,o,r(t,s))}}}clone(){if(this._closed)throw Error(`AudioSample is closed.`);if(tN(this._data)){let t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}else return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||=(RM?.unregister(this),tN(this._data)?this._data.close():this._data=new Uint8Array,!0)}toAudioData(){if(this._closed)throw Error(`AudioSample is closed.`);if(tN(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(QM(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(new Uint8Array(t,n*e,e),{planeIndex:n,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}else{let e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}else return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw Error(`AudioSample is closed.`);let e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:`f32-planar`})/4);for(let n=0;n<this.numberOfChannels;n++)this.copyTo(t,{planeIndex:n,format:`f32-planar`}),e.copyToChannel(t,n);return e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError(`newTimestamp must be a number.`);this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a;for(;c>0;){let a=Math.min(o,c),l=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*a,(e+1)*a),e,s);yield new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:l}),s+=a,c-=a}}static fromAudioBuffer(t,n){if(!(t instanceof AudioBuffer))throw TypeError(`audioBuffer must be an AudioBuffer.`);let r=t.numberOfChannels,i=t.sampleRate,a=t.length,o=Math.floor(24e4/r),s=0,c=a,l=[];for(;c>0;){let a=Math.min(o,c),u=new Float32Array(r*a);for(let e=0;e<r;e++)t.copyFromChannel(u.subarray(e*a,(e+1)*a),e,s);let d=new e({format:`f32-planar`,sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:n+s/i,data:u});l.push(d),s+=a,c-=a}return l}},ZM=e=>{switch(e){case`u8`:case`u8-planar`:return 1;case`s16`:case`s16-planar`:return 2;case`s32`:case`s32-planar`:return 4;case`f32`:case`f32-planar`:return 4;default:throw Error(`Unknown AudioSampleFormat`)}},QM=e=>{switch(e){case`u8-planar`:case`s16-planar`:case`s32-planar`:case`f32-planar`:return!0;default:return!1}},$M=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t)=>(e.getUint8(t)-128)/128;case`s16`:case`s16-planar`:return(e,t)=>e.getInt16(t,!0)/32768;case`s32`:case`s32-planar`:return(e,t)=>e.getInt32(t,!0)/2147483648;case`f32`:case`f32-planar`:return(e,t)=>e.getFloat32(t,!0)}},eN=e=>{switch(e){case`u8`:case`u8-planar`:return(e,t,n)=>e.setUint8(t,uA((n+1)*127.5,0,255));case`s16`:case`s16-planar`:return(e,t,n)=>e.setInt16(t,uA(Math.round(n*32767),-32768,32767),!0);case`s32`:case`s32-planar`:return(e,t,n)=>e.setInt32(t,uA(Math.round(n*2147483647),-2147483648,2147483647),!0);case`f32`:case`f32-planar`:return(e,t,n)=>e.setFloat32(t,n,!0)}},tN=e=>typeof AudioData<`u`&&e instanceof AudioData,nN=(e,t,n,r,i,a,o,s)=>{let c=$M(n),l=eN(r),u=ZM(n),d=ZM(r),f=QM(n);if(QM(r))if(f){let r=new ArrayBuffer(s*u),i=Fk(r);e.copyTo(r,{planeIndex:a,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,e*d,c(i,n))}}else{let r=new ArrayBuffer(s*i*u),f=Fk(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=(e*i+a)*u;l(t,e*d,c(f,n))}}else if(f){let r=s*u,a=new ArrayBuffer(r),f=Fk(a);for(let r=0;r<i;r++){e.copyTo(a,{planeIndex:r,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++){let n=e*u;l(t,(e*i+r)*d,c(f,n))}}}else{let r=new ArrayBuffer(s*i*u),a=Fk(r);e.copyTo(r,{planeIndex:0,frameOffset:o,frameCount:s,format:n});for(let e=0;e<s;e++)for(let n=0;n<i;n++){let r=e*i+n,o=r*u;l(t,r*d,c(a,o))}}},rN=e=>{if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.metadataOnly!==void 0&&typeof e.metadataOnly!=`boolean`)throw TypeError(`options.metadataOnly, when defined, must be a boolean.`);if(e.verifyKeyPackets!==void 0&&typeof e.verifyKeyPackets!=`boolean`)throw TypeError(`options.verifyKeyPackets, when defined, must be a boolean.`);if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError(`options.verifyKeyPackets and options.metadataOnly cannot be enabled together.`)},iN=e=>{if(!NA(e))throw TypeError(`timestamp must be a number.`)},aN=(e,t,n)=>n.verifyKeyPackets?t.then(async t=>{if(!t||t.type===`delta`)return t;let n=await e.determinePacketType(t);return n&&(t.type=n),t}):t,oN=class{constructor(e){if(!(e instanceof _N))throw TypeError(`track must be an InputTrack.`);this._track=e}getFirstPacket(e={}){if(rN(e),this._track.input._disposed)throw new EF;return aN(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){rN(e);let t=await this.getFirstPacket(e);return t?t.type===`key`?t:this.getNextKeyPacket(t,e):null}getPacket(e,t={}){if(iN(e),rN(t),this._track.input._disposed)throw new EF;return aN(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof jM))throw TypeError(`packet must be an EncodedPacket.`);if(rN(t),this._track.input._disposed)throw new EF;return aN(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(iN(e),rN(t),this._track.input._disposed)throw new EF;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let n=await this._track._backing.getKeyPacket(e,t);return n&&(U(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getKeyPacket(n.timestamp-1/this._track.timeResolution,t):n)}async getNextKeyPacket(e,t={}){if(!(e instanceof jM))throw TypeError(`packet must be an EncodedPacket.`);if(rN(t),this._track.input._disposed)throw new EF;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let n=await this._track._backing.getNextKeyPacket(e,t);return n&&(U(n.type===`key`),await this._track.determinePacketType(n)===`delta`?this.getNextKeyPacket(n,t):n)}packets(e,t,n={}){if(e!==void 0&&!(e instanceof jM))throw TypeError(`startPacket must be an EncodedPacket.`);if(e!==void 0&&e.isMetadataOnly&&!n?.metadataOnly)throw TypeError(`startPacket can only be metadata-only if options.metadataOnly is enabled.`);if(t!==void 0&&!(t instanceof jM))throw TypeError(`endPacket must be an EncodedPacket.`);if(rN(n),this._track.input._disposed)throw new EF;let r=[],{promise:i,resolve:a}=$k(),{promise:o,resolve:s}=$k(),c=!1,l=!1,u=null,d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(n);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(r.length>f()){({promise:o,resolve:s}=$k()),await o;continue}r.push(u),a(),{promise:i,resolve:a}=$k(),u=await this.getNextPacket(u,n)}c=!0,a()})().catch(e=>{u||(u=e,a())});let p=this._track;return{async next(){for(;;)if(p.input._disposed)throw new EF;else if(l)return{value:void 0,done:!0};else if(u)throw u;else if(r.length>0){let e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return s(),{value:e,done:!1}}else if(c)return{value:void 0,done:!0};else await i},async return(){return l=!0,s(),a(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},sN=class{constructor(e,t){this.onSample=e,this.onError=t}},cN=class{mediaSamplesInRange(e=0,t=1/0){iN(e),iN(t);let n=[],r=!1,i=null,{promise:a,resolve:o}=$k(),{promise:s,resolve:c}=$k(),l=!1,u=!1,d=!1,f=null;(async()=>{let p=await this._createDecoder(s=>{if(c(),s.timestamp>=t&&(u=!0),u){s.close();return}i&&(s.timestamp>e?(n.push(i),r=!0):i.close()),s.timestamp>=e&&(n.push(s),r=!0),i=r?null:s,n.length>0&&(o(),{promise:a,resolve:o}=$k())},e=>{f||(f=e,o())}),m=this._createPacketSink(),h=await m.getKeyPacket(e,{verifyKeyPackets:!0})??await m.getFirstKeyPacket({verifyKeyPackets:!0}),g=h,_=m.packets(h??void 0,void 0);for(await _.next();g&&!u&&!this._track.input._disposed;){let e=lN(n.length);if(n.length+p.getDecodeQueueSize()>e){({promise:s,resolve:c}=$k()),await s;continue}p.decode(g);let t=await _.next();if(t.done)break;g=t.value}await _.return(),!d&&!this._track.input._disposed&&await p.flush(),p.close(),!r&&i&&n.push(i),l=!0,o()})().catch(e=>{f||(f=e,o())});let p=this._track,m=()=>{i?.close();for(let e of n)e.close()};return{async next(){for(;;)if(p.input._disposed)throw m(),new EF;else if(d)return{value:void 0,done:!0};else if(f)throw m(),f;else if(n.length>0){let e=n.shift();return c(),{value:e,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}},async return(){return d=!0,u=!0,c(),o(),m(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){rA(e);let t=nA(e),n=[],r=[],{promise:i,resolve:a}=$k(),{promise:o,resolve:s}=$k(),c=!1,l=!1,u=null,d=e=>{r.push(e),a(),{promise:i,resolve:a}=$k()};(async()=>{let e=await this._createDecoder(e=>{if(s(),l){e.close();return}let t=0;for(;n.length>0&&e.timestamp-n[0]>-1e-10;)t++,n.shift();if(t>0)for(let n=0;n<t;n++)d(n<t-1?e.clone():e);else e.close()},e=>{u||(u=e,a())}),i=this._createPacketSink(),f=null,p=null,m=-1,h=async()=>{U(p);let t=p;for(e.decode(t);t.sequenceNumber<m;){let n=lN(r.length);for(;r.length+e.getDecodeQueueSize()>n&&!l;)({promise:o,resolve:s}=$k()),await o;if(l)break;let a=await i.getNextPacket(t);U(a),e.decode(a),t=a}m=-1},g=async()=>{await e.flush();for(let e=0;e<n.length;e++)d(null);n.length=0};for await(let e of t){if(iN(e),l||this._track.input._disposed)break;let t=await i.getPacket(e),r=t&&await i.getKeyPacket(e,{verifyKeyPackets:!0});if(!r){m!==-1&&(await h(),await g()),d(null),f=null;continue}f&&(r.sequenceNumber!==p.sequenceNumber||t.timestamp<f.timestamp)&&(await h(),await g()),n.push(t.timestamp),m=Math.max(t.sequenceNumber,m),f=t,p=r}!l&&!this._track.input._disposed&&(m!==-1&&await h(),await g()),e.close(),c=!0,a()})().catch(e=>{u||(u=e,a())});let f=this._track,p=()=>{for(let e of r)e?.close()};return{async next(){for(;;)if(f.input._disposed)throw p(),new EF;else if(l)return{value:void 0,done:!0};else if(u)throw p(),u;else if(r.length>0){let e=r.shift();return U(e!==void 0),s(),{value:e,done:!1}}else if(!c)await i;else return{value:void 0,done:!0}},async return(){return l=!0,s(),a(),p(),{value:void 0,done:!0}},async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},lN=e=>e===0?40:8,uN=class extends sN{constructor(e,t,n,r,i,a){super(e,t),this.codec=n,this.decoderConfig=r,this.rotation=i,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new yA,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;let o=EM.find(e=>e.supports(n,r));if(o)this.customDecoder=new o,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof VM))throw TypeError(`The argument passed to onSample must be a VideoSample.`);this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();U(t!==void 0),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(n===`avc`&&this.decoderConfig.description&&TA()){let e=Wj(Pk(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=Kj(e.sequenceParameterSets[0]);t&&t.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:`prefer-software`})}}let t=Error(`Decoding error`).stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(U(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(this.codec===`hevc`&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(U(this.decoder),xA()||Qk(this.inputTimestamps,e.timestamp,e=>e),TA()&&this.currentPacketIndex===0&&this.codec===`avc`){let t=[];for(let n of Fj(e.data,this.decoderConfig)){let r=Ij(e.data[n.offset]);r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}e=new jM(Vj(t,this.decoderConfig),e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed){this.pushNullAlphaFrame();return}if(!this.merger)try{this.merger=new dN}catch(t){console.error(`Due to an error, only color data will be decoded.`,t),this.mergerCreationFailed=!0,this.decodeAlphaData(e);return}if(!this.alphaDecoder){let e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){let t=this.colorQueue.shift();U(t!==void 0),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();U(e!==void 0),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},t=Error(`Decoding error`).stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=pM(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||=t===`key`,this.alphaHadKeyframe){if(this.codec===`hevc`&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of Jj(e,this.decoderConfig)){let n=Yj(e[t.offset]);if(n===Mj.RASL_N||n===Mj.RASL_R)return!0}return!1}sampleHandler(e){if(xA()){if(this.sampleQueue.length>0&&e.timestamp>=jk(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Qk(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();U(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,t){if(!t){let t=new VM(e);this.sampleHandler(t);return}U(this.merger),this.merger.update(e,t),e.close(),t.close();let n=new VM(new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}));this.sampleHandler(n)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(U(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),xA()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(U(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(let e of this.sampleQueue)e.close();this.sampleQueue.length=0}},dN=class{constructor(){typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement(`canvas`);let e=this.canvas.getContext(`webgl2`,{premultipliedAlpha:!1});if(!e)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_colorTexture`),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,`u_alphaTexture`),1)}createProgram(){let e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2102
2102
  in vec2 a_position;
2103
2103
  in vec2 a_texCoord;
2104
2104
  out vec2 v_texCoord;
@@ -2120,7 +2120,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
2120
2120
  float alpha = texture(u_alphaTexture, v_texCoord).r;
2121
2121
  fragColor = vec4(color, alpha);
2122
2122
  }
2123
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.program,`a_position`),i=this.gl.getAttribLocation(this.program,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null}},rN=class extends $M{constructor(e){if(!(e instanceof lN))throw TypeError(`videoTrack must be an InputVideoTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This video track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let n=this._track.codec,r=this._track.rotation,i=await this._track.getDecoderConfig(),a=this._track.timeResolution;return U(n&&i),new tN(e,t,n,i,r,a)}_createPacketSink(){return new ZM(this._track)}async getSample(e){YM(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw Error(`Internal error: Iterator returned nothing.`)}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},iN=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof lN))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&IM(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);let n=t.rotation??e.rotation,[r,i]=n%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],a=t.crop;a&&FM(a,r,i);let[o,s]=a?[a.width,a.height]:[r,i],c=o/s;t.width!==void 0&&t.height===void 0?(o=t.width,s=Math.round(o/c)):t.width===void 0&&t.height!==void 0?(s=t.height,o=Math.round(s*c)):t.width!==void 0&&t.height!==void 0&&(o=t.width,s=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=o,this._height=s,this._rotation=n,this._crop=a,this._fit=t.fit??`fill`,this._videoSampleSink=new rN(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<`u`?(t=document.createElement(`canvas`),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let r=t.getContext(`2d`,{alpha:this._alpha||mA()});U(r),r.resetTransform(),n||(!this._alpha&&mA()?(r.fillStyle=`black`,r.fillRect(0,0,this._width,this._height)):r.clearRect(0,0,this._width,this._height)),e.drawWithFit(r,{fit:this._fit,rotation:this._rotation,crop:this._crop});let i={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),i}async getCanvas(e){YM(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return eA(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return eA(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}},aN=class extends QM{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new uA,this.customDecoderQueueSize=0,this.currentTimestamp=null;let i=t=>{(this.currentTimestamp===null||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);let n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,t.numberOfFrames===0){t.close();return}let i=r.sampleRate;t.setTimestamp(Math.round(n*i)/i),e(t)},a=vM.find(e=>e.supports(n,r));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof VM))throw TypeError(`The argument passed to onSample must be an AudioSample.`);i(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=Error(`Decoding error`).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new VM(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(U(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(U(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(U(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(U(this.decoder),this.decoder.close())}},oN=class extends QM{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,U(RA.includes(n.codec)),this.codec=n.codec;let{dataType:r,sampleSize:i,littleEndian:a}=tj(this.codec);switch(this.inputSampleSize=i,i){case 1:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-2**7:r===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):r===`ulaw`?this.readInputValue=(e,t)=>wM(e.getUint8(t)):r===`alaw`?this.readInputValue=(e,t)=>EM(e.getUint8(t)):U(!1);break;case 2:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint16(t,a)-2**15:r===`signed`?this.readInputValue=(e,t)=>e.getInt16(t,a):U(!1);break;case 3:r===`unsigned`?this.readInputValue=(e,t)=>Xk(e,t,a)-2**23:r===`signed`?this.readInputValue=(e,t)=>Zk(e,t,a):U(!1);break;case 4:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint32(t,a)-2**31:r===`signed`?this.readInputValue=(e,t)=>e.getInt32(t,a):r===`float`?this.readInputValue=(e,t)=>e.getFloat32(t,a):U(!1);break;case 8:r===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,a):U(!1);break;default:Yk(i),U(!1)}switch(i){case 1:r===`ulaw`||r===`alaw`?(this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0)):(this.outputSampleSize=1,this.outputFormat=`u8`,this.writeOutputValue=(e,t,n)=>e.setUint8(t,n+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0);break;case 3:this.outputSampleSize=4,this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n<<8,!0);break;case 4:this.outputSampleSize=4,r===`float`?(this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0)):(this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n,!0));break;case 8:this.outputSampleSize=4,this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0);break;default:Yk(i),U(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=Ek(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(r),a=new DataView(i);for(let e=0;e<n*this.decoderConfig.numberOfChannels;e++){let n=e*this.inputSampleSize,r=e*this.outputSampleSize,i=this.readInputValue(t,n);this.writeOutputValue(a,r,i)}let o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let s=this.currentTimestamp;this.currentTimestamp+=o;let c=new VM({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:s});this.onSample(c)}async flush(){}close(){}},sN=class extends $M{constructor(e){if(!(e instanceof uN))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let n=this._track.codec,r=await this._track.getDecoderConfig();return U(n&&r),RA.includes(r.codec)?new oN(e,t,r):new aN(e,t,n,r)}_createPacketSink(){return new ZM(this._track)}async getSample(e){YM(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw Error(`Internal error: Iterator returned nothing.`)}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},cN=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof lN}isAudioTrack(){return this instanceof uN}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new ZM(this),n=1/0,r=-1/0,i=0,a=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&o.timestamp>=r)break;n=Math.min(n,o.timestamp),r=Math.max(r,o.timestamp+o.duration),i++,a+=o.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(r-n)).toPrecision(16)):0,averageBitrate:i?Number((8*a/(r-n)).toPrecision(16)):0}}},lN=class extends cN{constructor(e,t){super(e,t),this._backing=t,this.pixelAspectRatio=TA({num:this._backing.getSquarePixelWidth()*this._backing.getCodedHeight(),den:this._backing.getSquarePixelHeight()*this._backing.getCodedWidth()})}get type(){return`video`}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get squarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelHeight(){return this._backing.getSquarePixelHeight()}get displayWidth(){return this._backing.getRotation()%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this._backing.getRotation()%180==0?this.squarePixelHeight:this.squarePixelWidth}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pg`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return U(t!==null),_M.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof SM))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);if(this.codec===null)return null;let t=await this.getDecoderConfig();return U(t),iM(this.codec,t,e.data)}},uN=class extends cN{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return U(t!==null),vM.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof SM))throw TypeError(`packet must be an EncodedPacket.`);return this.codec===null?null:`key`}},dN=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},fN=e=>{let t=Y(e),n=FF(e,4),r=8;t===1&&(t=AF(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},pN=e=>DF(e)/65536,mN=e=>DF(e)/1073741824,hN=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=J(e);if(t|=n&127,!(n&128))break}return t},gN=e=>{let t=SF(e);return e.skip(2),t=Math.min(t,e.remainingLength),Dk.decode(q(e,t))},_N=e=>{let t=fN(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=Y(e);e.skip(4);let r=q(e,t.contentSize-8);switch(n){case 1:return Dk.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new DA(r,`image/jpeg`);case 14:return new DA(r,`image/png`);case 27:return new DA(r,`image/bmp`);default:return r}},vN=class extends gM{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return dN({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,16);if(t instanceof Promise&&(t=await t),!t)break;let n=e,r=fN(t);if(!r)break;if(r.name===`ftyp`)this.isQuickTime=FF(t,4)===`qt `;else if(r.name===`moov`){let e=this.reader.requestSlice(t.filePos,r.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=n+r.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),U(e);let t=Y(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),e){let t=fN(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);n instanceof Promise&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,U(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&RA.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){U(e.info?.type===`audio`);let n=tj(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=Hk(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=Hk(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=Sk(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),U(t);let n=fN(t);U(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);r instanceof Promise&&(r=await r),U(r),this.traverseBox(r);let i=this.lastReadFragment;U(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)EN(e,r.timestamp);else{let t=Hk(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];EN(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=Hk(n,e.startTimestamp,e=>e.startTimestamp);(r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=fN(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=fN(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=J(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=Y(e),this.movieDurationInTimescale=AF(e)):(e.skip(8),this.movieTimescale=Y(e),this.movieDurationInTimescale=Y(e))}break;case`trak`:{let t={id:-1,demuxer:this,inputTrack:null,disposition:{...AA},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null){if(t.info.type===`video`&&t.info.width!==-1){let e=t;t.inputTrack=new lN(this.input,new bN(e)),this.tracks.push(t)}else if(t.info.type===`audio`&&t.info.numberOfChannels!==-1){let e=t;t.inputTrack=new uN(this.input,new xN(e)),this.tracks.push(t)}}this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=J(e),r=!!(CF(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=Y(e),e.skip(4),t.durationInMovieTimescale=Y(e);else if(n===1)e.skip(16),t.id=Y(e),e.skip(4),t.durationInMovieTimescale=AF(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=xk(rA(DN([pN(e),pN(e),mN(e),pN(e),pN(e),mN(e),pN(e),pN(e),mN(e)]),90));U(i===0||i===90||i===180||i===270),t.rotation=i}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=J(e);e.skip(3);let r=!1,i=0,a=Y(e);for(let o=0;o<a;o++){let a=n===1?AF(e):Y(e),o=n===1?jF(e):DF(e),s=pN(e);if(a!==0){if(r){console.warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){console.warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=J(e);e.skip(3),n===0?(e.skip(8),t.timescale=Y(e),t.durationInMediaTimescale=Y(e)):n===1&&(e.skip(16),t.timescale=Y(e),t.durationInMediaTimescale=AF(e));let r=SF(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;sA(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=FF(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=J(e);e.skip(3);let r=Y(e);for(let i=0;i<r;i++){let r=e.filePos,i=fN(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`)a===`avc1`||a===`avc3`?(t.info.codec=`avc`,t.info.avcType=a===`avc1`?1:3):a===`hvc1`||a===`hev1`?t.info.codec=`hevc`:a===`vp08`?t.info.codec=`vp8`:a===`vp09`?t.info.codec=`vp9`:a===`av01`?t.info.codec=`av1`:console.warn(`Unsupported video codec (sample entry type '${i.name}').`),e.skip(24),t.info.width=SF(e),t.info.height=SF(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));else{a===`mp4a`||(a===`opus`?t.info.codec=`opus`:a===`flac`?t.info.codec=`flac`:a===`twos`||a===`sowt`||a===`raw `||a===`in24`||a===`in32`||a===`fl32`||a===`fl64`||a===`lpcm`||a===`ipcm`||a===`fpcm`||(a===`ulaw`?t.info.codec=`ulaw`:a===`alaw`?t.info.codec=`alaw`:a===`ac-3`?t.info.codec=`ac3`:a===`ec-3`?t.info.codec=`eac3`:console.warn(`Unsupported audio codec (sample entry type '${i.name}').`))),e.skip(8);let o=SF(e);e.skip(6);let s=SF(e),c=SF(e);e.skip(4);let l=Y(e)/65536;if(n===0&&o>0){if(o===1)e.skip(4),c=8*Y(e),e.skip(8);else if(o===2){e.skip(4),l=PF(e),s=Y(e),e.skip(4),c=Y(e);let n=Y(e);if(e.skip(8),a===`lpcm`){let e=c+7>>3,r=!!(n&1),i=!!(n&2),a=n&4?-1:0;c>0&&c<=64&&(r?c===32&&(t.info.codec=i?`pcm-f32be`:`pcm-f32`):a&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=i?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=i?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=i?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&console.warn(`Unsupported PCM format.`)}}}t.info.codec===`opus`&&(l=$A),t.info.numberOfChannels=s,t.info.sampleRate=l,a===`twos`?c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16be`:(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):a===`sowt`?c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null):a===`raw `?t.info.codec=`pcm-u8`:a===`in24`?t.info.codec=`pcm-s24be`:a===`in32`?t.info.codec=`pcm-s32be`:a===`fl32`?t.info.codec=`pcm-f32be`:a===`fl64`?t.info.codec=`pcm-f64be`:a===`ipcm`?t.info.codec=`pcm-s16be`:a===`fpcm`&&(t.info.codec=`pcm-f32be`),this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos))}}}break;case`avcC`:{let t=this.currentTrack;if(!t)break;U(t.info),t.info.codecDescription=q(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t)break;U(t.info),t.info.codecDescription=q(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`video`),e.skip(4);let n=J(e),r=J(e),i=J(e),a=i>>4,o=i>>1&7,s=i&1,c=J(e),l=J(e),u=J(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`video`),e.skip(1);let n=J(e),r=n>>5,i=n&31,a=J(e),o=a>>7,s=a>>6&1,c=a>>5&1,l=a>>4&1,u=a>>3&1,d=a>>2&1,f=a&3,p=r===2&&s?c?12:10:s?10:8;t.info.av1CodecInfo={profile:r,level:i,tier:o,bitDepth:p,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:f}}break;case`colr`:{let t=this.currentTrack;if(!t||(U(t.info?.type===`video`),FF(e,4)!==`nclx`))break;let n=SF(e),r=SF(e),i=SF(e),a=!!(J(e)&128);t.info.colorSpace={primaries:jk[n],transfer:Nk[r],matrix:Fk[i],fullRange:a}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`video`);let n=Y(e),r=Y(e);n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n)}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(4),U(J(e)===3),hN(e),e.skip(2);let n=J(e),r=(n&128)!=0,i=(n&64)!=0,a=(n&32)!=0;if(r&&e.skip(2),i){let t=J(e);e.skip(t)}a&&e.skip(2),U(J(e)===4);let o=hN(e),s=e.filePos,c=J(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){U(J(e)===5);let n=hN(e);if(t.info.codecDescription=q(e,n),t.info.codec===`aac`){let e=FA(t.info.codecDescription);e.numberOfChannels!==null&&(t.info.numberOfChannels=e.numberOfChannels),e.sampleRate!==null&&(t.info.sampleRate=e.sampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),SF(e)&255&&(t.info.codec===`pcm-s16be`?t.info.codec=`pcm-s16`:t.info.codec===`pcm-s24be`?t.info.codec=`pcm-s24`:t.info.codec===`pcm-s32be`?t.info.codec=`pcm-s32`:t.info.codec===`pcm-f32be`?t.info.codec=`pcm-f32`:t.info.codec===`pcm-f64be`&&(t.info.codec=`pcm-f64`))}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(4);let n=!!(J(e)&1),r=J(e);t.info.codec===`pcm-s16be`?n?r===16?t.info.codec=`pcm-s16`:r===24?t.info.codec=`pcm-s24`:r===32?t.info.codec=`pcm-s32`:(console.warn(`Invalid ipcm sample size ${r}.`),t.info.codec=null):r===16?t.info.codec=`pcm-s16be`:r===24?t.info.codec=`pcm-s24be`:r===32?t.info.codec=`pcm-s32be`:(console.warn(`Invalid ipcm sample size ${r}.`),t.info.codec=null):t.info.codec===`pcm-f32be`&&(n?r===32?t.info.codec=`pcm-f32`:r===64?t.info.codec=`pcm-f64`:(console.warn(`Invalid fpcm sample size ${r}.`),t.info.codec=null):r===32?t.info.codec=`pcm-f32be`:r===64?t.info.codec=`pcm-f64be`:(console.warn(`Invalid fpcm sample size ${r}.`),t.info.codec=null));break}case`dOps`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(1);let n=J(e),r=SF(e),i=Y(e),a=wF(e),o=J(e),s;s=o===0?new Uint8Array:q(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=J(e),r=CF(e);if((n&127)===aM.STREAMINFO){e.skip(10);let n=Y(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=q(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`);let n=new MA(q(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=bj[r]),t.info.numberOfChannels=sM[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`);let r=pM(q(e,n.contentSize));if(!r){console.warn(`Invalid dec3 box contents, ignoring.`);break}let i=mM(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=hM(r)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=0,i=0;for(let a=0;a<n;a++){let n=Y(e),a=Y(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=0;for(let i=0;i<n;i++){let n=Y(e),i=DF(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=Y(e);if(n===0)for(let n=0;n<r;n++){let n=Y(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=J(e),r=Y(e),i=new MA(q(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=Y(e);for(let r=0;r<n;r++){let n=Y(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=Y(e)-1,r=Y(e),i=Y(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=Y(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=AF(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=J(e);e.skip(3),this.movieDurationInTimescale=t===1?AF(e):Y(e)}break;case`trex`:{e.skip(4);let t=Y(e),n=Y(e),r=Y(e),i=Y(e),a=Y(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=J(e);e.skip(3);let n=Y(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=Y(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[J,SF,CF,Y],l=c[a],u=c[o],d=c[s],f=Y(e);for(let n=0;n<f;n++){let n=t===1?AF(e):Y(e),i=t===1?AF(e):Y(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(U(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){let{currentFragmentState:t}=this.currentTrack;U(t),t.startTimestamp!==null&&(EN(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`tfhd`:{U(this.currentFragment),e.skip(1);let t=CF(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=Y(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null},n?u.currentFragmentState.baseDataOffset=AF(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Y(e)),i&&(u.currentFragmentState.defaultSampleDuration=Y(e)),a&&(u.currentFragmentState.defaultSampleSize=Y(e)),o&&(u.currentFragmentState.defaultSampleFlags=Y(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;U(t.currentFragmentState);let n=J(e);e.skip(3);let r=n===0?Y(e):AF(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;if(U(this.currentFragment),U(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn(`Can't have two trun boxes for the same track in one fragment. Ignoring...`);break}let n=J(e),r=CF(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=Y(e),d=t.currentFragmentState.baseDataOffset;i&&(d+=DF(e));let f=null;a&&(f=Y(e));let p=d;if(u===0){this.currentFragment.implicitBaseDataOffset=p;break}let m=0,h={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,h);for(let r=0;r<u;r++){let i;o?i=Y(e):(U(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=Y(e):(U(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=Y(e):(U(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?Y(e):DF(e));let g=!(u&65536);h.samples.push({presentationTimestamp:m+d,duration:i,byteOffset:p,byteSize:a,isKeyFrame:g}),p+=a,m+=i}h.presentationTimestamps=h.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<h.presentationTimestamps.length;e++){let t=h.presentationTimestamps[e],n=h.samples[t.sampleIndex];h.firstKeyFrameTimestamp===null&&n.isKeyFrame&&(h.firstKeyFrameTimestamp=n.presentationTimestamp),e<h.presentationTimestamps.length-1&&(n.duration=h.presentationTimestamps[e+1].presentationTimestamp-t.presentationTimestamp)}let g=h.samples[h.presentationTimestamps[0].sampleIndex],_=h.samples[Sk(h.presentationTimestamps).sampleIndex];h.startTimestamp=g.presentationTimestamp,h.endTimestamp=_.presentationTimestamp+_.duration,this.currentFragment.implicitBaseDataOffset=p}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=gN(n):this.metadataTags.raw[e.name]??=q(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=Dk.decode(q(n,e.contentSize)):this.metadataTags.title??=gN(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=gN(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=gN(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=gN(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=gN(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=gN(n));break;case`©day`:if(!this.currentTrack){let e=new Date(gN(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=gN(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=gN(n));break}}}break;case`meta`:{if(this.currentTrack)break;let t=Y(e)!==0;this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=Y(e);for(let n=0;n<t;n++){let t=Y(e);e.skip(4);let r=Dk.decode(q(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=_N(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof DA?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=Ek(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=Ek(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}break}}}break}return e.filePos=i,!0}},yN=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.inputTrack.type,n=0;for(let r of e.tracks)if(r.inputTrack.type===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return nA(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=SN(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!ON(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Hk(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=CN(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!ON(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Kk(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=TN(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return U(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=wN(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=xM;else{let e=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);e instanceof Promise&&(e=await e),U(e),r=q(e,n.sampleSize)}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new SM(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];U(r);let i;if(n.metadataOnly)i=xM;else{let e=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);e instanceof Promise&&(e=await e),U(e),i=q(e,r.byteSize)}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new SM(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=Hk(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=Hk(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(e instanceof Promise&&(e=await e),!e)break;let n=m,l=fN(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];U(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},bN=class extends yN{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Zj(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&$j(e.data)}return{codec:XA(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},xN=class extends yN{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:QA(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},SN=(e,t)=>{if(e.presentationTimestamps){let n=Hk(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}else{let n=Hk(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},CN=(e,t)=>{if(!e.keySampleIndices)return SN(e,t);if(e.presentationTimestamps){let n=Hk(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(Vk(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}else{let n=SN(e,t),r=Hk(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},wN=(e,t)=>{let n=Hk(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=Hk(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=Hk(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];U(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];U(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:e.keySampleIndices?Vk(e.keySampleIndices,t,e=>e)!==-1:!0}},TN=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=Hk(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},EN=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},DN=e=>{let[t,,,n]=e,r=Math.hypot(t,n),i=t/r,a=n/r,o=-Math.atan2(a,i)*(180/Math.PI);return Number.isFinite(o)?o:0},ON=e=>e.sampleSizes.length===0,G;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(G||={});var kN=[G.EBML,G.Segment],AN=[G.SeekHead,G.Info,G.Cluster,G.Tracks,G.Cues,G.Attachments,G.Chapters,G.Tags],jN=[...kN,...AN],MN=e=>{if(e.remainingLength<1)return null;let t=J(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},NN=e=>{if(e.remainingLength<1)return null;let t=J(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=J(e);return i},K=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=J(e);return n},PN=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(J(e));return n},FN=e=>{let t=MN(e);return t===null||e.remainingLength<t?null:K(e,t)},IN=e=>{if(e.remainingLength<1)return null;if(J(e)===255)return;e.skip(-1);let t=NN(e);if(t===null)return null;if(t!==72057594037927940)return t},LN=e=>{U(e.remainingLength>=2);let t=FN(e);if(t===null)return null;let n=IN(e);return n===null?null:{id:t,size:n}},RN=(e,t)=>{let n=q(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},zN=(e,t)=>{let n=q(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return Dk.decode(n.subarray(0,r))},BN=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?NF(e):PF(e)},VN=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=LN(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};WN(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},HN=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=FN(t);if(e!==null&&a.has(e))return o;o++}}return null},UN={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,"pcm-u8":`A_PCM/INT/LIT`,"pcm-s16":`A_PCM/INT/LIT`,"pcm-s16be":`A_PCM/INT/BIG`,"pcm-s24":`A_PCM/INT/LIT`,"pcm-s24be":`A_PCM/INT/BIG`,"pcm-s32":`A_PCM/INT/LIT`,"pcm-s32be":`A_PCM/INT/BIG`,"pcm-f32":`A_PCM/FLOAT/IEEE`,"pcm-f64":`A_PCM/FLOAT/IEEE`,webvtt:`S_TEXT/WEBVTT`};function WN(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var GN=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t},KN;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(KN||={});var qN;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(qN||={});var JN;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(JN||={});var YN=[{id:G.SeekHead,flag:`seekHeadSeen`},{id:G.Info,flag:`infoSeen`},{id:G.Tracks,flag:`tracksSeen`},{id:G.Cues,flag:`cuesSeen`}],XN=10*2**20,ZN=class extends gM{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.getCodecParameterString()));return GN({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=LN(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===G.EBML){WN(i);let e=this.reader.requestSlice(a,i);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===G.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===G.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await VN(this.reader,a,jN,this.reader.fileSize)).pos-a);let e=Sk(this.segments);e&&(e.elementEndPos=a+i)}WN(i),e=a+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=n,r=LN(e);if(!r||!AN.includes(r.id)&&r.id!==G.Void){let e=await HN(this.reader,t,AN,Math.min(this.currentSegment.elementEndPos??1/0,t+XN));if(e){n=e;continue}else break}let{id:i,size:a}=r,o=e.filePos,s=YN.findIndex(e=>e.id===i);if(s!==-1){let e=YN[s].flag;this.currentSegment[e]=!0,WN(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===G.Tags||i===G.Attachments){i===G.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,WN(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===G.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=YN.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=LN(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;WN(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,2,16);n instanceof Promise&&(n=await n),U(n);let r=e,i=LN(n);U(i);let a=i.id;U(a===G.Cluster);let o=i.size,s=n.filePos;o===void 0&&(o=(await VN(this.reader,s,jN,t.elementEndPos)).pos-s);let c=this.reader.requestSlice(s,o);c instanceof Promise&&(c=await c);let l={segment:t,elementStartPos:r,elementEndPos:s+o,dataStartPos:s,timestamp:-1,trackData:new Map};this.currentCluster=l,c&&(l.elementEndPos=this.readContiguousElements(c,jN));for(let[,e]of l.trackData){let t=e.track;U(e.blocks.length>0);let n=!1;for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t];r.timestamp+=l.timestamp,n||=r.lacing!==KN.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===KN.None&&(i.duration=t.defaultDuration)}n&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let i=e.blocks[e.presentationTimestamps[0].blockIndex],a=e.blocks[Sk(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=a.timestamp+a.duration;let o=Hk(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(o===-1||t.clusterPositionCache[o].elementStartPos!==r)&&t.clusterPositionCache.splice(o+1,0,{elementStartPos:l.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=l,l}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.lacing===KN.None)continue;r.decoded||=(r.data=this.decodeBlockData(t,r.data),!0);let i=yF.tempFromBytes(r.data),a=[],o=J(i)+1;switch(r.lacing){case KN.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;i.bufferPos<i.length;){let n=J(i);if(t+=n,n<255){a.push(t),e+=t;break}}}a.push(i.length-(i.bufferPos+e))}break;case KN.FixedSize:{let e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)a.push(t)}break;case KN.Ebml:{let e=NN(i);U(e!==null);let t=e;a.push(t);let n=t;for(let e=1;e<o-1;e++){let e=i.bufferPos,r=NN(i);U(r!==null);let o=r-((1<<(i.bufferPos-e)*7-1)-1);t+=o,a.push(t),n+=t}a.push(i.length-(i.bufferPos+n))}break;default:U(!1)}U(a.length===o),e.splice(n,1);let s=r.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let c=a[t],l=q(i,c),u=r.timestamp+s*t/o,d=s/o;e.splice(n+t,0,{timestamp:u,duration:d,isKeyFrame:r.isKeyFrame,data:l,lacing:KN.None,decoded:!0,mainAdditional:r.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===G.Tags&&!e.tagsSeen)&&!(t.id===G.Attachments&&!e.attachmentsSeen))continue;let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(n instanceof Promise&&(n=await n),!n)continue;let r=LN(n);if(!r||r.id!==t.id)continue;let{size:i}=r;WN(i),U(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,i);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===G.Tags?e.tagsSeen=!0:t.id===G.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=LN(e);if(!n||t&&t.includes(n.id))return!1;let{id:r,size:i}=n,a=e.filePos;switch(WN(i),r){case G.DocType:this.isWebM=RN(e,i)===`webm`;break;case G.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(a,i)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case G.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=K(e,i)}break;case G.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=K(e,i)}break;case G.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=K(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case G.Duration:if(!this.currentSegment)break;this.currentSegment.duration=BN(e,i);break;case G.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...AA},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:`und`,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,i)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==qN.Block||e.data.algorithm!==JN.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e)}this.currentTrack.codecId===UN.avc?(this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===UN.hevc?(this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===UN.vp8?this.currentTrack.info.codec=`vp8`:t===UN.vp9?this.currentTrack.info.codec=`vp9`:t===UN.av1&&(this.currentTrack.info.codec=`av1`);let e=this.currentTrack,n=new lN(this.input,new $N(e));this.currentTrack.inputTrack=n,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){t===UN.aac?(this.currentTrack.info.codec=`aac`,this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes(`MPEG2`),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===UN.mp3?this.currentTrack.info.codec=`mp3`:t===UN.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=$A):t===UN.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===UN.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===UN.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===UN.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===`A_PCM/INT/LIT`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32`):this.currentTrack.codecId===`A_PCM/INT/BIG`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16be`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24be`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32be`):this.currentTrack.codecId===`A_PCM/FLOAT/IEEE`&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec=`pcm-f32`:this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec=`pcm-f64`));let e=this.currentTrack,n=new uN(this.input,new eP(e));this.currentTrack.inputTrack=n,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case G.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=K(e,i);break;case G.TrackType:{if(!this.currentTrack)break;let t=K(e,i);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case G.FlagEnabled:if(!this.currentTrack)break;K(e,i)||(this.currentTrack=null);break;case G.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!K(e,i);break;case G.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!K(e,i);break;case G.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!K(e,i);break;case G.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!K(e,i);break;case G.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!K(e,i);break;case G.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!K(e,i);break;case G.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=RN(e,i);break;case G.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=q(e,i);break;case G.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=K(e,i);break;case G.Name:if(!this.currentTrack)break;this.currentTrack.name=zN(e,i);break;case G.Language:if(!this.currentTrack||this.currentTrack.languageCode!==`und`)break;this.currentTrack.languageCode=RN(e,i),sA(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case G.LanguageBCP47:{if(!this.currentTrack)break;let t=RN(e,i).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`}break;case G.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case G.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=K(e,i);break;case G.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=K(e,i);break;case G.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=K(e,i);break;case G.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=K(e,i);break;case G.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=K(e,i);break;case G.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=K(e,i)===1;break;case G.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,i));break;case G.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Fk[K(e,i)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case G.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=K(e,i)===2;break;case G.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Nk[K(e,i)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case G.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=jk[K(e,i)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case G.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case G.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-BN(e,i);try{this.currentTrack.info.rotation=xk(t)}catch{}}break;case G.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(a,i));break;case G.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=BN(e,i);break;case G.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=K(e,i);break;case G.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=K(e,i);break;case G.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,i)),this.currentCueTime=null;break;case G.CueTime:this.currentCueTime=K(e,i);break;case G.CueTrackPositions:{if(this.currentCueTime===null)break;U(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(a,i)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case G.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=K(e,i)}break;case G.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;U(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+K(e,i)}break;case G.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=K(e,i);break;case G.SimpleBlock:{if(!this.currentCluster)break;let t=NN(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=wF(e),o=J(e),s=o>>1&3,c=!!(o&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=q(e,i-(e.filePos-a)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,mainAdditional:null})}break;case G.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,i)),this.currentBlock=null;break;case G.Block:{if(!this.currentCluster)break;let t=NN(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=wF(e),o=J(e)>>1&3;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:q(e,i-(e.filePos-a)),lacing:o,decoded:!(n.track.decodingInstructions.length>0),mainAdditional:null},n.blocks.push(this.currentBlock)}break;case G.BlockAdditions:this.readContiguousElements(e.slice(a,i));break;case G.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case G.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=q(e,i);break;case G.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=K(e,i);break;case G.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=K(e,i);break;case G.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case G.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,i));break;case G.Targets:this.readContiguousElements(e.slice(a,i));break;case G.TargetTypeValue:K(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case G.TagTrackUID:case G.TagEditionUID:case G.TagChapterUID:case G.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case G.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,i));break;case G.TagName:this.currentSimpleTagName=zN(e,i);break;case G.TagString:{if(!this.currentSimpleTagName)break;let t=zN(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case G.TagBinary:{if(!this.currentSimpleTagName)break;let t=q(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case G.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,i));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new OA(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case G.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=PN(e,i);break;case G.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=zN(e,i);break;case G.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=RN(e,i);break;case G.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=q(e,i);break;case G.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=zN(e,i);break;case G.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case G.ContentEncoding:this.currentDecodingInstruction={order:0,scope:qN.Block,data:null},this.readContiguousElements(e.slice(a,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case G.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=K(e,i);break;case G.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=K(e,i);break;case G.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:JN.Zlib,settings:null},this.readContiguousElements(e.slice(a,i));break;case G.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=K(e,i);break;case G.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=q(e,i);break;case G.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`};break}return e.filePos=a+i,!0}decodeBlockData(e,t){U(e.decodingInstructions.length>0);let n=t;for(let t of e.decodingInstructions)switch(U(t.data),t.data.type){case`decompress`:switch(t.data.algorithm){case JN.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length),n=r}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}},QN=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.inputTrack.type,n=0;for(let r of e.segments)for(let e of r.tracks)if(e.inputTrack.type===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return nA(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=Hk(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=Kk(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>n.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return U(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).blocks[t];U(r),r.decoded||=(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),!0);let i=n.metadataOnly?xM:r.data,a=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,s={};r.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(s.alpha=n.metadataOnly?xM:r.mainAdditional,s.alphaByteLength=r.mainAdditional.byteLength);let c=new SM(i,r.isKeyFrame?`key`:`delta`,a,o,e.dataStartPos+t,r.data.byteLength,s);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,n,r,i){let{demuxer:a,segment:o}=this.internalTrack,s=null,c=null,l=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,i);n!==-1&&(c=e,l=n)}let u=Hk(this.internalTrack.cuePoints,n,e=>e.time),d=u===-1?null:this.internalTrack.cuePoints[u],f=Hk(this.internalTrack.clusterPositionCache,n,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.clusterPositionCache[f],m=Math.max(d?.clusterPosition??0,p?.elementStartPos??0)||null,h;for(e?m===null||e.elementStartPos>=m?(h=e.elementEndPos,s=e):h=m:h=m??o.clusterSeekStartPos;o.elementEndPos===null||h<=o.elementEndPos-2;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(h,2,16);if(e instanceof Promise&&(e=await e),!e)break;let n=h,u=LN(e);if(!u||!AN.includes(u.id)&&u.id!==G.Void){let e=await HN(a.reader,n,AN,Math.min(o.elementEndPos??1/0,n+XN));if(e){h=e;continue}else break}let d=u.id,f=u.size,p=e.filePos;if(d===G.Cluster){s=await a.readCluster(n,o),f=s.elementEndPos-p;let{blockIndex:e,correctBlockFound:r}=t(s);if(r)return this.fetchPacketInCluster(s,e,i);e!==-1&&(c=s,l=e)}f===void 0&&(U(d!==G.Cluster),f=(await VN(a.reader,p,jN,o.elementEndPos)).pos-p);let m=p+f;if(o.elementEndPos===null){let e=a.reader.requestSliceRange(m,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(FN(e)===G.Segment){o.elementEndPos=m;break}}h=m}if(d&&(!c||c.elementStartPos<d.clusterPosition)){let e=this.internalTrack.cuePoints[u-1];U(!e||e.time<d.time);let n=e?.time??-1/0;return this.performClusterLookup(null,t,n,r,i)}return c?this.fetchPacketInCluster(c,l,i):null}},$N=class extends QN{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec===`vp9`||this.internalTrack.info.codec===`av1`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:XA({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec===`avc`&&e?Nj(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?Hj(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?Zj(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?$j(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},eP=class extends QN{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:QA({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},tP=async(e,t,n)=>{let r=t;for(;n===null||r<n;){let t=e.requestSlice(r,4);if(t instanceof Promise&&(t=await t),!t)break;let n=vj(Y(t),e.fileSize===null?null:e.fileSize-r);if(n.header)return{header:n.header,startPos:r};r+=n.bytesAdvanced}return null},nP=class extends gM{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Rk,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.tracks=[new uN(this.input,new rP(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=VF(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await tP(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=_j(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let e=Y(r);if(e===1483304551||e===1231971951)return}this.firstFrameHeader||=t,t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return U(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(n instanceof Promise&&(n=await n),!n)break;let r=VF(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;HF(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),U(e),FF(e,3)===`TAG`&&zF(e,this.metadataTags)}return this.metadataTags}finally{e()}}},rP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...AA}}async getDecoderConfig(){return U(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=xM;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=q(e,n.dataSize)}return new SM(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Vk(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Hk(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},iP=79764919,aP=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^iP:t<<1;aP[e]=t>>>0&4294967295}var oP=e=>{let t=Ek(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^aP[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},sP=(e,t,n)=>{let r=0,i=null;if(e.length>0)if(t.codec===`vorbis`){U(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<aA(a-1))-1<<1,s=(e[0]&o)>>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let c=n,l=t.vorbisInfo.modeBlockflags[s];if(i=t.vorbisInfo.blocksizes[l],l===1){let n=(o|1)+1,r=e[0]&n?1:0;c=t.vorbisInfo.blocksizes[r]}r=c===null?0:c+i>>2}else t.codec===`opus`&&(r=nM(e).durationInSamples);return{durationInSamples:r,vorbisBlockSize:i}},cP=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},lP=65307,uP=e=>{let t=e.filePos;if(EF(e)!==1399285583)return null;e.skip(1);let n=J(e),r=MF(e),i=EF(e),a=EF(e),o=EF(e),s=J(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=J(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},dP=(e,t)=>{for(;e.filePos<t-3;){let t=EF(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(!(n!==79&&r!==79&&i!==79&&a!==79)){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1},fP=class extends gM{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let n=uP(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.tracks.push(new uN(this.input,new pP(e,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=Ek(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:rM(i.data).modeBlockflags},oM(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=eM(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=$A,t.codecInfo.opusInfo={preSkip:i.preSkip},oM(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){U(t<e.lacingValues.length);let n=0;for(let r=0;r<t;r++)n+=e.lacingValues[r];let r=e,i=n,a=t,o=[];outer:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);t instanceof Promise&&(t=await t),U(t);let s=q(t,r.dataSize);for(;;){if(a===r.lacingValues.length){o.push(s.subarray(n,i));break}let e=r.lacingValues[a];if(i+=e,e<255){o.push(s.subarray(n,i));break outer}a++}let c=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(c,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let n=uP(t);if(!n)return null;if(r=n,r.serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}n=0,i=0,a=0}let s=o.reduce((e,t)=>e+t.length,0);if(s===0)return null;let c=new Uint8Array(s),l=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,l),l+=t.length}return{data:c,endPage:r,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(e.endPage.headerType&4)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(n instanceof Promise&&(n=await n),!n)return null;let r=uP(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),cP({codecStrings:(await Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},pP=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new Rk,this.internalSampleRate=e.codecInfo.codec===`opus`?$A:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.tracks.findIndex(e=>e._backing.bitstream===this.bitstream);return U(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return U(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...AA}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(U(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=sP(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new SM(n.metadataOnly?xM:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){U(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec===`opus`&&(U(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=nA(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;U(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=r.startPage,a=this.demuxer.reader.fileSize,o=[i];outer:for(;i.headerStartPos+i.totalSize<a;){let e=i.headerStartPos,t=Math.floor((e+a)/2),r=t;for(;;){let e=Math.min(r+lP,a-27),s=this.demuxer.reader.requestSlice(r,e-r);if(s instanceof Promise&&(s=await s),U(s),!dP(s,e)){a=t+27;continue outer}let c=this.demuxer.reader.requestSliceRange(s.filePos,27,282);c instanceof Promise&&(c=await c),U(c);let l=uP(c);U(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);e instanceof Promise&&(e=await e),U(e),u=oP(q(e,l.totalSize))===l.checksum}if(!u){r=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){r=l.headerStartPos+l.totalSize;continue}if(l.granulePosition===-1){r=l.headerStartPos+l.totalSize;continue}this.granulePositionToTimestampInSamples(l.granulePosition)>n?a=l.headerStartPos:(i=l,o.push(l));continue outer}}let s=r.startPage;for(let e of o){if(e.granulePosition===i.granulePosition)break;(!s||e.headerStartPos>s.headerStartPos)&&(s=e)}let c=s,l=[c];for(;!(c.serialNumber===this.bitstream.serialNumber&&c.granulePosition===i.granulePosition);){let e=c.headerStartPos+c.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),U(t);let n=uP(t);U(n),c=n,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}U(c.granulePosition!==-1);let u=null,d,f,p=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{d=0,f=!1;for(let e=c.lacingValues.length-1;e>=0;e--)if(c.lacingValues[e]<255){u=e+1;break}if(u===null)throw Error(`Invalid page with granule position: no packets end on this page.`);m=u-1;let e={data:xM,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){let e=hP(l,c,u);U(e);let t=mP(l,e.page,e.segmentIndex);t&&(c=t.page,u=t.segmentIndex)}else for(;;){let e=hP(l,c,u);if(!e)break;let t=mP(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,u=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,m=e.segmentIndex;break}}}let h=null,g=null;for(;c!==null;){U(u!==null);let e=await this.demuxer.readPacket(c,u);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&u<r.startSegmentIndex)){let r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);U(r);let i=this.encodedPacketToMetadata.get(r);if(U(i),!f&&e.endPage.headerStartPos===p.headerStartPos&&e.endSegmentIndex===m?(d=this.granulePositionToTimestampInSamples(c.granulePosition),f=!0,r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d-i.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),U(r),i=this.encodedPacketToMetadata.get(r),U(i)):d+=i.durationInSamples,h=r,g=i,f&&(Math.max(d,0)>n||Math.max(i.timestampInSamples,0)===n))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;c=i.startPage,u=i.startSegmentIndex}return h}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let n=nA(e*this.internalSampleRate);e=n/this.internalSampleRate;let r=Hk(this.sequentialScanCache,n,e=>e.timestampInSamples),i;if(r!==-1){let e=this.sequentialScanCache[r];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let a=0;for(;i&&i.timestamp<e;){let n=await this.getNextPacket(i,t);if(!n||n.timestamp>e)break;if(i=n,a++,a===100){a=0;let e=this.encodedPacketToMetadata.get(i);U(e),this.sequentialScanCache.length>0&&U(Sk(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},mP=(e,t,n)=>{let r=t,i=n;outer:for(;;){for(i--;i>=0;i--)if(r.lacingValues[i]<255){i++;break outer}if(U(i===-1),!(r.headerType&1)){i=0;break}let t=Gk(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,i=r.lacingValues.length}if(U(i!==-1),i===r.lacingValues.length){let t=e[e.indexOf(r)+1];U(t),r=t,i=0}return{page:r,segmentIndex:i}},hP=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=Gk(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},gP;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(gP||={});var _P=class extends gM{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),U(e);let t=FF(e,4),n=t!==`RIFX`,r=t===`RF64`,i=TF(e,n),a=r?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(FF(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let o=0,s=null,c=e.filePos;for(;a===null||c<a;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;let t=FF(e,4),i=TF(e,n),l=e.filePos;if(r&&o===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(l,i,n);else if(t===`data`){if(s??=i,this.dataStart=e.filePos,this.dataSize=Math.min(s,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(l,i);if(e instanceof Promise&&(e=await e),!e)break;let t=kF(e,n);s=kF(e,n),a=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(l,i,n):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(l,i);c=l+i+(i&1),o++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.tracks.push(new uN(this.input,new yP(this)))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=xF(r,n),a=xF(r,n),o=TF(r,n);r.skip(4);let s=xF(r,n),c;if(c=t===14?8:xF(r,n),t>=18&&i!==357){let e=xF(r,n),a=t-18;if(Math.min(a,e)>=22&&i===gP.EXTENSIBLE){r.skip(6);let e=q(r,16);i=e[0]|e[1]<<8}}(i===gP.MULAW||i===gP.ALAW)&&(c=8),this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=FF(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=FF(r,4),t=TF(r,n),i=q(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s;break}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let r=VF(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&HF(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(U(this.audioInfo),this.audioInfo.format===gP.MULAW)return`ulaw`;if(this.audioInfo.format===gP.ALAW)return`alaw`;if(this.audioInfo.format===gP.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}return this.audioInfo.format===gP.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?`pcm-f32`:null}async getMimeType(){return`audio/wav`}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return U(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},vP=2048,yP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(U(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...AA}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){U(e>=0),U(this.demuxer.audioInfo);let n=e*vP*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let r=Math.min(vP*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);if(e instanceof Promise&&(e=await e),!e)return null}let i;if(t.metadataOnly)i=xM;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);e instanceof Promise&&(e=await e),U(e),i=q(e,r)}let a=e*vP/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new SM(i,`key`,a,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){U(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/vP,(this.demuxer.dataSize-1)/(vP*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let r=await this.getPacketAtIndex(n,t);if(r)return r;if(n===0)return null;U(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){U(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/vP);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},bP=e=>{let t=e.filePos,n=new MA(q(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},xP=1024,SP=class extends gM{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new Rk,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();U(this.firstFrameHeader),this.tracks=[new uN(this.input,new CP(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=VF(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=bP(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let n=NA[t.samplingFrequencyIndex];U(n!==void 0);let r=xP/n,i={timestamp:this.nextTimestampInSamples/n,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(i),this.nextTimestampInSamples+=xP,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return U(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let n=VF(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;HF(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},CP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/xP}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){U(this.demuxer.firstFrameHeader);let e=PA[this.demuxer.firstFrameHeader.channelConfiguration];return U(e!==void 0),e}getSampleRate(){U(this.demuxer.firstFrameHeader);let e=NA[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return U(e!==void 0),e}getDisposition(){return{...AA}}async getDecoderConfig(){return U(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=xM;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=q(e,n.dataSize)}return new SM(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Vk(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Hk(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},wP=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,TP=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},EP=e=>{let t=0,n=new MA(q(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new MA(q(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},DP=(e,t)=>{if(t===`uncommon-u16`)return SF(e)+1;if(t===`uncommon-u8`)return J(e)+1;if(typeof t==`number`)return t;Yk(t),U(!1)},OP=(e,t)=>t===`uncommon-u16`?SF(e):t===`uncommon-u16-10`?SF(e)*10:t===`uncommon-u8`?J(e):typeof t==`number`?t:null,kP=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t},AP=class extends gM{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new Rk,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),U(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),U(this.track),[this.track]}async getMimeType(){return`audio/flac`}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);U(t);let n=J(t),r=CF(t),i=(n&128)!=0;switch(n&127){case aM.STREAMINFO:{let t=this.reader.requestSlice(e,r);if(t instanceof Promise&&(t=await t),U(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let n=q(t,34),i=new MA(n),a=i.readBits(16),o=i.readBits(16),s=i.readBits(24),c=i.readBits(24),l=i.readBits(20),u=i.readBits(3)+1;i.readBits(5);let d=i.readBits(36);i.skipBits(128);let f=new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(n,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:a,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:f},this.track=new uN(this.input,new jP(this));break}case aM.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),U(t),oM(q(t,r),this.metadataTags);break}case aM.PICTURE:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),U(t);let n=Y(t),i=Y(t),a=Dk.decode(q(t,i)),o=Y(t),s=Dk.decode(q(t,o));t.skip(16);let c=Y(t),l=q(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:l,mimeType:a,kind:n===3?`coverFront`:n===4?`coverBack`:`unknown`,description:s});break}default:break}if(e+=r,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){U(this.audioInfo);let n=this.audioInfo.maximumFrameSize+16,r=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,n);if(!r)return null;let i=this.readFlacFrameHeader({slice:r,isFirstPacket:t});if(!i)return null;for(r.filePos=e+this.audioInfo.minimumFrameSize;;){if(r.filePos>r.end-6)return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:r.end-e,isLastFrame:!0};if(J(r)===255){let t=r.filePos;if(J(r)!==(this.blockingBit===1?249:248)){r.filePos=t;continue}r.skip(-2);let n=r.filePos-e,a=this.readFlacFrameHeader({slice:r,isFirstPacket:!1});if(!a){r.filePos=t;continue}if(this.blockingBit===0){if(a.num-i.num!==1){r.filePos=t;continue}}else if(a.num-i.num!==i.blockSize){r.filePos=t;continue}return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,r=new MA(q(e,4));if(r.readBits(15)!==32764)return null;if(this.blockingBit===null)U(t),this.blockingBit=r.readBits(1);else if(this.blockingBit===1){if(U(!t),r.readBits(1)!==1)return null}else if(this.blockingBit===0){if(U(!t),r.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let i=wP(r.readBits(4));if(!i)return null;U(this.audioInfo);let a=TP(r.readBits(4),this.audioInfo.sampleRate);if(!a||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let o=EP(e),s=DP(e,i),c=OP(e,a);if(c===null||c!==this.audioInfo.sampleRate)return null;let l=e.filePos-n,u=J(e);return e.skip(-l),e.skip(-1),u===kP(q(e,l))?{num:o,blockSize:s,sampleRate:c}:null}async advanceReader(){await this.readMetadata(),U(this.lastLoadedPos!==null),U(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(r),t.isLastFrame){this.lastSampleLoaded=!0;return}}},jP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...AA}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return U(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(U(this.demuxer.audioInfo),e<0)throw Error(`Timestamp cannot be negative`);let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Hk(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=xM;else{let e=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;r=q(e,n.byteSize)}U(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new SM(r,`key`,i,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},MP=9e4,NP=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},PP=class extends gM{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.tracks=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),U(e);let t=q(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let n=this.packetOffset,r=null,i=!1,a=!1;for(;;){let e=await this.readPacketHeader(n);if(!e)break;if(e.payloadUnitStartIndicator===0){n+=this.packetStride;continue}let t=await this.readSection(n,!0,!a);if(!t)break;let o=!1;if(!a&&t.pid!==0&&!(t.payload[0]===0&&t.payload[1]===0&&t.payload[2]===1)){let e=new MA(t.payload),n=e.readAlignedByte();e.skipBits(8*n),o=e.readBits(8)===2}if(t.pid===0&&!i){let e=new MA(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(14);let a=e.readBits(10);for(e.skipBits(40);8*(a+3)-e.pos>32;){let t=e.readBits(16);if(e.skipBits(3),t!==0){if(r!==null)throw Error(`Only files with a single program are supported.`);r=e.readBits(13)}}if(r===null)throw Error(`Program Association Table must link to a Program Map Table.`);i=!0}else if((t.pid===r||o)&&!a){let e=new MA(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10);for(e.skipBits(8*i);8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8);t===106?a=!0:(t===122||t===204)&&(o=!0),e.skipBits(8*n)}let s=null;switch(t){case 3:case 4:case 15:s={type:`audio`,codec:t===15?`aac`:`mp3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 27:case 36:s={type:`video`,codec:t===27?`avc`:`hevc`,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 129:s={type:`audio`,codec:`ac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 135:s={type:`audio`,codec:`eac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 6:o?s={type:`audio`,codec:`eac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:a&&(s={type:`audio`,codec:`ac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:console.warn(`Unsupported stream_type 0x${t.toString(16)}; ignoring stream.`)}s&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,info:s,referencePesPackets:[]})}a=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);if(e&&!e.initialized){let n=IP(t);if(!n)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.info.type===`video`)if(e.info.codec===`avc`){if(e.info.avcCodecInfo=Nj(n.data),!e.info.avcCodecInfo)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from first packet.`);let t=e.info.avcCodecInfo.sequenceParameterSets[0];U(t);let r=Lj(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:jk[r.colourPrimaries],transfer:Nk[r.transferCharacteristics],matrix:Fk[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering,e.initialized=!0}else if(e.info.codec===`hevc`){if(e.info.hevcCodecInfo=Hj(n.data),!e.info.hevcCodecInfo)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Cj.SPS_NUT).nalUnits[0];U(t);let r=Vj(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:jk[r.colourPrimaries],transfer:Nk[r.transferCharacteristics],matrix:Fk[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering,e.initialized=!0}else throw Error(`Unhandled.`);else if(e.info.codec===`aac`){let t=bP(yF.tempFromBytes(n.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=PA[t.channelConfiguration],e.info.sampleRate=NA[t.samplingFrequencyIndex],e.initialized=!0}else if(e.info.codec===`mp3`){let t=vj(Y(yF.tempFromBytes(n.data)),n.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.header.channel===3?1:2,e.info.sampleRate=t.header.sampleRate,e.initialized=!0}else if(e.info.codec===`ac3`){let t=cM(n.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=sM[t.acmod]+t.lfeon,e.info.sampleRate=bj[t.fscod],e.initialized=!0}else if(e.info.codec===`eac3`){let t=fM(n.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let r=mM(t);if(r===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=hM(t),e.info.sampleRate=r,e.initialized=!0}else throw Error(`Unhandled.`)}}if(a&&this.elementaryStreams.every(e=>e.initialized))break;n+=this.packetStride}if(!a)throw i?Error(`No Program Map Table found in the file.`):Error(`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.info.type===`video`?this.tracks.push(new lN(this.input,new RP(e))):this.tracks.push(new uN(this.input,new zP(e)))})()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return{}}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMimeType(){await this.readMetadata();let e=await this.getTracks();return NP(await Promise.all(e.map(e=>e.getCodecParameterString())))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(Vk(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=Hk(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(J(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=SF(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=J(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=q(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}},FP=e=>{if(e.payload.byteLength<3)return null;let t=new MA(e.payload);if(t.readBits(24)!==1)return null;let n=t.readBits(8);if(t.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;t.skipBits(8);let r=t.readBits(2);t.skipBits(14);let i=0;if(r===2||r===3)t.skipBits(4),i+=t.readBits(3)*(1<<30),t.skipBits(1),i+=t.readBits(15)*32768,t.skipBits(1),i+=t.readBits(15);else throw Error(`PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:i,randomAccessIndicator:e.randomAccessIndicator}},IP=e=>{U(e.endPos!==null);let t=FP(e);if(!t)return null;let n=new MA(e.payload);n.skipBits(32);let r=n.readBits(16);n.skipBits(16);let i=n.readBits(8),a=n.pos+8*i;n.pos=a;let o=a/8;U(Number.isInteger(o));let s=e.payload.subarray(o,r>0?6+r:e.payload.byteLength);return{...t,data:s}},LP=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,n=this.elementaryStream.info.type,r=0;for(let i of t.tracks)if(i.type===n&&r++,U(i._backing instanceof e),i._backing.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return AA}getTimeResolution(){return MP}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new SM(n.metadataOnly?xM:e.data,r,e.pts/MP,Math.max(t/MP,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;U(t);let n=IP(t);U(n);let r=new HP(this.elementaryStream,n),i=new UP(this,r),a=await i.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,i),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let r=await n.readNext();if(!r)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(i,n),this.packetSectionStarts.set(i,r.packet.sectionStartPos),i}let r=this.packetSectionStarts.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);let i=await this.elementaryStream.demuxer.readSection(r,!0);U(i);let a=IP(i);U(a);let o=new HP(this.elementaryStream,a);n=new UP(this,o);let s=e.sequenceNumber;for(;;){let e=await n.readNext();if(!e)return null;if(e.packet.sequenceNumber>s){let r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,n),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let r=nA(e*MP),i=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=i,s=this.elementaryStream.pid,c=async(e,t)=>{let n=e;for(;n<t;){let e=await i.readPacketHeader(n);if(!e)return null;if(e.pid===s&&e.payloadUnitStartIndicator===1){let e=await i.readSection(n,!1);if(!e)return null;let t=FP(e);if(t)return t}n+=i.packetStride}return null},l=this.elementaryStream.firstSection;U(l);let u=FP(l);if(U(u),r<u.pts)return null;let d,f=this.elementaryStream.referencePesPackets,p=Hk(f,r,e=>e.pts),m=p===-1?null:f[p];if(m&&r-m.pts<9e4/2)d=m.sectionStartPos;else{let e=0;if(a.fileSize!==null){let t=Math.ceil(a.fileSize/o);if(t>1){let n=0,a=t-1;for(e=n;n<=a;){let t=Math.floor((n+a)/2),s=iA(t*o,i.packetStride)+u.sectionStartPos,l=await c(s,s+o);if(!l){a=t-1;continue}l.pts<=r?(e=t,n=t+1):a=t-1}}}d=iA(e*o,i.packetStride)+u.sectionStartPos}let h=await c(d,a.fileSize??1/0);h||=u;let g=this.getReorderSize(),_=async(e,t)=>{let a=await i.readSection(e,!0);U(a);let o=IP(a);U(o);let s=new HP(this.elementaryStream,o),c=new UP(this,s);for(;!((Sk(c.presentationOrderPackets)?.pts??-1/0)>=r||!await c.readNextPacket()););let l=Kk(c.presentationOrderPackets,t);if(l===-1)return null;let u=c.presentationOrderPackets[l],d=l===0?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=d;let f=await c.readNext();U(f);let p=this.createEncodedPacket(f.packet,f.duration,n);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,f.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=h.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=FP(t);if(e){if(e.pts>r)break outer;h=e,BP(this.elementaryStream,e);break}}}e+=i.packetStride}}outer:for(let e=0;e<g;e++){let e=h.sectionStartPos-i.packetStride;for(;e>=i.packetOffset;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=FP(t);if(e){h=e;break}}}e-=i.packetStride}}return _(h.sectionStartPos,e=>e.pts<=r)}else{let e=d,t=null;for(;;){let n=null,l=e<=u.sectionStartPos,d;l?(d=u,n=u):d=await c(e,a.fileSize??1/0);let f=!1,p=0;outer:for(;d&&!(t!==null&&d.sectionStartPos>=t||(d.randomAccessIndicator===1&&d.pts<=r&&(n=d),d.pts>r&&(f=!0),f&&(p++,p>=g)));){let e=d.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t&&(d=FP(t),d)){BP(this.elementaryStream,d);break}}e+=i.packetStride}}if(n){let e=n;if(p===0)outer:for(let t=0;t<g-1;t++){let t=e.sectionStartPos-i.packetStride;for(;t>=i.packetOffset;){let n=await i.readPacketHeader(t);if(!n)break outer;if(n.pid===s&&n.payloadUnitStartIndicator===1){let n=await i.readSection(t,!1);if(n){let t=FP(n);if(t){e=t;break}}}t-=i.packetStride}}let t=await _(e.sectionStartPos,e=>e.pts<=r&&e.randomAccessIndicator===1);return U(t),t}U(!l),t=e,e=Math.max(iA(e-u.sectionStartPos-o,i.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}},RP=class extends LP{constructor(e){super(e),this.elementaryStream=e,this.decoderConfig={codec:XA({width:this.elementaryStream.info.width,height:this.elementaryStream.info.height,codec:this.elementaryStream.info.codec,codecDescription:null,colorSpace:this.elementaryStream.info.colorSpace,avcType:1,avcCodecInfo:this.elementaryStream.info.avcCodecInfo,hevcCodecInfo:this.elementaryStream.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:this.elementaryStream.info.width,codedHeight:this.elementaryStream.info.height,displayAspectWidth:this.elementaryStream.info.squarePixelWidth,displayAspectHeight:this.elementaryStream.info.squarePixelHeight,colorSpace:this.elementaryStream.info.colorSpace}}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return this.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},zP=class extends LP{constructor(e){super(e),this.elementaryStream=e}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return{codec:QA({codec:this.elementaryStream.info.codec,codecDescription:null,aacCodecInfo:this.elementaryStream.info.aacCodecInfo}),numberOfChannels:this.elementaryStream.info.numberOfChannels,sampleRate:this.elementaryStream.info.sampleRate}}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 1}},BP=(e,t)=>{let n=e.referencePesPackets,r=Hk(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0},VP=async e=>{U(!e.suppliedPacket);let t=e.elementaryStream;if(t.info.type===`video`){let n=t.info.codec,r=1024;if(n!==`avc`&&n!==`hevc`)throw Error(`Unhandled.`);let i=null;for(;;){let t=e.ensureBuffered(r);if(t instanceof Promise&&(t=await t),t===0)break;let a=e.currentPos,o=e.readBytes(t),s=o.byteLength,c=0;for(;c<s;){let t=o.indexOf(0,c);if(t===-1||t>=s)break;c=t;let r=a+c;if(c+4>=s){e.seekTo(r);break}let l=o[c+1],u=o[c+2],d=o[c+3],f=0,p=null;if(l===0&&u===0&&d===1?(f=4,p=o[c+4]):l===0&&u===1&&(f=3,p=d),f===0){c++;continue}let m=r;if(i===null){i=m,c+=f;continue}if(p!==null){let t=n===`avc`?Dj(p):Bj(p);if(n===`avc`?t===Sj.AUD:t===Cj.AUD_NUT){let t=m-i;return e.seekTo(i),e.supplyPacket(t,0)}}c+=f}if(t<r)break}if(i!==null){let t=e.endPos-i;return e.seekTo(i),e.supplyPacket(t,0)}}else{let n=t.info.codec;for(;;){let r=e.ensureBuffered(128);r instanceof Promise&&(r=await r);let i=e.currentPos;for(;e.currentPos-i<r;){let r=e.readU8();if(n===`aac`){if(r!==255)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(9);if(i instanceof Promise&&(i=await i),i<9)return;let a=e.readBytes(9),o=bP(yF.tempFromBytes(a));if(o){e.seekTo(n);let r=e.ensureBuffered(o.frameLength);return r instanceof Promise&&(r=await r),e.supplyPacket(r,Math.round(xP*MP/t.info.sampleRate))}else e.seekTo(n+1)}else if(n===`mp3`){if(r!==255)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;let a=vj(Ek(e.readBytes(4)).getUint32(0),null);if(a.header){e.seekTo(n);let r=e.ensureBuffered(a.header.totalSize);r instanceof Promise&&(r=await r);let i=a.header.audioSamplesInFrame*MP/t.info.sampleRate;return e.supplyPacket(r,Math.round(i))}else e.seekTo(n+1)}else if(n===`ac3`){if(r!==11)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=e.readBytes(5);if(a[0]!==11||a[1]!==119){e.seekTo(n+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){e.seekTo(n+1);continue}let c=lM[3*s+o];U(c!==void 0),e.seekTo(n),i=e.ensureBuffered(c),i instanceof Promise&&(i=await i);let l=Math.round(uM*MP/t.info.sampleRate);return e.supplyPacket(i,l)}else if(n===`eac3`){if(r!==11)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=e.readBytes(5);if(a[0]!==11||a[1]!==119){e.seekTo(n+1);continue}let o=(((a[2]&7)<<8|a[3])+1)*2,s=dM[a[4]>>6==3?3:a[4]>>4&3];e.seekTo(n),i=e.ensureBuffered(o),i instanceof Promise&&(i=await i);let c=s*256,l=Math.round(c*MP/t.info.sampleRate);return e.supplyPacket(i,l)}else throw Error(`Unhandled.`)}if(r<128)break}}},HP=class e{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.nextPts=0,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}clone(){let t=new e(this.elementaryStream,this.startingPesPacket);return t.currentPos=this.currentPos,t.pesPackets=[...this.pesPackets],t.currentPesPacketIndex=this.currentPesPacketIndex,t.currentPesPacketPos=this.currentPesPacketPos,t.endPos=this.endPos,t.nextPts=this.nextPts,t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return U(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=Sk(this.pesPackets).sectionEndPos;for(U(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=IP(n);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength,this.pesPackets.length===1&&(this.nextPts=e.pts)}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength,this.nextPts=e.pts}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}supplyPacket(e,t){let n=this.getCurrentPesPacket();BP(this.elementaryStream,n);let r=this.nextPts;this.nextPts+=t;let i=n.sectionStartPos,a=i+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),s=n.randomAccessIndicator;U(this.elementaryStream.firstSection),n.sectionStartPos===this.elementaryStream.firstSection.startPos&&(s=1),this.suppliedPacket={pts:r,data:o,sequenceNumber:a,sectionStartPos:i,randomAccessIndicator:s},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},UP=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),U(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);U(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await VP(this.context),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(U(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>=this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer.splice(e,1)[0];this.presentationOrderPackets.push(t)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},WP=class{},GP=class extends WP{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),FF(t,4)!==`ftyp`)?null:FF(t,4)}_createDemuxer(e){return new vN(e)}},KP=class extends GP{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!==`qt `}get name(){return`MP4`}get mimeType(){return`video/mp4`}},qP=class extends GP{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},JP=class extends WP{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=MN(n);if(r===null||r<1||r>8||K(n,r)!==G.EBML)return!1;let i=IN(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=LN(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case G.EBMLVersion:if(K(a,r)!==1)return!1;break;case G.EBMLReadVersion:if(K(a,r)!==1)return!1;break;case G.DocType:if(RN(a,r)!==t)return!1;break;case G.DocTypeVersion:if(K(a,r)>4)return!1;break}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new ZN(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},YP=class extends JP{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},XP=class extends WP{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=VF(n);if(!r)break;t=n.filePos+r.size}let n=await tP(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=_j(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=Y(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await tP(e._reader,t,t+4);if(!s)return!1;let c=s.header;return!(r.channel!==c.channel||r.sampleRate!==c.sampleRate)}_createDemuxer(e){return new nP(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},ZP=class extends WP{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=FF(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),FF(t,4)===`WAVE`)}_createDemuxer(e){return new _P(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},QP=class extends WP{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?FF(t,4)===`OggS`:!1}_createDemuxer(e){return new fP(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},$P=class extends WP{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?FF(t,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new AP(e)}},eF=class extends WP{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=VF(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(n instanceof Promise&&(n=await n),!n)return!1;let r=bP(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=bP(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new SP(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},tF=class extends WP{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=q(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(e){return new PP(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},nF=new KP,rF=new qP,iF=new JP,aF=new YP,oF=new XP,sF=new ZP,cF=new QP,lF=new eF,uF=[nF,rF,iF,aF,sF,cF,new $P,oF,lF,new tF];n(e(((e,t)=>{t.exports={}}))(),1);var dF=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new _F;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new _F;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}},fF=class extends dF{constructor(e,t={}){if(!(e instanceof Blob))throw TypeError(`blob must be a Blob.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!wA(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new hF({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:mF.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);for(t===void 0&&(t=(`stream`in this._blob)&&!fA()?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:r}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),Error(`Blob reader stopped unexpectedly before all requested data was read.`);if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else{let t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},pF=.5*2**20,mF={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{let n=2**16;return e=Math.floor((e-n)/n)*n,t=Math.ceil((t+n)/n)*n,{start:e,end:t}},network:(e,t,n)=>{let r=2**16;e=Math.max(0,Math.floor((e-r)/r)*r);for(let r of n){let n=8*2**20,i=Math.max((r.startPos+r.targetPos)/2,r.targetPos-n);if(bA(e,t,i,r.targetPos)){let e=r.targetPos-r.startPos,i=Math.ceil((e+1)/n)*n,a=2**Math.ceil(Math.log2(e+1)),o=Math.min(a,i);t=Math.max(t,r.startPos+o)}}return t=Math.max(t,e+pF),{start:e,end:t}}},hF=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){U(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),r=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);U(r<=e&&t<=i);let a=null,o=Hk(this.cache,e,e=>e.start),s=o===-1?null:this.cache[o];s&&s.start<=e&&t<=s.end&&(s.age=this.nextAge++,a={bytes:s.bytes,view:s.view,offset:s.start});let c=Hk(this.cache,r,e=>e.start),l=a?null:new Uint8Array(t-e),u=0,d=r,f=[];if(c!==-1){for(let n=c;n<this.cache.length;n++){let a=this.cache[n];if(a.start>=i)break;if(a.end<=r)continue;let o=Math.max(r,a.start),s=Math.min(i,a.end);if(U(o<=s),d<o&&f.push({start:d,end:o}),d=s,l){let n=Math.max(e,a.start),r=Math.min(t,a.end);if(n<r){let t=n-e;l.set(a.bytes.subarray(n-a.start,r-a.start),t),t===u&&(u=r-e)}}a.age=this.nextAge++}d<i&&f.push({start:d,end:i})}else f.push({start:r,end:i});if(l&&u>=l.length&&(a={bytes:l,view:Ek(l),offset:e}),f.length===0)return U(a),a;let{promise:p,resolve:m,reject:h}=Wk(),g=[];for(let n of f){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?g.push(n):r<i&&g.push({start:r,end:i})}for(let t of f){let n=l&&{start:e,bytes:l,holes:g,resolve:m,reject:h},r=!1;for(let e of this.workers)if(bA(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),r=!0,n&&!e.pendingSlices.includes(n)&&e.pendingSlices.push(n),e.running||this.runWorker(e);break}if(!r){let e=this.createWorker(t.start,t.end);n&&(e.pendingSlices=[n]),this.runWorker(e)}}return a||=(U(l),p.then(t=>({bytes:t,view:Ek(t),offset:e}))),a}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let n=1;n<this.workers.length;n++){let r=this.workers[n];r.age<t.age&&(e=n,t=r)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return n}runWorker(e){U(!e.running),U(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){U(!e.aborted);let n=e.currentPos,r=n+t.length;this.insertIntoCache({start:n,end:r,bytes:t,view:Ek(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let a=e.pendingSlices[i],o=Math.max(n,a.start),s=Math.min(r,a.start+a.bytes.length);o<s&&a.bytes.set(t.subarray(o-n,s-n),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];n<=t.start&&r>t.start&&(t.start=r),t.end<=t.start&&(a.holes.splice(e,1),e--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;t<this.workers.length;t++){let i=this.workers[t];e===i||i.running||bA(n,r,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){let t=this.workers.indexOf(e);U(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=Hk(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=Ek(r),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=Ek(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};CA();var gF=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof WP)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(e.source instanceof dF))throw TypeError(`options.source must be a Source.`);if(e.source._disposed)throw Error(`options.source must not be disposed.`);this._formats=e.formats,this._source=e.source,this._reader=new vF(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error(`Input has an unsupported or unrecognizable format.`)})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),U(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();if(e.length===0)return 0;let t=await Promise.all(e.map(e=>e.getFirstTimestamp()));return Math.min(...t)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},_F=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},vF=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new _F;if(e<0||this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,r=this.source._read(e,n);return r instanceof Promise?r.then(t=>t?new yF(t.bytes,t.view,t.offset,e,n):null):r?new yF(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new _F;if(e<0)return null;if(this.fileSize!==null)return this.requestSlice(e,tA(this.fileSize-e,t,n));{let r=this.requestSlice(e,n),i=r=>{if(r)return r;let i=r=>(U(r!==null),this.requestSlice(e,tA(r-e,t,n))),a=this.source._retrieveSize();return a instanceof Promise?a.then(i):i(a)};return r instanceof Promise?r.then(i):i(r)}}},yF=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,Ek(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},bF=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},q=(e,t)=>{bF(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},J=e=>(bF(e,1),e.view.getUint8(e.bufferPos++)),xF=(e,t)=>{bF(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},SF=e=>{bF(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},CF=e=>{bF(e,3);let t=Xk(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},wF=e=>{bF(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},TF=(e,t)=>{bF(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},Y=e=>{bF(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},EF=e=>{bF(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},DF=e=>{bF(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},OF=e=>{bF(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},kF=(e,t)=>{let n,r;return t?(n=TF(e,!0),r=TF(e,!0)):(r=TF(e,!1),n=TF(e,!1)),r*4294967296+n},AF=e=>{let t=Y(e),n=Y(e);return t*4294967296+n},jF=e=>{let t=DF(e),n=Y(e);return t*4294967296+n},MF=e=>{let t=EF(e);return OF(e)*4294967296+t},NF=e=>{bF(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},PF=e=>{bF(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},FF=(e,t)=>{bF(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},IF;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(IF||={});var LF;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(LF||={});var RF=`Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),zF=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=q(e,125),e.filePos=n;let r=BF(e,30);r&&(t.title??=r);let i=BF(e,30);i&&(t.artist??=i);let a=BF(e,30);a&&(t.album??=a);let o=BF(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(s,0,1));let c=q(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=BF(e,28),e.skip(2)}else e.skip(-30),l=BF(e,30);l&&(t.comment??=l);let u=J(e);u<RF.length&&(t.genre??=RF[u])},BF=(e,t)=>{let n=q(e,t),r=yA(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},VF=e=>{let t=e.filePos,n=FF(e,3),r=J(e),i=J(e),a=J(e),o=Y(e);return n!==`ID3`||r===255||i===255||o&2155905152?(e.filePos=t,null):{majorVersion:r,revision:i,flags:a,size:yj(o)}},HF=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new UF(t,q(e,t.size));if(t.flags&IF.Footer&&r.removeFooter(),t.flags&IF.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&IF.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&IF.Unsynchronisation)),o){console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){console.warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}switch(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size),r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(RF[e]!==void 0){n.genre??=RF[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(RF[e]!==void 0){n.genre??=RF[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(t,0,1))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size;break}r.pos=a}},UF=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}else{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?yj(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:yj(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case LF.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case LF.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=yA(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else if(r[0]===254&&r[1]===255){let e=new TextDecoder(`utf-16be`),t=yA(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else{let e=yA(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Dk.decode(r.subarray(0,e))}case LF.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=yA(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case LF.UTF_8:{let e=yA(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Dk.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},WF=class{constructor(e){this.mutex=new Rk,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,n){if(t+=e.source._timestampOffset,t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}return t}},GF=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,KF=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},qF=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);U(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},X=new Uint8Array(8),JF=new DataView(X.buffer),YF=e=>[(e%256+256)%256],Z=e=>(JF.setUint16(0,e,!1),[X[0],X[1]]),XF=e=>(JF.setInt16(0,e,!1),[X[0],X[1]]),ZF=e=>(JF.setUint32(0,e,!1),[X[1],X[2],X[3]]),Q=e=>(JF.setUint32(0,e,!1),[X[0],X[1],X[2],X[3]]),QF=e=>(JF.setInt32(0,e,!1),[X[0],X[1],X[2],X[3]]),$F=e=>(JF.setUint32(0,Math.floor(e/2**32),!1),JF.setUint32(4,e,!1),[X[0],X[1],X[2],X[3],X[4],X[5],X[6],X[7]]),eI=e=>(JF.setInt16(0,2**8*e,!1),[X[0],X[1]]),tI=e=>(JF.setInt32(0,2**16*e,!1),[X[0],X[1],X[2],X[3]]),nI=e=>(JF.setInt32(0,2**30*e,!1),[X[0],X[1],X[2],X[3]]),rI=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},iI=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},aI=e=>{let t=null;for(let n of e)(!t||n.timestamp>t.timestamp)&&(t=n);return t},oI=e=>{let t=e*(Math.PI/180),n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},sI=oI(0),cI=e=>[tI(e[0]),tI(e[1]),nI(e[2]),tI(e[3]),tI(e[4]),nI(e[5]),tI(e[6]),tI(e[7]),nI(e[8])],$=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),lI=(e,t,n,r,i)=>$(e,[YF(t),ZF(n),r??[]],i),uI=e=>e.isQuickTime?$(`ftyp`,[iI(`qt `),Q(512),iI(`qt `)]):e.fragmented?$(`ftyp`,[iI(`iso5`),Q(512),iI(`iso5`),iI(`iso6`),iI(`mp41`)]):$(`ftyp`,[iI(`isom`),Q(512),iI(`isom`),e.holdsAvc?iI(`avc1`):[],iI(`mp41`)]),dI=e=>({type:`mdat`,largeSize:e}),fI=e=>({type:`free`,size:e}),pI=e=>$(`moov`,void 0,[mI(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>hI(t,e.creationTime)),e.isFragmented?tL(e.trackDatas):null,gL(e)]),mI=(e,t)=>{let n=HL(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{let t=aI(e.samples);return t.timestamp+t.duration})),zL),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!Ck(e)||!Ck(n),a=i?$F:Q;return lI(`mvhd`,+i,0,[a(e),a(e),Q(zL),a(n),tI(1),eI(1),Array(10).fill(0),cI(sI),Array(24).fill(0),Q(r)])},hI=(e,t)=>{let n=VL(e);return $(`trak`,void 0,[gI(e,t),_I(e,t),n.name===void 0?null:$(`udta`,void 0,[$(`name`,[...Ok.encode(n.name)])])])},gI=(e,t)=>{let n=aI(e.samples),r=HL(n?n.timestamp+n.duration:0,zL),i=!Ck(t)||!Ck(r),a=i?$F:Q,o;if(e.type===`video`){let t=e.track.metadata.rotation;o=oI(t??0)}else o=sI;let s=2;return e.track.metadata.disposition?.default!==!1&&(s|=1),lI(`tkhd`,+i,s,[a(t),a(t),Q(e.track.id),Q(0),a(r),Array(8).fill(0),Z(0),Z(e.track.id),eI(e.type===`audio`?1:0),Z(0),cI(o),tI(e.type===`video`?e.info.width:0),tI(e.type===`video`?e.info.height:0)])},_I=(e,t)=>$(`mdia`,void 0,[vI(e,t),xI(!0,yI[e.type],bI[e.type]),SI(e)]),vI=(e,t)=>{let n=aI(e.samples),r=HL(n?n.timestamp+n.duration:0,e.timescale),i=!Ck(t)||!Ck(r),a=i?$F:Q;return lI(`mdhd`,+i,0,[a(t),a(t),Q(e.timescale),a(r),Z(AL(e.track.metadata.languageCode??`und`)),Z(0)])},yI={video:`vide`,audio:`soun`,subtitle:`text`},bI={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},xI=(e,t,n,r=`\0\0\0\0`)=>lI(`hdlr`,0,0,[e?iI(`mhlr`):Q(0),iI(t),iI(r),Q(0),Q(0),iI(n,!0)]),SI=e=>$(`minf`,void 0,[CI[e.type](),wI(),DI(e)]),CI={video:()=>lI(`vmhd`,0,1,[Z(0),Z(0),Z(0),Z(0)]),audio:()=>lI(`smhd`,0,0,[Z(0),Z(0)]),subtitle:()=>lI(`nmhd`,0,0)},wI=()=>$(`dinf`,void 0,[TI()]),TI=()=>lI(`dref`,0,0,[Q(1)],[EI()]),EI=()=>lI(`url `,0,1),DI=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return $(`stbl`,void 0,[OI(e),JI(e),t?$I(e):null,t?eL(e):null,XI(e),ZI(e),QI(e),YI(e)])},OI=e=>{let t;if(e.type===`video`)t=kI(wL(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=EL(e.track.source._codec,e.muxer.isQuickTime);U(n),t=II(n,e)}else e.type===`subtitle`&&(t=KI(OL[e.track.source._codec],e));return U(t),lI(`stsd`,0,0,[Q(1)],[t])},kI=(e,t)=>$(e,[[,,,,,,].fill(0),Z(1),Z(0),Z(0),Array(12).fill(0),Z(t.info.width),Z(t.info.height),Q(4718592),Q(4718592),Q(0),Z(1),Array(32).fill(0),Z(24),XF(65535)],[TL[t.track.source._codec](t),AI(t),Ik(t.info.decoderConfig.colorSpace)?jI(t):null]),AI=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:$(`pasp`,[Q(e.info.pixelAspectRatio.num),Q(e.info.pixelAspectRatio.den)]),jI=e=>$(`colr`,[iI(`nclx`),Z(Ak[e.info.decoderConfig.colorSpace.primaries]),Z(Mk[e.info.decoderConfig.colorSpace.transfer]),Z(Pk[e.info.decoderConfig.colorSpace.matrix]),YF((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),MI=e=>e.info.decoderConfig&&$(`avcC`,[...Tk(e.info.decoderConfig.description)]),NI=e=>e.info.decoderConfig&&$(`hvcC`,[...Tk(e.info.decoderConfig.description)]),PI=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?Ak[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Mk[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Pk[t.colorSpace.matrix]:2;return lI(`vpcC`,1,0,[YF(r),YF(i),YF(c),YF(l),YF(u),YF(d),Z(0)])},FI=e=>$(`av1C`,YA(e.info.decoderConfig.codec)),II=(e,t)=>{let n=0,r,i=16,a=RA.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=tj(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),Z(1),Z(n),Z(0),Q(0),Z(t.info.numberOfChannels),Z(i),Z(0),Z(0),Z(t.info.sampleRate<2**16?t.info.sampleRate:0),Z(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),Z(1),Z(n),Z(0),Q(0),Z(t.info.numberOfChannels),Z(Math.min(i,16)),XF(e),Z(0),Z(t.info.sampleRate<2**16?t.info.sampleRate:0),Z(0),a?[Q(1),Q(i/8),Q(t.info.numberOfChannels*i/8)]:[Q(0),Q(0),Q(0)],Q(2)]}return $(e,r,[DL(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},LI=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...YF(t),...YF(21),...ZF(0),...Q(0),...Q(0)];if(e.info.decoderConfig.description){let t=Tk(e.info.decoderConfig.description);n=[...n,...YF(5),...rI(t.byteLength),...t]}return n=[...Z(1),...YF(0),...YF(4),...rI(n.length),...n,...YF(6),...YF(1),...YF(2)],n=[...YF(3),...rI(n.length),...n],lI(`esds`,0,0,n)},RI=e=>$(`wave`,void 0,[zI(e),BI(e),$(`\0\0\0\0`)]),zI=e=>$(`frma`,[iI(EL(e.track.source._codec,e.muxer.isQuickTime))]),BI=e=>{let{littleEndian:t}=tj(e.track.source._codec);return $(`enda`,[Z(+t)])},VI=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){U(s.byteLength>=18);let e=eM(Tk(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return $(`dOps`,[YF(0),YF(t),Z(n),Q(r),XF(i),YF(a),...o])},HI=e=>{let t=e.info.decoderConfig?.description;return U(t),lI(`dfLa`,0,0,[...Tk(t).subarray(4)])},UI=e=>{let{littleEndian:t,sampleSize:n}=tj(e.track.source._codec);return lI(`pcmC`,0,0,[YF(+t),YF(8*n)])},WI=e=>{let t=cM(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new MA(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),$(`dac3`,[...n])},GI=e=>{let t=fM(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new MA(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return $(`dec3`,[...i])},KI=(e,t)=>$(e,[[,,,,,,].fill(0),Z(1)],[kL[t.track.source._codec](t)]),qI=e=>$(`vttC`,[...Ok.encode(e.info.config.description)]),JI=e=>lI(`stts`,0,0,[Q(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Q(e.sampleCount),Q(e.sampleDelta)])]),YI=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return lI(`stss`,0,0,[Q(t.length),t.map(([e])=>Q(e+1))])},XI=e=>lI(`stsc`,0,0,[Q(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Q(e.firstChunk),Q(e.samplesPerChunk),Q(1)])]),ZI=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=tj(e.track.source._codec);return lI(`stsz`,0,0,[Q(t*e.info.numberOfChannels),Q(e.samples.reduce((t,n)=>t+HL(n.duration,e.timescale),0))])}return lI(`stsz`,0,0,[Q(0),Q(e.samples.length),e.samples.map(e=>Q(e.size))])},QI=e=>e.finalizedChunks.length>0&&Sk(e.finalizedChunks).offset>=2**32?lI(`co64`,0,0,[Q(e.finalizedChunks.length),e.finalizedChunks.map(e=>$F(e.offset))]):lI(`stco`,0,0,[Q(e.finalizedChunks.length),e.finalizedChunks.map(e=>Q(e.offset))]),$I=e=>lI(`ctts`,1,0,[Q(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Q(e.sampleCount),QF(e.sampleCompositionTimeOffset)])]),eL=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;U(e.compositionTimeOffsetTable.length>0),U(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,HL(n.timestamp,e.timescale)),i=Math.max(i,HL(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:lI(`cslg`,0,0,[QF(a),QF(t),QF(n),QF(r),QF(i)])},tL=e=>$(`mvex`,void 0,e.map(nL)),nL=e=>lI(`trex`,0,0,[Q(e.track.id),Q(1),Q(0),Q(0),Q(0)]),rL=(e,t)=>$(`moof`,void 0,[iL(e),...t.map(oL)]),iL=e=>lI(`mfhd`,0,0,[Q(e)]),aL=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},oL=e=>$(`traf`,void 0,[sL(e),cL(e),lL(e)]),sL=e=>{U(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:aL(n)};return lI(`tfhd`,0,t,[Q(e.track.id),Q(r.duration),Q(r.size),Q(r.flags)])},cL=e=>(U(e.currentChunk),lI(`tfdt`,1,0,[$F(HL(e.currentChunk.startTimestamp,e.timescale))])),lL=e=>{U(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(aL),i=e.currentChunk.samples.map(t=>HL(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,lI(`trun`,1,m,[Q(e.currentChunk.samples.length),Q(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?Q(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?Q(t[a]):[],d?Q(n[a]):[],f?Q(r[a]):[],p?QF(i[a]):[]])])},uL=e=>$(`mfra`,void 0,[...e.map(dL),fL()]),dL=(e,t)=>lI(`tfra`,1,0,[Q(e.track.id),Q(63),Q(e.finalizedChunks.length),e.finalizedChunks.map(n=>[$F(HL(n.samples[0].timestamp,e.timescale)),$F(n.moofOffset),Q(t+1),Q(1),Q(1)])]),fL=()=>lI(`mfro`,0,0,[Q(0)]),pL=()=>$(`vtte`),mL=(e,t,n,r,i)=>$(`vttc`,void 0,[i===null?null:$(`vsid`,[QF(i)]),n===null?null:$(`iden`,[...Ok.encode(n)]),t===null?null:$(`ctim`,[...Ok.encode(KF(t))]),r===null?null:$(`sttg`,[...Ok.encode(r)]),$(`payl`,[...Ok.encode(e)])]),hL=e=>$(`vtta`,[...Ok.encode(e)]),gL=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=xL(r);e&&t.push(e)}else if(n===`mdta`){let e=SL(r);e&&t.push(e)}else (n===`udta`||n===`auto`&&e.isQuickTime)&&_L(t,e.output._metadataTags);return t.length===0?null:$(`udta`,void 0,t)},_L=(e,t)=>{for(let{key:n,value:r}of xA(t))switch(n){case`title`:e.push(vL(`©nam`,r));break;case`description`:e.push(vL(`©des`,r));break;case`artist`:e.push(vL(`©ART`,r));break;case`album`:e.push(vL(`©alb`,r));break;case`albumArtist`:e.push(vL(`albr`,r));break;case`genre`:e.push(vL(`©gen`,r));break;case`date`:e.push(vL(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(vL(`©cmt`,r));break;case`lyrics`:e.push(vL(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:Yk(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(vL(n,r)):r instanceof Uint8Array&&e.push($(n,Array.from(r))))}},vL=(e,t)=>{let n=Ok.encode(t);return $(e,[Z(n.length),Z(AL(`und`)),Array.from(n)])},yL={"image/jpeg":13,"image/png":14,"image/bmp":27},bL=(e,t)=>{let n=[];for(let{key:r,value:i}of xA(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:CL(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:CL(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:CL(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:CL(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:CL(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:CL(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:CL(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:CL(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:CL(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:$(`data`,[Q(yL[e.mimeType]??0),Q(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:CL(t)})}else n.push({key:`trkn`,value:$(`data`,[Q(0),Q(0),Z(0),Z(i),Z(e.tracksTotal??0),Z(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:$(`data`,[Q(0),Q(0),Z(0),Z(i),Z(e.discsTotal??0),Z(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:Yk(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:CL(i)}):i instanceof Uint8Array?n.push({key:r,value:$(`data`,[Q(0),Q(0),Array.from(i)])}):i instanceof DA&&n.push({key:r,value:$(`data`,[Q(yL[i.mimeType]??0),Q(0),Array.from(i.data)])}))}return n},xL=e=>{let t=bL(e,!1);return t.length===0?null:lI(`meta`,0,0,void 0,[xI(!1,`mdir`,``,`appl`),$(`ilst`,void 0,t.map(e=>$(e.key,void 0,[e.value])))])},SL=e=>{let t=bL(e,!0);return t.length===0?null:$(`meta`,void 0,[xI(!1,`mdta`,``),lI(`keys`,0,0,[Q(t.length)],t.map(e=>$(`mdta`,[...Ok.encode(e.key)]))),$(`ilst`,void 0,t.map((e,t)=>$(String.fromCharCode(...Q(t+1)),void 0,[e.value])))])},CL=e=>$(`data`,[Q(1),Q(0),...Ok.encode(e)]),wL=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},TL={avc:MI,hevc:NI,vp8:PI,vp9:PI,av1:FI},EL=(e,t)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`}if(t)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},DL=(e,t)=>{switch(e){case`aac`:return LI;case`mp3`:return LI;case`opus`:return VI;case`vorbis`:return LI;case`flac`:return HI;case`ac3`:return WI;case`eac3`:return GI}if(t)switch(e){case`pcm-s24`:return RI;case`pcm-s24be`:return RI;case`pcm-s32`:return RI;case`pcm-s32be`:return RI;case`pcm-f32`:return RI;case`pcm-f32be`:return RI;case`pcm-f64`:return RI;case`pcm-f64be`:return RI}else switch(e){case`pcm-s16`:return UI;case`pcm-s16be`:return UI;case`pcm-s24`:return UI;case`pcm-s24be`:return UI;case`pcm-s32`:return UI;case`pcm-s32be`:return UI;case`pcm-f32`:return UI;case`pcm-f32be`:return UI;case`pcm-f64`:return UI;case`pcm-f64be`:return UI}return null},OL={webvtt:`wvtt`},kL={webvtt:qI},AL=e=>{U(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},jL=class{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},ML=2**16,NL=2**32,PL=class extends jL{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize=`resize`in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(ML,{maxByteLength:NL})}catch{this.buffer=new ArrayBuffer(ML),this.supportsResize=!1}else this.buffer=new ArrayBuffer(ML);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>NL)throw Error(`ArrayBuffer exceeded maximum size of ${NL} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this.bytes,0),this.buffer=e,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}},FL=class extends jL{constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}},IL=class{constructor(){this._output=null,this.onwrite=null}},LL=class extends IL{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new PL(this)}},RL=class extends IL{_createWriter(){return new FL(this)}},zL=1e3,BL=2082844800,VL=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},HL=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},UL=class extends WF{constructor(e,t){super(e),this.auxTarget=new LL,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new qF(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=Wk(),this.creationTime=Math.floor(Date.now()/1e3)+BL,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new qF(this.writer),this.isQuickTime=t instanceof qL;let n=this.writer instanceof PL?`in-memory`:!1;this.fastStart=t._options.fastStart??n,this.isFragmented=this.fastStart===`fragmented`,(this.fastStart===`in-memory`||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),t=this.output._tracks.some(e=>e.type===`video`&&e.source._codec===`avc`);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(uI({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}if(this.ftypSize=this.writer.getPos(),this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=dI(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return dN({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;uj(n),U(n),U(n.decoderConfig);let i={...n.decoderConfig};U(i.codedWidth!==void 0),U(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){let e=Nj(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Pj(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){let e=Hj(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=Xj(e),a=!0}let o=lA(1/(e.metadata.frameRate??57600),1e6).denominator,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:TA({num:s*i.codedHeight,den:c*i.codedWidth}),u={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;fj(n),U(n),U(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=bP(yF.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=NA[e.samplingFrequencyIndex],r=PA[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=IA({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&RA.includes(e.source._codec),requiresAdtsStripping:a,firstPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;pj(t),U(t),U(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...wj(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=jj(e,4)}let a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type===`key`),o=this.createSampleForTrack(r,i,a,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=bP(yF.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}let a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type===`key`),o=this.createSampleForTrack(r,i,a,t.duration,t.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,o)}finally{r()}}async maybePadWithSilence(e,t){let n=Sk(e.samples),r=n?n.timestamp+n.duration:0,i=t-r,a=HL(i,e.timescale);if(a>0){let{sampleSize:t,silentValue:n}=tj(e.info.decoderConfig.codec),o=a*e.info.numberOfChannels,s=new Uint8Array(t*o).fill(n),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),r,i,`key`);await this.registerSample(e,c)}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)U(r.timestamp<=t),U(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=pL();this.auxBoxWriter.writeBox(t);let n=this.auxWriter.getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;GF.lastIndex=0;let r=GF.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=hL(n.notes);this.auxBoxWriter.writeBox(e)}let c=mL(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:HL(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=HL(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=Sk(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t],!this.isFragmented&&e.lastTimescaleUnits===null&&(r.decodeTimestamp=0);let i=HL(r.timestamp-r.decodeTimestamp,e.timescale),a=HL(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){U(e.lastSample);let t=HL(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(U(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=Sk(e.timeToSampleTable);if(U(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=Sk(e.compositionTimeOffsetTable);U(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=HL(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,U(e.lastSample),U(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){U(t.type===`key`);let n=HL(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(U(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.track.source._closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),U(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(U(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+HL(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||Sk(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)U(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(U(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.track.source._closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!0){U(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let e=pI(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}let n=this.trackDatas.filter(e=>e.currentChunk),r=rL(t,n),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e of n){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(let t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of n)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=rL(t,n);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}U(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let d=dI(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){let e=pI(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;U(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=dI(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){U(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;U(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)await this.finalizeCurrentChunk(e);if(this.fastStart===`in-memory`){this.mdat=dI(!1);let e;for(let t=0;t<2;t++){let t=pI(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)U(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=pI(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)U(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){let e=this.writer.getPos(),t=uL(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{U(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);U(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let n=pI(this);if(this.fastStart===`reserve`){U(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(fI(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},WL=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>LA.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>BA.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>VA.includes(e))}_codecUnsupportedHint(e){return``}},GL=class extends WL{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new UL(e,this)}},KL=class extends GL{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...LA,...zA,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...VA]}_codecUnsupportedHint(e){return new qL().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},qL=class extends GL{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...LA,...BA]}_codecUnsupportedHint(e){return new KL().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},JL=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!LA.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${LA.join(`, `)}.`);if(!(e.bitrate instanceof eR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedChunk, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);YL(e.codec,e)},YL=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&nj(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},XL=e=>{let t=e.bitrate instanceof eR?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??JA(e.codec,e.width,e.height,t),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...rj(e.codec)}},ZL=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!BA.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${BA.join(`, `)}.`);if(e.bitrate===void 0&&(!RA.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.bitrate must be provided for compressed audio codecs.`);if(e.bitrate!==void 0&&!(e.bitrate instanceof eR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedChunk, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);QL(e.codec,e)},QL=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&nj(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},$L=e=>{let t=e.bitrate instanceof eR?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??ZA(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...ij(e.codec)}},eR=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let r=3e6*(t*n/(1920*1080))**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[e]*this._factor;return Math.ceil(r/1e3)*1e3}_toAudioBitrate(e){if(RA.includes(e)||e===`flac`)return;let t={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!t)throw Error(`Unhandled codec: ${e}`);let n=t*this._factor;return e===`aac`?n=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e):e===`opus`||e===`vorbis`?n=Math.max(6e3,n):e===`mp3`&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e)),Math.round(n/1e3)*1e3}},tR=new eR(2),nR=async(e,t={})=>{let{width:n=1280,height:r=720,bitrate:i=1e6,...a}=t;if(!LA.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(!(i instanceof eR)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);YL(e,a);let o=null;return yM.length>0&&(o??=XL({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a}),yM.some(t=>t.supports(e,o)))?!0:typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`)||(o??=XL({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a,alpha:`discard`}),!(await VideoEncoder.isConfigSupported(o)).supported)?!1:mA()?new Promise(async e=>{try{let t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(o);let i=new Uint8Array(n*r*4),a=new VideoFrame(i,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});t.encode(a),a.close(),await t.flush(),e(!0)}catch{e(!1)}}):!0},rR=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,bitrate:i=128e3,...a}=t;if(!BA.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(!(i instanceof eR)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer.`);QL(e,a);let o=null;return bM.length>0&&(o??=$L({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),bM.some(t=>t.supports(e,o)))||RA.includes(e)?!0:typeof AudioEncoder>`u`?!1:(o??=$L({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),(await AudioEncoder.isConfigSupported(o)).supported===!0)},iR=async(e=BA,t)=>{let n=await Promise.all(e.map(e=>rR(e,t)));return e.filter((e,t)=>n[t])},aR=async(e,t)=>{for(let n of e)if(await nR(n,t))return n;return null},oR=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state===`finalizing`||e.output.state===`finalized`)&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},sR=class extends oR{constructor(e){if(super(),this._connectedTrack=null,!LA.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${LA.join(`, `)}.`);this._codec=e}},cR=class extends sR{constructor(e){super(e)}add(e,t){if(!(e instanceof SM))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},lR=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new uA,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null}async add(e,t,n){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let n=this.encodingConfig.sizeChangeBehavior??`deny`;if(n!==`passThrough`){if(n===`deny`)throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let r=!1;this.resizeCanvas||(typeof document<`u`?(this.resizeCanvas=document.createElement(`canvas`),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),r=!0);let i=this.resizeCanvas.getContext(`2d`,{alpha:mA()});U(i),r||(mA()?(i.fillStyle=`black`,i.fillRect(0,0,this.codedWidth,this.codedHeight)):i.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(i,{fit:n}),t&&e.close(),e=new MM(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),U(this.encoderInitialized);let r=this.encodingConfig.keyFrameInterval??5,i=Math.floor(e.timestamp/r),a={...n,keyFrame:n?.keyFrame||r===0||i!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=i,this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{U(this.encoder);let n=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(n,a),n.close();else if(n.format&&!n.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(n,a),n.close();else{let e=n.displayWidth,t=n.displayHeight;if(!this.splitter)try{this.splitter=new uR(e,t)}catch(e){console.error(`Due to an error, only color data will be encoded.`,e),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(n,a),n.close()}if(this.splitter){let e=this.splitter.extractColor(n),t=this.splitter.extractAlpha(n);this.alphaFrameQueue.push(t),this.encoder.encode(e,a),e.close(),n.close()}}t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=XL({width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=yM.find(e=>e.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof SM))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],n=[],r=0,i=0,a=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=SM.fromEncodedChunk(e,r);this.encodingConfig.onEncodedPacket?.(i,n),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e})},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder){a(t,null,o);return}let s=this.alphaFrameQueue.shift();U(s!==void 0),s?(this.alphaEncoder.encode(s,{keyFrame:t.type===`key`}),i++,s.close(),e.push({chunk:t,meta:o})):i===0?a(t,null,o):(n.push(r+i),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{i--;let s=e.shift();for(U(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();U(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}U(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},uR=class{constructor(e,t){this.lastFrame=null,typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement(`canvas`),this.canvas.width=e,this.canvas.height=t);let n=this.canvas.getContext(`webgl2`,{alpha:!0});if(!n)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=n,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2123
+ `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.program,`a_position`),i=this.gl.getAttribLocation(this.program,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null}},fN=class extends cN{constructor(e){if(!(e instanceof vN))throw TypeError(`videoTrack must be an InputVideoTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This video track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let n=this._track.codec,r=this._track.rotation,i=await this._track.getDecoderConfig(),a=this._track.timeResolution;return U(n&&i),new uN(e,t,n,i,r,a)}_createPacketSink(){return new oN(this._track)}async getSample(e){iN(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw Error(`Internal error: Iterator returned nothing.`)}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},pN=class{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof vN))throw TypeError(`videoTrack must be an InputVideoTrack.`);if(t&&typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.alpha!==void 0&&typeof t.alpha!=`boolean`)throw TypeError(`options.alpha, when provided, must be a boolean.`);if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError(`options.width, when defined, must be a positive integer.`);if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError(`options.height, when defined, must be a positive integer.`);if(t.fit!==void 0&&![`fill`,`contain`,`cover`].includes(t.fit))throw TypeError(`options.fit, when provided, must be one of "fill", "contain", or "cover".`);if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw TypeError(`When both options.width and options.height are provided, options.fit must also be provided.`);if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`options.rotation, when provided, must be 0, 90, 180 or 270.`);if(t.crop!==void 0&&GM(t.crop,`options.`),t.poolSize!==void 0&&(typeof t.poolSize!=`number`||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError(`poolSize must be a non-negative integer.`);let n=t.rotation??e.rotation,[r,i]=n%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],a=t.crop;a&&WM(a,r,i);let[o,s]=a?[a.width,a.height]:[r,i],c=o/s;t.width!==void 0&&t.height===void 0?(o=t.width,s=Math.round(o/c)):t.width===void 0&&t.height!==void 0?(s=t.height,o=Math.round(s*c)):t.width!==void 0&&t.height!==void 0&&(o=t.width,s=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=o,this._height=s,this._rotation=n,this._crop=a,this._fit=t.fit??`fill`,this._videoSampleSink=new fN(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_videoSampleToWrappedCanvas(e){let t=this._canvasPool[this._nextCanvasIndex],n=!1;t||(typeof document<`u`?(t=document.createElement(`canvas`),t.width=this._width,t.height=this._height):t=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=t),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let r=t.getContext(`2d`,{alpha:this._alpha||CA()});U(r),r.resetTransform(),n||(!this._alpha&&CA()?(r.fillStyle=`black`,r.fillRect(0,0,this._width,this._height)):r.clearRect(0,0,this._width,this._height)),e.drawWithFit(r,{fit:this._fit,rotation:this._rotation,crop:this._crop});let i={canvas:t,timestamp:e.timestamp,duration:e.duration};return e.close(),i}async getCanvas(e){iN(e);let t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return lA(this._videoSampleSink.samples(e,t),e=>this._videoSampleToWrappedCanvas(e))}canvasesAtTimestamps(e){return lA(this._videoSampleSink.samplesAtTimestamps(e),e=>e&&this._videoSampleToWrappedCanvas(e))}},mN=class extends sN{constructor(e,t,n,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new yA,this.customDecoderQueueSize=0,this.currentTimestamp=null;let i=t=>{(this.currentTimestamp===null||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);let n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,t.numberOfFrames===0){t.close();return}let i=r.sampleRate;t.setTimestamp(Math.round(n*i)/i),e(t)},a=DM.find(e=>e.supports(n,r));if(a)this.customDecoder=new a,this.customDecoder.codec=n,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof XM))throw TypeError(`The argument passed to onSample must be an AudioSample.`);i(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{let e=Error(`Decoding error`).stack;this.decoder=new AudioDecoder({output:e=>{try{i(new XM(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(U(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(U(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(U(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(U(this.decoder),this.decoder.close())}},hN=class extends sN{constructor(e,t,n){super(e,t),this.decoderConfig=n,this.currentTimestamp=null,U(qA.includes(n.codec)),this.codec=n.codec;let{dataType:r,sampleSize:i,littleEndian:a}=uj(this.codec);switch(this.inputSampleSize=i,i){case 1:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint8(t)-2**7:r===`signed`?this.readInputValue=(e,t)=>e.getInt8(t):r===`ulaw`?this.readInputValue=(e,t)=>NM(e.getUint8(t)):r===`alaw`?this.readInputValue=(e,t)=>FM(e.getUint8(t)):U(!1);break;case 2:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint16(t,a)-2**15:r===`signed`?this.readInputValue=(e,t)=>e.getInt16(t,a):U(!1);break;case 3:r===`unsigned`?this.readInputValue=(e,t)=>aA(e,t,a)-2**23:r===`signed`?this.readInputValue=(e,t)=>oA(e,t,a):U(!1);break;case 4:r===`unsigned`?this.readInputValue=(e,t)=>e.getUint32(t,a)-2**31:r===`signed`?this.readInputValue=(e,t)=>e.getInt32(t,a):r===`float`?this.readInputValue=(e,t)=>e.getFloat32(t,a):U(!1);break;case 8:r===`float`?this.readInputValue=(e,t)=>e.getFloat64(t,a):U(!1);break;default:iA(i),U(!1)}switch(i){case 1:r===`ulaw`||r===`alaw`?(this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0)):(this.outputSampleSize=1,this.outputFormat=`u8`,this.writeOutputValue=(e,t,n)=>e.setUint8(t,n+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat=`s16`,this.writeOutputValue=(e,t,n)=>e.setInt16(t,n,!0);break;case 3:this.outputSampleSize=4,this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n<<8,!0);break;case 4:this.outputSampleSize=4,r===`float`?(this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0)):(this.outputFormat=`s32`,this.writeOutputValue=(e,t,n)=>e.setInt32(t,n,!0));break;case 8:this.outputSampleSize=4,this.outputFormat=`f32`,this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,!0);break;default:iA(i),U(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=Fk(e.data),n=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=n*this.decoderConfig.numberOfChannels*this.outputSampleSize,i=new ArrayBuffer(r),a=new DataView(i);for(let e=0;e<n*this.decoderConfig.numberOfChannels;e++){let n=e*this.inputSampleSize,r=e*this.outputSampleSize,i=this.readInputValue(t,n);this.writeOutputValue(a,r,i)}let o=n/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);let s=this.currentTimestamp;this.currentTimestamp+=o;let c=new XM({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:n,timestamp:s});this.onSample(c)}async flush(){}close(){}},gN=class extends cN{constructor(e){if(!(e instanceof yN))throw TypeError(`audioTrack must be an InputAudioTrack.`);super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error(`This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.`);let n=this._track.codec,r=await this._track.getDecoderConfig();return U(n&&r),qA.includes(r.codec)?new hN(e,t,r):new mN(e,t,n,r)}_createPacketSink(){return new oN(this._track)}async getSample(e){iN(e);for await(let t of this.mediaSamplesAtTimestamps([e]))return t;throw Error(`Internal error: Iterator returned nothing.`)}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}},_N=class{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof vN}isAudioTrack(){return this instanceof yN}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){let t=new oN(this),n=1/0,r=-1/0,i=0,a=0;for await(let o of t.packets(void 0,void 0,{metadataOnly:!0})){if(i>=e&&o.timestamp>=r)break;n=Math.min(n,o.timestamp),r=Math.max(r,o.timestamp+o.duration),i++,a+=o.byteLength}return{packetCount:i,averagePacketRate:i?Number((i/(r-n)).toPrecision(16)):0,averageBitrate:i?Number((8*a/(r-n)).toPrecision(16)):0}}},vN=class extends _N{constructor(e,t){super(e,t),this._backing=t,this.pixelAspectRatio=PA({num:this._backing.getSquarePixelWidth()*this._backing.getCodedHeight(),den:this._backing.getSquarePixelHeight()*this._backing.getCodedWidth()})}get type(){return`video`}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get squarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelHeight(){return this._backing.getSquarePixelHeight()}get displayWidth(){return this._backing.getRotation()%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this._backing.getRotation()%180==0?this.squarePixelHeight:this.squarePixelWidth}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return e.primaries===`bt2020`||e.primaries===`smpte432`||e.transfer===`pg`||e.transfer===`hlg`||e.matrix===`bt2020-ncl`}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return U(t!==null),EM.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>`u`?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof jM))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`packet must not be metadata-only to determine its type.`);if(this.codec===null)return null;let t=await this.getDecoderConfig();return U(t),pM(this.codec,t,e.data)}},yN=class extends _N{constructor(e,t){super(e,t),this._backing=t}get type(){return`audio`}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){return(await this._backing.getDecoderConfig())?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=this._backing.getCodec();return U(t!==null),DM.some(n=>n.supports(t,e))||e.codec.startsWith(`pcm-`)?!0:typeof AudioDecoder>`u`?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error(`Error during decodability check:`,e),!1}}async determinePacketType(e){if(!(e instanceof jM))throw TypeError(`packet must be an EncodedPacket.`);return this.codec===null?null:`key`}},bN=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isQuickTime?`quicktime`:`mp4`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},xN=e=>{let t=Y(e),n=WF(e,4),r=8;t===1&&(t=zF(e),r=16);let i=t-r;return i<0?null:{name:n,totalSize:t,headerSize:r,contentSize:i}},SN=e=>IF(e)/65536,CN=e=>IF(e)/1073741824,wN=e=>{let t=0;for(let n=0;n<4;n++){t<<=7;let n=J(e);if(t|=n&127,!(n&128))break}return t},TN=e=>{let t=jF(e);return e.skip(2),t=Math.min(t,e.remainingLength),Ik.decode(q(e,t))},EN=e=>{let t=xN(e);if(!t||t.name!==`data`||e.remainingLength<8)return null;let n=Y(e);e.skip(4);let r=q(e,t.contentSize-8);switch(n){case 1:return Ik.decode(r);case 2:return new TextDecoder(`utf-16be`).decode(r);case 13:return new IA(r,`image/jpeg`);case 14:return new IA(r,`image/png`);case 27:return new IA(r,`image/bmp`);default:return r}},DN=class extends TM{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map(e=>e.inputTrack)}async getMimeType(){await this.readMetadata();let e=await Promise.all(this.tracks.map(e=>e.inputTrack.getCodecParameterString()));return bN({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type===`video`),hasAudio:this.tracks.some(e=>e.info?.type===`audio`),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,16);if(t instanceof Promise&&(t=await t),!t)break;let n=e,r=xN(t);if(!r)break;if(r.name===`ftyp`)this.isQuickTime=WF(t,4)===`qt `;else if(r.name===`moov`){let e=this.reader.requestSlice(t.filePos,r.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));for(let e of this.tracks){let t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=n+r.totalSize}if(this.isFragmented&&this.reader.fileSize!==null){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),U(e);let t=Y(e),n=this.reader.fileSize-t;if(n>=0&&n<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),e){let t=xN(e);if(t&&t.name===`mfra`){let n=this.reader.requestSlice(e.filePos,t.contentSize);n instanceof Promise&&(n=await n),n&&this.readContiguousBoxes(n)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=t,U(this.moovSlice);let n=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(n),this.currentTrack=null,e.info?.type===`audio`&&e.info.codec&&qA.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){U(e.info?.type===`audio`);let n=uj(e.info.codec),r=[],i=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],s=t.sampleToChunk[a+1],c=(s?s.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let s=o.startSampleIndex+a*o.samplesPerChunk,c=s+o.samplesPerChunk,l=Zk(t.sampleTimingEntries,s,e=>e.startIndex),u=t.sampleTimingEntries[l],d=Zk(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[d],p=u.startDecodeTimestamp+(s-u.startIndex)*u.delta,m=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-p,h=jk(r);h&&h.delta===m?h.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:p,count:1,delta:m});let g=o.samplesPerChunk*n.sampleSize*e.info.numberOfChannels;i.push(g)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=i}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(let e of t.sampleTimingEntries)for(let n=0;n<e.count;n++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+n*e.delta,sampleIndex:e.startIndex+n});for(let e of t.sampleCompositionTimeOffsets)for(let n=0;n<e.count;n++){let r=e.startIndex+n,i=t.presentationTimestamps[r];i&&(i.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),U(t);let n=xN(t);U(n?.name===`moof`);let r=this.reader.requestSlice(e,n.totalSize);r instanceof Promise&&(r=await r),U(r),this.traverseBox(r);let i=this.lastReadFragment;U(i&&i.moofOffset===e);for(let[,e]of i.trackData){let t=e.track,{fragmentPositionCache:n}=t;if(!e.startTimestampIsFinal){let r=t.fragmentLookupTable.find(e=>e.moofOffset===i.moofOffset);if(r)FN(e,r.timestamp);else{let t=Zk(n,i.moofOffset-1,e=>e.moofOffset);if(t!==-1){let r=n[t];FN(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}let r=Zk(n,e.startTimestamp,e=>e.startTimestamp);(r===-1||n[r].moofOffset!==i.moofOffset)&&n.splice(r+1,0,{moofOffset:i.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return i}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,n=xN(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=t+n.totalSize}}traverseBox(e){let t=e.filePos,n=xN(e);if(!n)return!1;let r=e.filePos,i=t+n.totalSize;switch(n.name){case`mdia`:case`minf`:case`dinf`:case`mfra`:case`edts`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mvhd`:{let t=J(e);e.skip(3),t===1?(e.skip(16),this.movieTimescale=Y(e),this.movieDurationInTimescale=zF(e)):(e.skip(8),this.movieTimescale=Y(e),this.movieDurationInTimescale=Y(e))}break;case`trak`:{let t={id:-1,demuxer:this,inputTrack:null,disposition:{...zA},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:`und`,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(r,n.contentSize)),t.id!==-1&&t.timescale!==-1&&t.info!==null){if(t.info.type===`video`&&t.info.width!==-1){let e=t;t.inputTrack=new vN(this.input,new kN(e)),this.tracks.push(t)}else if(t.info.type===`audio`&&t.info.numberOfChannels!==-1){let e=t;t.inputTrack=new yN(this.input,new AN(e)),this.tracks.push(t)}}this.currentTrack=null}break;case`tkhd`:{let t=this.currentTrack;if(!t)break;let n=J(e),r=!!(MF(e)&1);if(t.disposition.default=r,n===0)e.skip(8),t.id=Y(e),e.skip(4),t.durationInMovieTimescale=Y(e);else if(n===1)e.skip(16),t.id=Y(e),e.skip(4),t.durationInMovieTimescale=zF(e);else throw Error(`Incorrect track header version ${n}.`);e.skip(16);let i=Ak(fA(IN([SN(e),SN(e),CN(e),SN(e),SN(e),CN(e),SN(e),SN(e),CN(e)]),90));U(i===0||i===90||i===180||i===270),t.rotation=i}break;case`elst`:{let t=this.currentTrack;if(!t)break;let n=J(e);e.skip(3);let r=!1,i=0,a=Y(e);for(let o=0;o<a;o++){let a=n===1?zF(e):Y(e),o=n===1?BF(e):IF(e),s=SN(e);if(a!==0){if(r){console.warn(`Unsupported edit list: multiple edits are not currently supported. Only using first edit.`);break}if(o===-1){i+=a;continue}if(s!==1){console.warn(`Unsupported edit list entry: media rate must be 1.`);break}t.editListPreviousSegmentDurations=i,t.editListOffset=o,r=!0}}}break;case`mdhd`:{let t=this.currentTrack;if(!t)break;let n=J(e);e.skip(3),n===0?(e.skip(8),t.timescale=Y(e),t.durationInMediaTimescale=Y(e)):n===1&&(e.skip(16),t.timescale=Y(e),t.durationInMediaTimescale=zF(e));let r=jF(e);if(r>0){t.languageCode=``;for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(r&31))+t.languageCode,r>>=5;gA(t.languageCode)||(t.languageCode=`und`)}}break;case`hdlr`:{let t=this.currentTrack;if(!t)break;e.skip(8);let n=WF(e,4);n===`vide`?t.info={type:`video`,width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:n===`soun`&&(t.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case`stbl`:{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,n.contentSize))}break;case`stsd`:{let t=this.currentTrack;if(!t||t.info===null||t.sampleTable)break;let n=J(e);e.skip(3);let r=Y(e);for(let i=0;i<r;i++){let r=e.filePos,i=xN(e);if(!i)break;t.internalCodecId=i.name;let a=i.name.toLowerCase();if(t.info.type===`video`)a===`avc1`||a===`avc3`?(t.info.codec=`avc`,t.info.avcType=a===`avc1`?1:3):a===`hvc1`||a===`hev1`?t.info.codec=`hevc`:a===`vp08`?t.info.codec=`vp8`:a===`vp09`?t.info.codec=`vp9`:a===`av01`?t.info.codec=`av1`:console.warn(`Unsupported video codec (sample entry type '${i.name}').`),e.skip(24),t.info.width=jF(e),t.info.height=jF(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos));else{a===`mp4a`||(a===`opus`?t.info.codec=`opus`:a===`flac`?t.info.codec=`flac`:a===`twos`||a===`sowt`||a===`raw `||a===`in24`||a===`in32`||a===`fl32`||a===`fl64`||a===`lpcm`||a===`ipcm`||a===`fpcm`||(a===`ulaw`?t.info.codec=`ulaw`:a===`alaw`?t.info.codec=`alaw`:a===`ac-3`?t.info.codec=`ac3`:a===`ec-3`?t.info.codec=`eac3`:console.warn(`Unsupported audio codec (sample entry type '${i.name}').`))),e.skip(8);let o=jF(e);e.skip(6);let s=jF(e),c=jF(e);e.skip(4);let l=Y(e)/65536;if(n===0&&o>0){if(o===1)e.skip(4),c=8*Y(e),e.skip(8);else if(o===2){e.skip(4),l=UF(e),s=Y(e),e.skip(4),c=Y(e);let n=Y(e);if(e.skip(8),a===`lpcm`){let e=c+7>>3,r=!!(n&1),i=!!(n&2),a=n&4?-1:0;c>0&&c<=64&&(r?c===32&&(t.info.codec=i?`pcm-f32be`:`pcm-f32`):a&1<<e-1?e===1?t.info.codec=`pcm-s8`:e===2?t.info.codec=i?`pcm-s16be`:`pcm-s16`:e===3?t.info.codec=i?`pcm-s24be`:`pcm-s24`:e===4&&(t.info.codec=i?`pcm-s32be`:`pcm-s32`):e===1&&(t.info.codec=`pcm-u8`)),t.info.codec===null&&console.warn(`Unsupported PCM format.`)}}}t.info.codec===`opus`&&(l=cj),t.info.numberOfChannels=s,t.info.sampleRate=l,a===`twos`?c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16be`:(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):a===`sowt`?c===8?t.info.codec=`pcm-s8`:c===16?t.info.codec=`pcm-s16`:(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null):a===`raw `?t.info.codec=`pcm-u8`:a===`in24`?t.info.codec=`pcm-s24be`:a===`in32`?t.info.codec=`pcm-s32be`:a===`fl32`?t.info.codec=`pcm-f32be`:a===`fl64`?t.info.codec=`pcm-f64be`:a===`ipcm`?t.info.codec=`pcm-s16be`:a===`fpcm`&&(t.info.codec=`pcm-f32be`),this.readContiguousBoxes(e.slice(e.filePos,r+i.totalSize-e.filePos))}}}break;case`avcC`:{let t=this.currentTrack;if(!t)break;U(t.info),t.info.codecDescription=q(e,n.contentSize)}break;case`hvcC`:{let t=this.currentTrack;if(!t)break;U(t.info),t.info.codecDescription=q(e,n.contentSize)}break;case`vpcC`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`video`),e.skip(4);let n=J(e),r=J(e),i=J(e),a=i>>4,o=i>>1&7,s=i&1,c=J(e),l=J(e),u=J(e);t.info.vp9CodecInfo={profile:n,level:r,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:s,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case`av1C`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`video`),e.skip(1);let n=J(e),r=n>>5,i=n&31,a=J(e),o=a>>7,s=a>>6&1,c=a>>5&1,l=a>>4&1,u=a>>3&1,d=a>>2&1,f=a&3,p=r===2&&s?c?12:10:s?10:8;t.info.av1CodecInfo={profile:r,level:i,tier:o,bitDepth:p,monochrome:l,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:f}}break;case`colr`:{let t=this.currentTrack;if(!t||(U(t.info?.type===`video`),WF(e,4)!==`nclx`))break;let n=jF(e),r=jF(e),i=jF(e),a=!!(J(e)&128);t.info.colorSpace={primaries:Bk[n],transfer:Hk[r],matrix:Wk[i],fullRange:a}}break;case`pasp`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`video`);let n=Y(e),r=Y(e);n>r?t.info.squarePixelWidth=Math.round(t.info.width*n/r):t.info.squarePixelHeight=Math.round(t.info.height*r/n)}break;case`wave`:this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`esds`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(4),U(J(e)===3),wN(e),e.skip(2);let n=J(e),r=(n&128)!=0,i=(n&64)!=0,a=(n&32)!=0;if(r&&e.skip(2),i){let t=J(e);e.skip(t)}a&&e.skip(2),U(J(e)===4);let o=wN(e),s=e.filePos,c=J(e);if(c===64||c===103?(t.info.codec=`aac`,t.info.aacCodecInfo={isMpeg2:c===103,objectType:null}):c===105||c===107?t.info.codec=`mp3`:c===221?t.info.codec=`vorbis`:console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),o>e.filePos-s){U(J(e)===5);let n=wN(e);if(t.info.codecDescription=q(e,n),t.info.codec===`aac`){let e=WA(t.info.codecDescription);e.numberOfChannels!==null&&(t.info.numberOfChannels=e.numberOfChannels),e.sampleRate!==null&&(t.info.sampleRate=e.sampleRate)}}}break;case`enda`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),jF(e)&255&&(t.info.codec===`pcm-s16be`?t.info.codec=`pcm-s16`:t.info.codec===`pcm-s24be`?t.info.codec=`pcm-s24`:t.info.codec===`pcm-s32be`?t.info.codec=`pcm-s32`:t.info.codec===`pcm-f32be`?t.info.codec=`pcm-f32`:t.info.codec===`pcm-f64be`&&(t.info.codec=`pcm-f64`))}break;case`pcmC`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(4);let n=!!(J(e)&1),r=J(e);t.info.codec===`pcm-s16be`?n?r===16?t.info.codec=`pcm-s16`:r===24?t.info.codec=`pcm-s24`:r===32?t.info.codec=`pcm-s32`:(console.warn(`Invalid ipcm sample size ${r}.`),t.info.codec=null):r===16?t.info.codec=`pcm-s16be`:r===24?t.info.codec=`pcm-s24be`:r===32?t.info.codec=`pcm-s32be`:(console.warn(`Invalid ipcm sample size ${r}.`),t.info.codec=null):t.info.codec===`pcm-f32be`&&(n?r===32?t.info.codec=`pcm-f32`:r===64?t.info.codec=`pcm-f64`:(console.warn(`Invalid fpcm sample size ${r}.`),t.info.codec=null):r===32?t.info.codec=`pcm-f32be`:r===64?t.info.codec=`pcm-f64be`:(console.warn(`Invalid fpcm sample size ${r}.`),t.info.codec=null));break}case`dOps`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(1);let n=J(e),r=jF(e),i=Y(e),a=NF(e),o=J(e),s;s=o===0?new Uint8Array:q(e,2+n);let c=new Uint8Array(19+s.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,n),l.setUint16(10,r,!0),l.setUint32(12,i,!0),l.setInt16(16,a,!0),l.setUint8(18,o),c.set(s,19),t.info.codecDescription=c,t.info.numberOfChannels=n}break;case`dfLa`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`),e.skip(4);let n=e.filePos;for(;e.filePos<i;){let n=J(e),r=MF(e);if((n&127)===mM.STREAMINFO){e.skip(10);let n=Y(e),r=n>>>12,i=(n>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=i,e.skip(20)}else e.skip(r);if(n&128)break}let r=e.filePos;e.filePos=n;let a=q(e,r-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case`dac3`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`);let n=new VA(q(e,3)),r=n.readBits(2);n.skipBits(8);let i=n.readBits(3),a=n.readBits(1);r<3&&(t.info.sampleRate=kj[r]),t.info.numberOfChannels=gM[i]+a}break;case`dec3`:{let t=this.currentTrack;if(!t)break;U(t.info?.type===`audio`);let r=SM(q(e,n.contentSize));if(!r){console.warn(`Invalid dec3 box contents, ignoring.`);break}let i=CM(r);i!==null&&(t.info.sampleRate=i),t.info.numberOfChannels=wM(r)}break;case`stts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=0,i=0;for(let a=0;a<n;a++){let n=Y(e),a=Y(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:i,count:n,delta:a}),r+=n,i+=n*a}}break;case`ctts`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=0;for(let i=0;i<n;i++){let n=Y(e),i=IF(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:n,offset:i}),r+=n}}break;case`stsz`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e),r=Y(e);if(n===0)for(let n=0;n<r;n++){let n=Y(e);t.sampleTable.sampleSizes.push(n)}else t.sampleTable.sampleSizes.push(n)}break;case`stz2`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let n=J(e),r=Y(e),i=new VA(q(e,Math.ceil(r*n/8)));for(let e=0;e<r;e++){let e=i.readBits(n);t.sampleTable.sampleSizes.push(e)}}break;case`stss`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let n=Y(e);for(let r=0;r<n;r++){let n=Y(e)-1;t.sampleTable.keySampleIndices.push(n)}t.sampleTable.keySampleIndices[0]!==0&&t.sampleTable.keySampleIndices.unshift(0)}break;case`stsc`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=Y(e)-1,r=Y(e),i=Y(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:n,samplesPerChunk:r,sampleDescriptionIndex:i})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){let n=t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex;r+=n*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case`stco`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=Y(e);t.sampleTable.chunkOffsets.push(n)}}break;case`co64`:{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let n=Y(e);for(let r=0;r<n;r++){let n=zF(e);t.sampleTable.chunkOffsets.push(n)}}break;case`mvex`:this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,n.contentSize));break;case`mehd`:{let t=J(e);e.skip(3),this.movieDurationInTimescale=t===1?zF(e):Y(e)}break;case`trex`:{e.skip(4);let t=Y(e),n=Y(e),r=Y(e),i=Y(e),a=Y(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:n,defaultSampleDuration:r,defaultSampleSize:i,defaultSampleFlags:a})}break;case`tfra`:{let t=J(e);e.skip(3);let n=Y(e),r=this.tracks.find(e=>e.id===n);if(!r)break;let i=Y(e),a=(i&48)>>4,o=(i&12)>>2,s=i&3,c=[J,jF,MF,Y],l=c[a],u=c[o],d=c[s],f=Y(e);for(let n=0;n<f;n++){let n=t===1?zF(e):Y(e),i=t===1?zF(e):Y(e);l(e),u(e),d(e),r.fragmentLookupTable.push({timestamp:n,moofOffset:i})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],n=r.fragmentLookupTable[e+1];t.timestamp===n.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case`moof`:this.currentFragment={moofOffset:t,moofSize:n.totalSize,implicitBaseDataOffset:t,trackData:new Map},this.readContiguousBoxes(e.slice(r,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case`traf`:if(U(this.currentFragment),this.readContiguousBoxes(e.slice(r,n.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){let{currentFragmentState:t}=this.currentTrack;U(t),t.startTimestamp!==null&&(FN(e,t.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case`tfhd`:{U(this.currentFragment),e.skip(1);let t=MF(e),n=!!(t&1),r=!!(t&2),i=!!(t&8),a=!!(t&16),o=!!(t&32),s=!!(t&65536),c=!!(t&131072),l=Y(e),u=this.tracks.find(e=>e.id===l);if(!u)break;let d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null},n?u.currentFragmentState.baseDataOffset=zF(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Y(e)),i&&(u.currentFragmentState.defaultSampleDuration=Y(e)),a&&(u.currentFragmentState.defaultSampleSize=Y(e)),o&&(u.currentFragmentState.defaultSampleFlags=Y(e)),s&&(u.currentFragmentState.defaultSampleDuration=0)}break;case`tfdt`:{let t=this.currentTrack;if(!t)break;U(t.currentFragmentState);let n=J(e);e.skip(3);let r=n===0?Y(e):zF(e);t.currentFragmentState.startTimestamp=r}break;case`trun`:{let t=this.currentTrack;if(!t)break;if(U(this.currentFragment),U(t.currentFragmentState),this.currentFragment.trackData.has(t.id)){console.warn(`Can't have two trun boxes for the same track in one fragment. Ignoring...`);break}let n=J(e),r=MF(e),i=!!(r&1),a=!!(r&4),o=!!(r&256),s=!!(r&512),c=!!(r&1024),l=!!(r&2048),u=Y(e),d=t.currentFragmentState.baseDataOffset;i&&(d+=IF(e));let f=null;a&&(f=Y(e));let p=d;if(u===0){this.currentFragment.implicitBaseDataOffset=p;break}let m=0,h={track:t,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(t.id,h);for(let r=0;r<u;r++){let i;o?i=Y(e):(U(t.currentFragmentState.defaultSampleDuration!==null),i=t.currentFragmentState.defaultSampleDuration);let a;s?a=Y(e):(U(t.currentFragmentState.defaultSampleSize!==null),a=t.currentFragmentState.defaultSampleSize);let u;c?u=Y(e):(U(t.currentFragmentState.defaultSampleFlags!==null),u=t.currentFragmentState.defaultSampleFlags),r===0&&f!==null&&(u=f);let d=0;l&&(d=n===0?Y(e):IF(e));let g=!(u&65536);h.samples.push({presentationTimestamp:m+d,duration:i,byteOffset:p,byteSize:a,isKeyFrame:g}),p+=a,m+=i}h.presentationTimestamps=h.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let e=0;e<h.presentationTimestamps.length;e++){let t=h.presentationTimestamps[e],n=h.samples[t.sampleIndex];h.firstKeyFrameTimestamp===null&&n.isKeyFrame&&(h.firstKeyFrameTimestamp=n.presentationTimestamp),e<h.presentationTimestamps.length-1&&(n.duration=h.presentationTimestamps[e+1].presentationTimestamp-t.presentationTimestamp)}let g=h.samples[h.presentationTimestamps[0].sampleIndex],_=h.samples[jk(h.presentationTimestamps).sampleIndex];h.startTimestamp=g.presentationTimestamp,h.endTimestamp=_.presentationTimestamp+_.duration,this.currentFragment.implicitBaseDataOffset=p}break;case`udta`:{let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){if(e.name!==`meta`&&!this.currentTrack){let t=n.filePos;this.metadataTags.raw??={},e.name[0]===`©`?this.metadataTags.raw[e.name]??=TN(n):this.metadataTags.raw[e.name]??=q(n,e.contentSize),n.filePos=t}switch(e.name){case`meta`:n.skip(-e.headerSize),this.traverseBox(n);break;case`©nam`:case`name`:this.currentTrack?this.currentTrack.name=Ik.decode(q(n,e.contentSize)):this.metadataTags.title??=TN(n);break;case`©des`:this.currentTrack||(this.metadataTags.description??=TN(n));break;case`©ART`:this.currentTrack||(this.metadataTags.artist??=TN(n));break;case`©alb`:this.currentTrack||(this.metadataTags.album??=TN(n));break;case`albr`:this.currentTrack||(this.metadataTags.albumArtist??=TN(n));break;case`©gen`:this.currentTrack||(this.metadataTags.genre??=TN(n));break;case`©day`:if(!this.currentTrack){let e=new Date(TN(n));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`©cmt`:this.currentTrack||(this.metadataTags.comment??=TN(n));break;case`©lyr`:this.currentTrack||(this.metadataTags.lyrics??=TN(n));break}}}break;case`meta`:{if(this.currentTrack)break;let t=Y(e)!==0;this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(r,n.contentSize)):this.readContiguousBoxes(e.slice(r+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case`keys`:{if(!this.currentMetadataKeys)break;e.skip(4);let t=Y(e);for(let n=0;n<t;n++){let t=Y(e);e.skip(4);let r=Ik.decode(q(e,t-8));this.currentMetadataKeys.set(n+1,r)}}break;case`ilst`:{if(!this.currentMetadataKeys)break;let t=this.iterateContiguousBoxes(e.slice(r,n.contentSize));for(let{boxInfo:e,slice:n}of t){let t=e.name,r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));let i=EN(n);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=i,t){case`©nam`:case`titl`:case`com.apple.quicktime.title`:case`title`:typeof i==`string`&&(this.metadataTags.title??=i);break;case`©des`:case`desc`:case`dscp`:case`com.apple.quicktime.description`:case`description`:typeof i==`string`&&(this.metadataTags.description??=i);break;case`©ART`:case`com.apple.quicktime.artist`:case`artist`:typeof i==`string`&&(this.metadataTags.artist??=i);break;case`©alb`:case`albm`:case`com.apple.quicktime.album`:case`album`:typeof i==`string`&&(this.metadataTags.album??=i);break;case`aART`:case`album_artist`:typeof i==`string`&&(this.metadataTags.albumArtist??=i);break;case`©cmt`:case`com.apple.quicktime.comment`:case`comment`:typeof i==`string`&&(this.metadataTags.comment??=i);break;case`©gen`:case`gnre`:case`com.apple.quicktime.genre`:case`genre`:typeof i==`string`&&(this.metadataTags.genre??=i);break;case`©lyr`:case`lyrics`:typeof i==`string`&&(this.metadataTags.lyrics??=i);break;case`©day`:case`rldt`:case`com.apple.quicktime.creationdate`:case`date`:if(typeof i==`string`){let e=new Date(i);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`covr`:case`com.apple.quicktime.artwork`:i instanceof IA?(this.metadataTags.images??=[],this.metadataTags.images.push({data:i.data,kind:`coverFront`,mimeType:i.mimeType})):i instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:i,kind:`coverFront`,mimeType:`image/*`}));break;case`track`:if(typeof i==`string`){let e=i.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`trkn`:if(i instanceof Uint8Array&&i.length>=6){let e=Fk(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),n>0&&(this.metadataTags.tracksTotal??=n)}break;case`disc`:case`disk`:if(i instanceof Uint8Array&&i.length>=6){let e=Fk(i),t=e.getUint16(2,!1),n=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),n>0&&(this.metadataTags.discsTotal??=n)}break}}}break}return e.filePos=i,!0}},ON=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.inputTrack.type,n=0;for(let r of e.tracks)if(r.inputTrack.type===t&&n++,r===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}getDisposition(){return this.internalTrack.disposition}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return dA(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=jN(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!LN(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=Zk(t.presentationTimestamps,n,e=>e.presentationTimestamp);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0)return this.fetchPacketForSampleIndex(n+1,t);let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i=MN(r,n),a=await this.fetchPacketForSampleIndex(i,t);return!LN(r)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=tA(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=n);return{sampleIndex:r===-1?-1:t.presentationTimestamps[r].sampleIndex,correctSampleFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToSampleIndex.get(e);if(n!==void 0){let e=PN(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(t!==-1)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.samples.findIndex(e=>e.isKeyFrame);return U(e!==-1),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;let n=NN(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!n)return null;let r;if(t.metadataOnly)r=AM;else{let e=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);e instanceof Promise&&(e=await e),U(e),r=q(e,n.sampleSize)}let i=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=n.duration/this.internalTrack.timescale,o=new jM(r,n.isKeyFrame?`key`:`delta`,i,a,e,n.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).samples[t];U(r);let i;if(n.metadataOnly)i=AM;else{let e=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);e instanceof Promise&&(e=await e),U(e),i=q(e,r.byteSize)}let a=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=r.duration/this.internalTrack.timescale,s=new jM(i,r.isKeyFrame?`key`:`delta`,a,o,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(s,{fragment:e,sampleIndex:t}),s}async performFragmentedLookup(e,t,n,r,i){let a=this.internalTrack.demuxer,o=null,s=null,c=-1;if(e){let{sampleIndex:n,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,n,i);n!==-1&&(s=e,c=n)}let l=Zk(this.internalTrack.fragmentLookupTable,n,e=>e.timestamp),u=l===-1?null:this.internalTrack.fragmentLookupTable[l],d=Zk(this.internalTrack.fragmentPositionCache,n,e=>e.startTimestamp),f=d===-1?null:this.internalTrack.fragmentPositionCache[d],p=Math.max(u?.moofOffset??0,f?.moofOffset??0)||null,m;for(e?p===null||e.moofOffset>=p?(m=e.moofOffset+e.moofSize,o=e):m=p:m=p??0;;){if(o){let e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(m,8,16);if(e instanceof Promise&&(e=await e),!e)break;let n=m,l=xN(e);if(!l)break;if(l.name===`moof`){o=await a.readFragment(n);let{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,i);e!==-1&&(s=o,c=e)}m=n+l.totalSize}if(u&&(!s||s.moofOffset<u.moofOffset)){let e=this.internalTrack.fragmentLookupTable[l-1];U(!e||e.timestamp<u.timestamp);let n=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,n,r,i)}return s?this.fetchPacketInFragment(s,c,i):null}},kN=class extends ON{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if(this.internalTrack.info.codec===`vp9`&&!this.internalTrack.info.vp9CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&oM(e.data)}else if(this.internalTrack.info.codec===`av1`&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&cM(e.data)}return{codec:aj(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},AN=class extends ON{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:sj(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},jN=(e,t)=>{if(e.presentationTimestamps){let n=Zk(e.presentationTimestamps,t,e=>e.presentationTimestamp);return n===-1?-1:e.presentationTimestamps[n].sampleIndex}else{let n=Zk(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(n===-1)return-1;let r=e.sampleTimingEntries[n];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},MN=(e,t)=>{if(!e.keySampleIndices)return jN(e,t);if(e.presentationTimestamps){let n=Zk(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(n===-1)return-1;for(let t=n;t>=0;t--){let n=e.presentationTimestamps[t].sampleIndex;if(Xk(e.keySampleIndices,n,e=>e)!==-1)return n}return-1}else{let n=jN(e,t),r=Zk(e.keySampleIndices,n,e=>e);return e.keySampleIndices[r]??-1}},NN=(e,t)=>{let n=Zk(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[n];if(!r||r.startIndex+r.count<=t)return null;let i=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,a=Zk(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[a];o&&t-o.startIndex<o.count&&(i+=o.offset);let s=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=Zk(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];U(l);let u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],f=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk,p=0,m=d;if(e.sampleSizes.length===1)m+=s*(t-f),p+=s*l.samplesPerChunk;else for(let n=f;n<f+l.samplesPerChunk;n++){let r=e.sampleSizes[n];n<t&&(m+=r),p+=r}let h=r.delta;if(e.presentationTimestamps){let n=e.presentationTimestampIndexMap[t];U(n!==void 0),n<e.presentationTimestamps.length-1&&(h=e.presentationTimestamps[n+1].presentationTimestamp-i)}return{presentationTimestamp:i,duration:h,sampleOffset:m,sampleSize:s,chunkOffset:d,chunkSize:p,isKeyFrame:e.keySampleIndices?Xk(e.keySampleIndices,t,e=>e)!==-1:!0}},PN=(e,t)=>{if(!e.keySampleIndices)return t+1;let n=Zk(e.keySampleIndices,t,e=>e);return e.keySampleIndices[n+1]??-1},FN=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(let n of e.samples)n.presentationTimestamp+=t;for(let n of e.presentationTimestamps)n.presentationTimestamp+=t},IN=e=>{let[t,,,n]=e,r=Math.hypot(t,n),i=t/r,a=n/r,o=-Math.atan2(a,i)*(180/Math.PI);return Number.isFinite(o)?o:0},LN=e=>e.sampleSizes.length===0,G;(function(e){e[e.EBML=440786851]=`EBML`,e[e.EBMLVersion=17030]=`EBMLVersion`,e[e.EBMLReadVersion=17143]=`EBMLReadVersion`,e[e.EBMLMaxIDLength=17138]=`EBMLMaxIDLength`,e[e.EBMLMaxSizeLength=17139]=`EBMLMaxSizeLength`,e[e.DocType=17026]=`DocType`,e[e.DocTypeVersion=17031]=`DocTypeVersion`,e[e.DocTypeReadVersion=17029]=`DocTypeReadVersion`,e[e.Void=236]=`Void`,e[e.Segment=408125543]=`Segment`,e[e.SeekHead=290298740]=`SeekHead`,e[e.Seek=19899]=`Seek`,e[e.SeekID=21419]=`SeekID`,e[e.SeekPosition=21420]=`SeekPosition`,e[e.Duration=17545]=`Duration`,e[e.Info=357149030]=`Info`,e[e.TimestampScale=2807729]=`TimestampScale`,e[e.MuxingApp=19840]=`MuxingApp`,e[e.WritingApp=22337]=`WritingApp`,e[e.Tracks=374648427]=`Tracks`,e[e.TrackEntry=174]=`TrackEntry`,e[e.TrackNumber=215]=`TrackNumber`,e[e.TrackUID=29637]=`TrackUID`,e[e.TrackType=131]=`TrackType`,e[e.FlagEnabled=185]=`FlagEnabled`,e[e.FlagDefault=136]=`FlagDefault`,e[e.FlagForced=21930]=`FlagForced`,e[e.FlagOriginal=21934]=`FlagOriginal`,e[e.FlagHearingImpaired=21931]=`FlagHearingImpaired`,e[e.FlagVisualImpaired=21932]=`FlagVisualImpaired`,e[e.FlagCommentary=21935]=`FlagCommentary`,e[e.FlagLacing=156]=`FlagLacing`,e[e.Name=21358]=`Name`,e[e.Language=2274716]=`Language`,e[e.LanguageBCP47=2274717]=`LanguageBCP47`,e[e.CodecID=134]=`CodecID`,e[e.CodecPrivate=25506]=`CodecPrivate`,e[e.CodecDelay=22186]=`CodecDelay`,e[e.SeekPreRoll=22203]=`SeekPreRoll`,e[e.DefaultDuration=2352003]=`DefaultDuration`,e[e.Video=224]=`Video`,e[e.PixelWidth=176]=`PixelWidth`,e[e.PixelHeight=186]=`PixelHeight`,e[e.DisplayWidth=21680]=`DisplayWidth`,e[e.DisplayHeight=21690]=`DisplayHeight`,e[e.DisplayUnit=21682]=`DisplayUnit`,e[e.AlphaMode=21440]=`AlphaMode`,e[e.Audio=225]=`Audio`,e[e.SamplingFrequency=181]=`SamplingFrequency`,e[e.Channels=159]=`Channels`,e[e.BitDepth=25188]=`BitDepth`,e[e.SimpleBlock=163]=`SimpleBlock`,e[e.BlockGroup=160]=`BlockGroup`,e[e.Block=161]=`Block`,e[e.BlockAdditions=30113]=`BlockAdditions`,e[e.BlockMore=166]=`BlockMore`,e[e.BlockAdditional=165]=`BlockAdditional`,e[e.BlockAddID=238]=`BlockAddID`,e[e.BlockDuration=155]=`BlockDuration`,e[e.ReferenceBlock=251]=`ReferenceBlock`,e[e.Cluster=524531317]=`Cluster`,e[e.Timestamp=231]=`Timestamp`,e[e.Cues=475249515]=`Cues`,e[e.CuePoint=187]=`CuePoint`,e[e.CueTime=179]=`CueTime`,e[e.CueTrackPositions=183]=`CueTrackPositions`,e[e.CueTrack=247]=`CueTrack`,e[e.CueClusterPosition=241]=`CueClusterPosition`,e[e.Colour=21936]=`Colour`,e[e.MatrixCoefficients=21937]=`MatrixCoefficients`,e[e.TransferCharacteristics=21946]=`TransferCharacteristics`,e[e.Primaries=21947]=`Primaries`,e[e.Range=21945]=`Range`,e[e.Projection=30320]=`Projection`,e[e.ProjectionType=30321]=`ProjectionType`,e[e.ProjectionPoseRoll=30325]=`ProjectionPoseRoll`,e[e.Attachments=423732329]=`Attachments`,e[e.AttachedFile=24999]=`AttachedFile`,e[e.FileDescription=18046]=`FileDescription`,e[e.FileName=18030]=`FileName`,e[e.FileMediaType=18016]=`FileMediaType`,e[e.FileData=18012]=`FileData`,e[e.FileUID=18094]=`FileUID`,e[e.Chapters=272869232]=`Chapters`,e[e.Tags=307544935]=`Tags`,e[e.Tag=29555]=`Tag`,e[e.Targets=25536]=`Targets`,e[e.TargetTypeValue=26826]=`TargetTypeValue`,e[e.TargetType=25546]=`TargetType`,e[e.TagTrackUID=25541]=`TagTrackUID`,e[e.TagEditionUID=25545]=`TagEditionUID`,e[e.TagChapterUID=25540]=`TagChapterUID`,e[e.TagAttachmentUID=25542]=`TagAttachmentUID`,e[e.SimpleTag=26568]=`SimpleTag`,e[e.TagName=17827]=`TagName`,e[e.TagLanguage=17530]=`TagLanguage`,e[e.TagString=17543]=`TagString`,e[e.TagBinary=17541]=`TagBinary`,e[e.ContentEncodings=28032]=`ContentEncodings`,e[e.ContentEncoding=25152]=`ContentEncoding`,e[e.ContentEncodingOrder=20529]=`ContentEncodingOrder`,e[e.ContentEncodingScope=20530]=`ContentEncodingScope`,e[e.ContentCompression=20532]=`ContentCompression`,e[e.ContentCompAlgo=16980]=`ContentCompAlgo`,e[e.ContentCompSettings=16981]=`ContentCompSettings`,e[e.ContentEncryption=20533]=`ContentEncryption`})(G||={});var RN=[G.EBML,G.Segment],zN=[G.SeekHead,G.Info,G.Cluster,G.Tracks,G.Cues,G.Attachments,G.Chapters,G.Tags],BN=[...RN,...zN],VN=e=>{if(e.remainingLength<1)return null;let t=J(e);if(e.skip(-1),t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;return e.remainingLength<n?null:n},HN=e=>{if(e.remainingLength<1)return null;let t=J(e);if(t===0)return null;let n=1,r=128;for(;(t&r)===0;)n++,r>>=1;if(e.remainingLength<n-1)return null;let i=t&r-1;for(let t=1;t<n;t++)i*=256,i+=J(e);return i},K=(e,t)=>{if(t<1||t>8)throw Error(`Bad unsigned int size `+t);let n=0;for(let r=0;r<t;r++)n*=256,n+=J(e);return n},UN=(e,t)=>{if(t<1)throw Error(`Bad unsigned int size `+t);let n=0n;for(let r=0;r<t;r++)n<<=8n,n+=BigInt(J(e));return n},WN=e=>{let t=VN(e);return t===null||e.remainingLength<t?null:K(e,t)},GN=e=>{if(e.remainingLength<1)return null;if(J(e)===255)return;e.skip(-1);let t=HN(e);if(t===null)return null;if(t!==72057594037927940)return t},KN=e=>{U(e.remainingLength>=2);let t=WN(e);if(t===null)return null;let n=GN(e);return n===null?null:{id:t,size:n}},qN=(e,t)=>{let n=q(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return String.fromCharCode(...n.subarray(0,r))},JN=(e,t)=>{let n=q(e,t),r=0;for(;r<t&&n[r]!==0;)r+=1;return Ik.decode(n.subarray(0,r))},YN=(e,t)=>{if(t===0)return 0;if(t!==4&&t!==8)throw Error(`Bad float size `+t);return t===4?HF(e):UF(e)},XN=async(e,t,n,r)=>{let i=new Set(n),a=t;for(;r===null||a<r;){let t=e.requestSliceRange(a,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=KN(t);if(!n)break;if(i.has(n.id))return{pos:a,found:!0};$N(n.size),a=t.filePos+n.size}return{pos:r!==null&&r>a?r:a,found:!1}},ZN=async(e,t,n,r)=>{let i=2**16,a=new Set(n),o=t;for(;o<r;){let t=e.requestSliceRange(o,0,Math.min(i,r-o));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=o;let e=WN(t);if(e!==null&&a.has(e))return o;o++}}return null},QN={avc:`V_MPEG4/ISO/AVC`,hevc:`V_MPEGH/ISO/HEVC`,vp8:`V_VP8`,vp9:`V_VP9`,av1:`V_AV1`,aac:`A_AAC`,mp3:`A_MPEG/L3`,opus:`A_OPUS`,vorbis:`A_VORBIS`,flac:`A_FLAC`,ac3:`A_AC3`,eac3:`A_EAC3`,"pcm-u8":`A_PCM/INT/LIT`,"pcm-s16":`A_PCM/INT/LIT`,"pcm-s16be":`A_PCM/INT/BIG`,"pcm-s24":`A_PCM/INT/LIT`,"pcm-s24be":`A_PCM/INT/BIG`,"pcm-s32":`A_PCM/INT/LIT`,"pcm-s32be":`A_PCM/INT/BIG`,"pcm-f32":`A_PCM/FLOAT/IEEE`,"pcm-f64":`A_PCM/FLOAT/IEEE`,webvtt:`S_TEXT/WEBVTT`};function $N(e){if(e===void 0)throw Error(`Undefined element size is used in a place where it is not supported.`)}var eP=e=>{let t=(e.hasVideo?`video/`:e.hasAudio?`audio/`:`application/`)+(e.isWebM?`webm`:`x-matroska`);if(e.codecStrings.length>0){let n=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${n.join(`, `)}"`}return t},tP;(function(e){e[e.None=0]=`None`,e[e.Xiph=1]=`Xiph`,e[e.FixedSize=2]=`FixedSize`,e[e.Ebml=3]=`Ebml`})(tP||={});var nP;(function(e){e[e.Block=1]=`Block`,e[e.Private=2]=`Private`,e[e.Next=4]=`Next`})(nP||={});var rP;(function(e){e[e.Zlib=0]=`Zlib`,e[e.Bzlib=1]=`Bzlib`,e[e.lzo1x=2]=`lzo1x`,e[e.HeaderStripping=3]=`HeaderStripping`})(rP||={});var iP=[{id:G.SeekHead,flag:`seekHeadSeen`},{id:G.Info,flag:`infoSeen`},{id:G.Tracks,flag:`tracksSeen`},{id:G.Cues,flag:`cuesSeen`}],aP=10*2**20,oP=class extends TM{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.inputTrack))}async getMimeType(){await this.readMetadata();let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.getCodecParameterString()));return eP({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`video`)),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type===`audio`)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(let e of this.segments)e.metadataTagsCollected||=(this.reader.fileSize!==null&&await this.loadSegmentMetadata(e),!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(t instanceof Promise&&(t=await t),!t)break;let n=KN(t);if(!n)break;let r=n.id,i=n.size,a=t.filePos;if(r===G.EBML){$N(i);let e=this.reader.requestSlice(a,i);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===G.Segment){if(await this.readSegment(a,i),i===void 0||this.reader.fileSize===null)break}else if(r===G.Cluster){if(this.reader.fileSize===null)break;i===void 0&&(i=(await XN(this.reader,a,BN,this.reader.fileSize)).pos-a);let e=jk(this.segments);e&&(e.elementEndPos=a+i)}$N(i),e=a+i}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let n=e;for(;this.currentSegment.elementEndPos===null||n<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=n,r=KN(e);if(!r||!zN.includes(r.id)&&r.id!==G.Void){let e=await ZN(this.reader,t,zN,Math.min(this.currentSegment.elementEndPos??1/0,t+aP));if(e){n=e;continue}else break}let{id:i,size:a}=r,o=e.filePos,s=iP.findIndex(e=>e.id===i);if(s!==-1){let e=iP[s].flag;this.currentSegment[e]=!0,$N(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(i===G.Tags||i===G.Attachments){i===G.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,$N(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(i===G.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(a===void 0)break;n=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),this.reader.fileSize!==null)for(let t of this.currentSegment.seekEntries){let n=iP.find(e=>e.id===t.id);if(!n||this.currentSegment[n.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let i=KN(r);if(!i)continue;let{id:a,size:o}=i;if(a!==n.id)continue;$N(o),this.currentSegment[n.flag]=!0;let s=this.reader.requestSlice(r.filePos,o);s instanceof Promise&&(s=await s),s&&this.readContiguousElements(s)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(let e of this.currentSegment.tracks)e.defaultDurationNs!==null&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);this.currentSegment.tracks.sort((e,t)=>Number(t.disposition.default)-Number(e.disposition.default));let r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let n=e.cuePoints[t],r=e.cuePoints[t+1];n.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let i=null,a=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,i=e);for(let e of this.currentSegment.tracks)e.cuePoints.length===0&&(e.cuePoints=i.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let n=this.reader.requestSliceRange(e,2,16);n instanceof Promise&&(n=await n),U(n);let r=e,i=KN(n);U(i);let a=i.id;U(a===G.Cluster);let o=i.size,s=n.filePos;o===void 0&&(o=(await XN(this.reader,s,BN,t.elementEndPos)).pos-s);let c=this.reader.requestSlice(s,o);c instanceof Promise&&(c=await c);let l={segment:t,elementStartPos:r,elementEndPos:s+o,dataStartPos:s,timestamp:-1,trackData:new Map};this.currentCluster=l,c&&(l.elementEndPos=this.readContiguousElements(c,BN));for(let[,e]of l.trackData){let t=e.track;U(e.blocks.length>0);let n=!1;for(let t=0;t<e.blocks.length;t++){let r=e.blocks[t];r.timestamp+=l.timestamp,n||=r.lacing!==tP.None}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){let r=e.presentationTimestamps[n],i=e.blocks[r.blockIndex];e.firstKeyFrameTimestamp===null&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.timestamp),n<e.presentationTimestamps.length-1?i.duration=e.presentationTimestamps[n+1].timestamp-i.timestamp:i.duration===0&&t.defaultDuration!=null&&i.lacing===tP.None&&(i.duration=t.defaultDuration)}n&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let i=e.blocks[e.presentationTimestamps[0].blockIndex],a=e.blocks[jk(e.presentationTimestamps).blockIndex];e.startTimestamp=i.timestamp,e.endTimestamp=a.timestamp+a.duration;let o=Zk(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);(o===-1||t.clusterPositionCache[o].elementStartPos!==r)&&t.clusterPositionCache.splice(o+1,0,{elementStartPos:l.elementStartPos,startTimestamp:e.startTimestamp})}return t.lastReadCluster=l,l}getTrackDataInCluster(e,t){let n=e.trackData.get(t);if(!n){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;n={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,n)}return n}expandLacedBlocks(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(r.lacing===tP.None)continue;r.decoded||=(r.data=this.decodeBlockData(t,r.data),!0);let i=OF.tempFromBytes(r.data),a=[],o=J(i)+1;switch(r.lacing){case tP.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;i.bufferPos<i.length;){let n=J(i);if(t+=n,n<255){a.push(t),e+=t;break}}}a.push(i.length-(i.bufferPos+e))}break;case tP.FixedSize:{let e=i.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)a.push(t)}break;case tP.Ebml:{let e=HN(i);U(e!==null);let t=e;a.push(t);let n=t;for(let e=1;e<o-1;e++){let e=i.bufferPos,r=HN(i);U(r!==null);let o=r-((1<<(i.bufferPos-e)*7-1)-1);t+=o,a.push(t),n+=t}a.push(i.length-(i.bufferPos+n))}break;default:U(!1)}U(a.length===o),e.splice(n,1);let s=r.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let c=a[t],l=q(i,c),u=r.timestamp+s*t/o,d=s/o;e.splice(n+t,0,{timestamp:u,duration:d,isKeyFrame:r.isKeyFrame,data:l,lacing:tP.None,decoded:!0,mainAdditional:r.mainAdditional})}n+=o,n--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if(!(t.id===G.Tags&&!e.tagsSeen)&&!(t.id===G.Attachments&&!e.attachmentsSeen))continue;let n=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(n instanceof Promise&&(n=await n),!n)continue;let r=KN(n);if(!r||r.id!==t.id)continue;let{size:i}=r;$N(i),U(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(n.filePos,i);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===G.Tags?e.tagsSeen=!0:t.id===G.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let n=e.filePos;if(!this.traverseElement(e,t))return n}return e.filePos}traverseElement(e,t){let n=KN(e);if(!n||t&&t.includes(n.id))return!1;let{id:r,size:i}=n,a=e.filePos;switch($N(i),r){case G.DocType:this.isWebM=qN(e,i)===`webm`;break;case G.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(a,i)),(t.id===-1||t.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case G.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=K(e,i)}break;case G.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=K(e,i)}break;case G.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=K(e,i),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case G.Duration:if(!this.currentSegment)break;this.currentSegment.duration=YN(e,i);break;case G.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...zA},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:`und`,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,i)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!==`decompress`||e.scope!==nP.Block||e.data.algorithm!==rP.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf(`/`),t=e===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if(this.currentTrack.info.type===`video`&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e)}this.currentTrack.codecId===QN.avc?(this.currentTrack.info.codec=`avc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===QN.hevc?(this.currentTrack.info.codec=`hevc`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===QN.vp8?this.currentTrack.info.codec=`vp8`:t===QN.vp9?this.currentTrack.info.codec=`vp9`:t===QN.av1&&(this.currentTrack.info.codec=`av1`);let e=this.currentTrack,n=new vN(this.input,new cP(e));this.currentTrack.inputTrack=n,this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type===`audio`&&this.currentTrack.info.numberOfChannels!==-1&&this.currentTrack.info.sampleRate!==-1){t===QN.aac?(this.currentTrack.info.codec=`aac`,this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes(`MPEG2`),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===QN.mp3?this.currentTrack.info.codec=`mp3`:t===QN.opus?(this.currentTrack.info.codec=`opus`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=cj):t===QN.vorbis?(this.currentTrack.info.codec=`vorbis`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===QN.flac?(this.currentTrack.info.codec=`flac`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===QN.ac3?(this.currentTrack.info.codec=`ac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===QN.eac3?(this.currentTrack.info.codec=`eac3`,this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===`A_PCM/INT/LIT`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32`):this.currentTrack.codecId===`A_PCM/INT/BIG`?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec=`pcm-u8`:this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec=`pcm-s16be`:this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec=`pcm-s24be`:this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec=`pcm-s32be`):this.currentTrack.codecId===`A_PCM/FLOAT/IEEE`&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec=`pcm-f32`:this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec=`pcm-f64`));let e=this.currentTrack,n=new yN(this.input,new lP(e));this.currentTrack.inputTrack=n,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case G.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=K(e,i);break;case G.TrackType:{if(!this.currentTrack)break;let t=K(e,i);t===1?this.currentTrack.info={type:`video`,width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:t===2&&(this.currentTrack.info={type:`audio`,numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case G.FlagEnabled:if(!this.currentTrack)break;K(e,i)||(this.currentTrack=null);break;case G.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!K(e,i);break;case G.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!K(e,i);break;case G.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!K(e,i);break;case G.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!K(e,i);break;case G.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!K(e,i);break;case G.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!K(e,i);break;case G.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=qN(e,i);break;case G.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=q(e,i);break;case G.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=K(e,i);break;case G.Name:if(!this.currentTrack)break;this.currentTrack.name=JN(e,i);break;case G.Language:if(!this.currentTrack||this.currentTrack.languageCode!==`und`)break;this.currentTrack.languageCode=qN(e,i),gA(this.currentTrack.languageCode)||(this.currentTrack.languageCode=`und`);break;case G.LanguageBCP47:{if(!this.currentTrack)break;let t=qN(e,i).split(`-`)[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode=`und`}break;case G.Video:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case G.PixelWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.width=K(e,i);break;case G.PixelHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.height=K(e,i);break;case G.DisplayWidth:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayWidth=K(e,i);break;case G.DisplayHeight:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayHeight=K(e,i);break;case G.DisplayUnit:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.displayUnit=K(e,i);break;case G.AlphaMode:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.alphaMode=K(e,i)===1;break;case G.Colour:if(this.currentTrack?.info?.type!==`video`)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,i));break;case G.MatrixCoefficients:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Wk[K(e,i)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case G.Range:if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=K(e,i)===2;break;case G.TransferCharacteristics:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Hk[K(e,i)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case G.Primaries:{if(this.currentTrack?.info?.type!==`video`||!this.currentTrack.info.colorSpace)break;let t=Bk[K(e,i)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case G.Projection:if(this.currentTrack?.info?.type!==`video`)break;this.readContiguousElements(e.slice(a,i));break;case G.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!==`video`)break;let t=-YN(e,i);try{this.currentTrack.info.rotation=Ak(t)}catch{}}break;case G.Audio:if(this.currentTrack?.info?.type!==`audio`)break;this.readContiguousElements(e.slice(a,i));break;case G.SamplingFrequency:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.sampleRate=YN(e,i);break;case G.Channels:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.numberOfChannels=K(e,i);break;case G.BitDepth:if(this.currentTrack?.info?.type!==`audio`)break;this.currentTrack.info.bitDepth=K(e,i);break;case G.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,i)),this.currentCueTime=null;break;case G.CueTime:this.currentCueTime=K(e,i);break;case G.CueTrackPositions:{if(this.currentCueTime===null)break;U(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(a,i)),(t.trackId===-1||t.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case G.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=K(e,i)}break;case G.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;U(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+K(e,i)}break;case G.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=K(e,i);break;case G.SimpleBlock:{if(!this.currentCluster)break;let t=HN(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=NF(e),o=J(e),s=o>>1&3,c=!!(o&128);n.track.info?.type===`audio`&&n.track.info.codec&&(c=!0);let l=q(e,i-(e.filePos-a)),u=n.track.decodingInstructions.length>0;n.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!u,mainAdditional:null})}break;case G.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,i)),this.currentBlock=null;break;case G.Block:{if(!this.currentCluster)break;let t=HN(e);if(t===null)break;let n=this.getTrackDataInCluster(this.currentCluster,t);if(!n)break;let r=NF(e),o=J(e)>>1&3;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:q(e,i-(e.filePos-a)),lacing:o,decoded:!(n.track.decodingInstructions.length>0),mainAdditional:null},n.blocks.push(this.currentBlock)}break;case G.BlockAdditions:this.readContiguousElements(e.slice(a,i));break;case G.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,i)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case G.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=q(e,i);break;case G.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=K(e,i);break;case G.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=K(e,i);break;case G.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case G.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,i));break;case G.Targets:this.readContiguousElements(e.slice(a,i));break;case G.TargetTypeValue:K(e,i)!==50&&(this.currentTagTargetIsMovie=!1);break;case G.TagTrackUID:case G.TagEditionUID:case G.TagChapterUID:case G.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case G.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,i));break;case G.TagName:this.currentSimpleTagName=JN(e,i);break;case G.TagString:{if(!this.currentSimpleTagName)break;let t=JN(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case G.TagBinary:{if(!this.currentSimpleTagName)break;let t=q(e,i);this.processTagValue(this.currentSimpleTagName,t)}break;case G.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,i));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new LA(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith(`image/`)&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,n=`unknown`;if(e){let t=e.toLowerCase();t.startsWith(`cover.`)?n=`coverFront`:t.startsWith(`back.`)&&(n=`coverBack`)}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:n,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case G.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=UN(e,i);break;case G.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=JN(e,i);break;case G.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=qN(e,i);break;case G.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=q(e,i);break;case G.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=JN(e,i);break;case G.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,i)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case G.ContentEncoding:this.currentDecodingInstruction={order:0,scope:nP.Block,data:null},this.readContiguousElements(e.slice(a,i)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case G.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=K(e,i);break;case G.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=K(e,i);break;case G.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decompress`,algorithm:rP.Zlib,settings:null},this.readContiguousElements(e.slice(a,i));break;case G.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.algorithm=K(e,i);break;case G.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!==`decompress`)break;this.currentDecodingInstruction.data.settings=q(e,i);break;case G.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:`decrypt`};break}return e.filePos=a+i,!0}decodeBlockData(e,t){U(e.decodingInstructions.length>0);let n=t;for(let t of e.decodingInstructions)switch(U(t.data),t.data.type){case`decompress`:switch(t.data.algorithm){case rP.HeaderStripping:if(t.data.settings&&t.data.settings.length>0){let e=t.data.settings,r=new Uint8Array(e.length+n.length);r.set(e,0),r.set(n,e.length),n=r}break;default:}break;default:}return n}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let n=this.currentSegment.metadataTags;if(n.raw??={},n.raw[e]??=t,typeof t==`string`)switch(e.toLowerCase()){case`title`:n.title??=t;break;case`description`:n.description??=t;break;case`artist`:n.artist??=t;break;case`album`:n.album??=t;break;case`album_artist`:n.albumArtist??=t;break;case`genre`:n.genre??=t;break;case`comment`:n.comment??=t;break;case`lyrics`:n.lyrics??=t;break;case`date`:{let e=new Date(t);Number.isNaN(e.getTime())||(n.date??=e)}break;case`track_number`:case`part_number`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`disc_number`:case`disc`:{let e=t.split(`/`),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(n.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break}}},sP=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.inputTrack.type,n=0;for(let r of e.segments)for(let e of r.tracks)if(e.inputTrack.type===t&&n++,e===this.internalTrack)break;return n}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return dA(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=Zk(t.presentationTimestamps,n,e=>e.timestamp);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id);if(n.blockIndex+1<t.blocks.length)return{blockIndex:n.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let n=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=tA(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=n);return{blockIndex:r===-1?-1:t.presentationTimestamps[r].blockIndex,correctBlockFound:r!==-1&&n<t.endTimestamp}},n,n,t)}async getNextKeyPacket(e,t){let n=this.packetToClusterLocation.get(e);if(n===void 0)throw Error(`Packet was not created from this track.`);return this.performClusterLookup(n.cluster,e=>{if(e===n.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>n.blockIndex);if(t!==-1)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&t.firstKeyFrameTimestamp!==null){let e=t.blocks.findIndex(e=>e.isKeyFrame);return U(e!==-1),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,n){if(t===-1)return null;let r=e.trackData.get(this.internalTrack.id).blocks[t];U(r),r.decoded||=(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),!0);let i=n.metadataOnly?AM:r.data,a=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,s={};r.mainAdditional&&this.internalTrack.info?.type===`video`&&this.internalTrack.info.alphaMode&&(s.alpha=n.metadataOnly?AM:r.mainAdditional,s.alphaByteLength=r.mainAdditional.byteLength);let c=new jM(i,r.isKeyFrame?`key`:`delta`,a,o,e.dataStartPos+t,r.data.byteLength,s);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,n,r,i){let{demuxer:a,segment:o}=this.internalTrack,s=null,c=null,l=-1;if(e){let{blockIndex:n,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,n,i);n!==-1&&(c=e,l=n)}let u=Zk(this.internalTrack.cuePoints,n,e=>e.time),d=u===-1?null:this.internalTrack.cuePoints[u],f=Zk(this.internalTrack.clusterPositionCache,n,e=>e.startTimestamp),p=f===-1?null:this.internalTrack.clusterPositionCache[f],m=Math.max(d?.clusterPosition??0,p?.elementStartPos??0)||null,h;for(e?m===null||e.elementStartPos>=m?(h=e.elementEndPos,s=e):h=m:h=m??o.clusterSeekStartPos;o.elementEndPos===null||h<=o.elementEndPos-2;){if(s){let e=s.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=a.reader.requestSliceRange(h,2,16);if(e instanceof Promise&&(e=await e),!e)break;let n=h,u=KN(e);if(!u||!zN.includes(u.id)&&u.id!==G.Void){let e=await ZN(a.reader,n,zN,Math.min(o.elementEndPos??1/0,n+aP));if(e){h=e;continue}else break}let d=u.id,f=u.size,p=e.filePos;if(d===G.Cluster){s=await a.readCluster(n,o),f=s.elementEndPos-p;let{blockIndex:e,correctBlockFound:r}=t(s);if(r)return this.fetchPacketInCluster(s,e,i);e!==-1&&(c=s,l=e)}f===void 0&&(U(d!==G.Cluster),f=(await XN(a.reader,p,BN,o.elementEndPos)).pos-p);let m=p+f;if(o.elementEndPos===null){let e=a.reader.requestSliceRange(m,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(WN(e)===G.Segment){o.elementEndPos=m;break}}h=m}if(d&&(!c||c.elementStartPos<d.clusterPosition)){let e=this.internalTrack.cuePoints[u-1];U(!e||e.time<d.time);let n=e?.time??-1/0;return this.performClusterLookup(null,t,n,r,i)}return c?this.fetchPacketInCluster(c,l,i):null}},cP=class extends sP{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;return(this.internalTrack.info.codec===`vp9`||this.internalTrack.info.codec===`av1`||this.internalTrack.info.codec===`avc`&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec===`hevc`&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:aj({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec===`avc`&&e?Hj(e.data):null,hevcCodecInfo:this.internalTrack.info.codec===`hevc`&&e?Zj(e.data):null,vp9CodecInfo:this.internalTrack.info.codec===`vp9`&&e?oM(e.data):null,av1CodecInfo:this.internalTrack.info.codec===`av1`&&e?cM(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,displayAspectWidth:this.internalTrack.info.squarePixelWidth,displayAspectHeight:this.internalTrack.info.squarePixelHeight,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}},lP=class extends sP{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:sj({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},uP=async(e,t,n)=>{let r=t;for(;n===null||r<n;){let t=e.requestSlice(r,4);if(t instanceof Promise&&(t=await t),!t)break;let n=Dj(Y(t),e.fileSize===null?null:e.fileSize-r);if(n.header)return{header:n.header,startPos:r};r+=n.bytesAdvanced}return null},dP=class extends TM{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new qk,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw Error(`No valid MP3 frame found.`);this.tracks=[new yN(this.input,new fP(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=XF(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await uP(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let n=Ej(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+n,4);if(r instanceof Promise&&(r=await r),r){let e=Y(r);if(e===1483304551||e===1231971951)return}this.firstFrameHeader||=t,t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);let i=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:i,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return`audio/mpeg`}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return U(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let n=this.reader.requestSlice(e,10);if(n instanceof Promise&&(n=await n),!n)break;let r=XF(n);if(!r)break;t=!0;let i=this.reader.requestSlice(n.filePos,r.size);if(i instanceof Promise&&(i=await i),!i)break;ZF(i,r,this.metadataTags),e=n.filePos+r.size}if(!t&&this.reader.fileSize!==null&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),U(e),WF(e,3)===`TAG`&&JF(e,this.metadataTags)}return this.metadataTags}finally{e()}}},fP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`mp3`}getInternalCodecId(){return null}getNumberOfChannels(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...zA}}async getDecoderConfig(){return U(this.demuxer.firstFrameHeader),{codec:`mp3`,numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=AM;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=q(e,n.dataSize)}return new jM(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Xk(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Zk(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},pP=79764919,mP=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=t&2147483648?t<<1^pP:t<<1;mP[e]=t>>>0&4294967295}var hP=e=>{let t=Fk(e),n=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++){let n=e[t];r=(r<<8^mP[r>>>24^n])>>>0}return t.setUint32(22,n,!0),r},gP=(e,t,n)=>{let r=0,i=null;if(e.length>0)if(t.codec===`vorbis`){U(t.vorbisInfo);let a=t.vorbisInfo.modeBlockflags.length,o=(1<<mA(a-1))-1<<1,s=(e[0]&o)>>1;if(s>=t.vorbisInfo.modeBlockflags.length)throw Error(`Invalid mode number.`);let c=n,l=t.vorbisInfo.modeBlockflags[s];if(i=t.vorbisInfo.blocksizes[l],l===1){let n=(o|1)+1,r=e[0]&n?1:0;c=t.vorbisInfo.blocksizes[r]}r=c===null?0:c+i>>2}else t.codec===`opus`&&(r=dM(e).durationInSamples);return{durationInSamples:r,vorbisBlockSize:i}},_P=e=>{let t=`audio/ogg`;if(e.codecStrings){let n=[...new Set(e.codecStrings)];t+=`; codecs="${n.join(`, `)}"`}return t},vP=65307,yP=e=>{let t=e.filePos;if(FF(e)!==1399285583)return null;e.skip(1);let n=J(e),r=VF(e),i=FF(e),a=FF(e),o=FF(e),s=J(e),c=new Uint8Array(s);for(let t=0;t<s;t++)c[t]=J(e);let l=27+s,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:n,granulePosition:r,serialNumber:i,sequenceNumber:a,checksum:o,lacingValues:c}},bP=(e,t)=>{for(;e.filePos<t-3;){let t=FF(e),n=t&255,r=t>>>8&255,i=t>>>16&255,a=t>>>24&255;if(!(n!==79&&r!==79&&i!==79&&a!==79)){if(e.skip(-4),t===1399285583)return!0;e.skip(1)}}return!1},xP=class extends TM{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let n=yP(t);if(!n||!(n.headerType&2))break;this.bitstreams.push({serialNumber:n.serialNumber,bosPage:n,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=n.headerStartPos+n.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&t.data[0]===1&&t.data[1]===118&&t.data[2]===111&&t.data[3]===114&&t.data[4]===98&&t.data[5]===105&&t.data[6]===115?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&t.data[0]===79&&t.data[1]===112&&t.data[2]===117&&t.data[3]===115&&t.data[4]===72&&t.data[5]===101&&t.data[6]===97&&t.data[7]===100&&await this.readOpusMetadata(t,e),e.codecInfo.codec!==null&&this.tracks.push(new yN(this.input,new SP(e,this))))}})()}async readVorbisMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r||(n=await this.findNextPacketStart(r),!n))return;let i=await this.readPacket(n.startPage,n.startSegmentIndex);if(!i||r.data[0]!==3||i.data[0]!==5)return;let a=[],o=e=>{for(;a.push(Math.min(255,e)),!(e<255);)e-=255};o(e.data.length),o(r.data.length);let s=new Uint8Array(1+a.length+e.data.length+r.data.length+i.data.length);s[0]=2,s.set(a,1),s.set(e.data,1+a.length),s.set(r.data,1+a.length+e.data.length),s.set(i.data,1+a.length+e.data.length+r.data.length),t.codecInfo.codec=`vorbis`,t.description=s,t.lastMetadataPacket=i;let c=Fk(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);let l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:fM(i.data).modeBlockflags},hM(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let n=await this.findNextPacketStart(e);if(!n)return;let r=await this.readPacket(n.startPage,n.startSegmentIndex);if(!r)return;t.codecInfo.codec=`opus`,t.description=e.data,t.lastMetadataPacket=r;let i=lM(e.data);t.numberOfChannels=i.outputChannelCount,t.sampleRate=cj,t.codecInfo.opusInfo={preSkip:i.preSkip},hM(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){U(t<e.lacingValues.length);let n=0;for(let r=0;r<t;r++)n+=e.lacingValues[r];let r=e,i=n,a=t,o=[];outer:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);t instanceof Promise&&(t=await t),U(t);let s=q(t,r.dataSize);for(;;){if(a===r.lacingValues.length){o.push(s.subarray(n,i));break}let e=r.lacingValues[a];if(i+=e,e<255){o.push(s.subarray(n,i));break outer}a++}let c=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(c,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let n=yP(t);if(!n)return null;if(r=n,r.serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}n=0,i=0,a=0}let s=o.reduce((e,t)=>e+t.length,0);if(s===0)return null;let c=new Uint8Array(s),l=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,l),l+=t.length}return{data:c,endPage:r,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(e.endPage.headerType&4)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let n=this.reader.requestSliceRange(t,27,282);if(n instanceof Promise&&(n=await n),!n)return null;let r=yP(n);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),_P({codecStrings:(await Promise.all(this.tracks.map(e=>e.getCodecParameterString()))).filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},SP=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new qk,this.internalSampleRate=e.codecInfo.codec===`opus`?cj:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.tracks.findIndex(e=>e._backing.bitstream===this.bitstream);return U(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return U(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...zA}}async getFirstTimestamp(){return 0}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec===`opus`?(U(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,n){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:i}=gP(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new jM(n.metadataOnly?AM:e.data,`key`,Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:i}),a}async getFirstPacket(e){U(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let n=0;this.bitstream.codecInfo.codec===`opus`&&(U(this.bitstream.codecInfo.opusInfo),n-=this.bitstream.codecInfo.opusInfo.preSkip);let r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:n,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let n=this.encodedPacketToMetadata.get(e);if(!n)throw Error(`Packet was not created from this track.`);let r=await this.demuxer.findNextPacketStart(n.packet);if(!r)return null;let i=n.timestampInSamples+n.durationInSamples,a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:n.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);let n=dA(e*this.internalSampleRate);if(n===0)return this.getFirstPacket(t);if(n<0)return null;U(this.bitstream.lastMetadataPacket);let r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=r.startPage,a=this.demuxer.reader.fileSize,o=[i];outer:for(;i.headerStartPos+i.totalSize<a;){let e=i.headerStartPos,t=Math.floor((e+a)/2),r=t;for(;;){let e=Math.min(r+vP,a-27),s=this.demuxer.reader.requestSlice(r,e-r);if(s instanceof Promise&&(s=await s),U(s),!bP(s,e)){a=t+27;continue outer}let c=this.demuxer.reader.requestSliceRange(s.filePos,27,282);c instanceof Promise&&(c=await c),U(c);let l=yP(c);U(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);e instanceof Promise&&(e=await e),U(e),u=hP(q(e,l.totalSize))===l.checksum}if(!u){r=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){r=l.headerStartPos+l.totalSize;continue}if(l.granulePosition===-1){r=l.headerStartPos+l.totalSize;continue}this.granulePositionToTimestampInSamples(l.granulePosition)>n?a=l.headerStartPos:(i=l,o.push(l));continue outer}}let s=r.startPage;for(let e of o){if(e.granulePosition===i.granulePosition)break;(!s||e.headerStartPos>s.headerStartPos)&&(s=e)}let c=s,l=[c];for(;!(c.serialNumber===this.bitstream.serialNumber&&c.granulePosition===i.granulePosition);){let e=c.headerStartPos+c.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),U(t);let n=yP(t);U(n),c=n,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}U(c.granulePosition!==-1);let u=null,d,f,p=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)d=this.granulePositionToTimestampInSamples(0),f=!0,u=0;else{d=0,f=!1;for(let e=c.lacingValues.length-1;e>=0;e--)if(c.lacingValues[e]<255){u=e+1;break}if(u===null)throw Error(`Invalid page with granule position: no packets end on this page.`);m=u-1;let e={data:AM,endPage:p,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){let e=wP(l,c,u);U(e);let t=CP(l,e.page,e.segmentIndex);t&&(c=t.page,u=t.segmentIndex)}else for(;;){let e=wP(l,c,u);if(!e)break;let t=CP(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,u=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,m=e.segmentIndex;break}}}let h=null,g=null;for(;c!==null;){U(u!==null);let e=await this.demuxer.readPacket(c,u);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&u<r.startSegmentIndex)){let r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);U(r);let i=this.encodedPacketToMetadata.get(r);if(U(i),!f&&e.endPage.headerStartPos===p.headerStartPos&&e.endSegmentIndex===m?(d=this.granulePositionToTimestampInSamples(c.granulePosition),f=!0,r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:d-i.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),U(r),i=this.encodedPacketToMetadata.get(r),U(i)):d+=i.durationInSamples,h=r,g=i,f&&(Math.max(d,0)>n||Math.max(i.timestampInSamples,0)===n))break}let i=await this.demuxer.findNextPacketStart(e);if(!i)break;c=i.startPage,u=i.startSegmentIndex}return h}async getPacketSequential(e,t){let n=await this.sequentialScanMutex.acquire();try{let n=dA(e*this.internalSampleRate);e=n/this.internalSampleRate;let r=Zk(this.sequentialScanCache,n,e=>e.timestampInSamples),i;if(r!==-1){let e=this.sequentialScanCache[r];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let a=0;for(;i&&i.timestamp<e;){let n=await this.getNextPacket(i,t);if(!n||n.timestamp>e)break;if(i=n,a++,a===100){a=0;let e=this.encodedPacketToMetadata.get(i);U(e),this.sequentialScanCache.length>0&&U(jk(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},CP=(e,t,n)=>{let r=t,i=n;outer:for(;;){for(i--;i>=0;i--)if(r.lacingValues[i]<255){i++;break outer}if(U(i===-1),!(r.headerType&1)){i=0;break}let t=eA(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,i=r.lacingValues.length}if(U(i!==-1),i===r.lacingValues.length){let t=e[e.indexOf(r)+1];U(t),r=t,i=0}return{page:r,segmentIndex:i}},wP=(e,t,n)=>{if(n>0)return{page:t,segmentIndex:n-1};let r=eA(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null},TP;(function(e){e[e.PCM=1]=`PCM`,e[e.IEEE_FLOAT=3]=`IEEE_FLOAT`,e[e.ALAW=6]=`ALAW`,e[e.MULAW=7]=`MULAW`,e[e.EXTENSIBLE=65534]=`EXTENSIBLE`})(TP||={});var EP=class extends TM{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),U(e);let t=WF(e,4),n=t!==`RIFX`,r=t===`RF64`,i=PF(e,n),a=r?this.reader.fileSize:Math.min(i+8,this.reader.fileSize??1/0);if(WF(e,4)!==`WAVE`)throw Error(`Invalid WAVE file - wrong format`);let o=0,s=null,c=e.filePos;for(;a===null||c<a;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;let t=WF(e,4),i=PF(e,n),l=e.filePos;if(r&&o===0&&t!==`ds64`)throw Error(`Invalid RF64 file: First chunk must be "ds64".`);if(t===`fmt `)await this.parseFmtChunk(l,i,n);else if(t===`data`){if(s??=i,this.dataStart=e.filePos,this.dataSize=Math.min(s,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(t===`ds64`){let e=this.reader.requestSlice(l,i);if(e instanceof Promise&&(e=await e),!e)break;let t=RF(e,n);s=RF(e,n),a=Math.min(t+8,this.reader.fileSize??1/0)}else t===`LIST`?await this.parseListChunk(l,i,n):(t===`ID3 `||t===`id3 `)&&await this.parseId3Chunk(l,i);c=l+i+(i&1),o++}if(!this.audioInfo)throw Error(`Invalid WAVE file - missing "fmt " chunk`);if(this.dataStart===-1)throw Error(`Invalid WAVE file - missing "data" chunk`);let l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.tracks.push(new yN(this.input,new OP(this)))})()}async parseFmtChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=AF(r,n),a=AF(r,n),o=PF(r,n);r.skip(4);let s=AF(r,n),c;if(c=t===14?8:AF(r,n),t>=18&&i!==357){let e=AF(r,n),a=t-18;if(Math.min(a,e)>=22&&i===TP.EXTENSIBLE){r.skip(6);let e=q(r,16);i=e[0]|e[1]<<8}}(i===TP.MULAW||i===TP.ALAW)&&(c=8),this.audioInfo={format:i,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:s}}async parseListChunk(e,t,n){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=WF(r,4);if(i!==`INFO`&&i!==`INF0`)return;let a=r.filePos;for(;a<=e+t-8;){r.filePos=a;let e=WF(r,4),t=PF(r,n),i=q(r,t),o=0;for(let e=0;e<i.length&&i[e]!==0;e++)o++;let s=String.fromCharCode(...i.subarray(0,o));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=s,e){case`INAM`:case`TITL`:this.metadataTags.title??=s;break;case`TIT3`:this.metadataTags.description??=s;break;case`IART`:this.metadataTags.artist??=s;break;case`IPRD`:this.metadataTags.album??=s;break;case`IPRT`:case`ITRK`:case`TRCK`:{let e=s.split(`/`),t=Number.parseInt(e[0],10),n=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),n&&Number.isInteger(n)&&n>0&&(this.metadataTags.tracksTotal??=n)}break;case`ICRD`:case`IDIT`:{let e=new Date(s);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case`YEAR`:{let e=Number.parseInt(s,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case`IGNR`:case`GENR`:this.metadataTags.genre??=s;break;case`ICMT`:case`CMNT`:case`COMM`:this.metadataTags.comment??=s;break}a+=8+t+(t&1)}}async parseId3Chunk(e,t){let n=this.reader.requestSlice(e,t);if(n instanceof Promise&&(n=await n),!n)return;let r=XF(n);if(r){let i=t-10;r.size=Math.min(r.size,i),r.size>0&&ZF(n.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(U(this.audioInfo),this.audioInfo.format===TP.MULAW)return`ulaw`;if(this.audioInfo.format===TP.ALAW)return`alaw`;if(this.audioInfo.format===TP.PCM){if(this.audioInfo.sampleSizeInBytes===1)return`pcm-u8`;if(this.audioInfo.sampleSizeInBytes===2)return`pcm-s16`;if(this.audioInfo.sampleSizeInBytes===3)return`pcm-s24`;if(this.audioInfo.sampleSizeInBytes===4)return`pcm-s32`}return this.audioInfo.format===TP.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?`pcm-f32`:null}async getMimeType(){return`audio/wav`}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return U(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},DP=2048,OP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(U(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return{...zA}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,t){U(e>=0),U(this.demuxer.audioInfo);let n=e*DP*this.demuxer.audioInfo.blockSizeInBytes;if(n>=this.demuxer.dataSize)return null;let r=Math.min(DP*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-n);if(this.demuxer.reader.fileSize===null){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);if(e instanceof Promise&&(e=await e),!e)return null}let i;if(t.metadataOnly)i=AM;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+n,r);e instanceof Promise&&(e=await e),U(e),i=q(e,r)}let a=e*DP/this.demuxer.audioInfo.sampleRate,o=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new jM(i,`key`,a,o,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){U(this.demuxer.audioInfo);let n=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/DP,(this.demuxer.dataSize-1)/(DP*this.demuxer.audioInfo.blockSizeInBytes)));if(n<0)return null;let r=await this.getPacketAtIndex(n,t);if(r)return r;if(n===0)return null;U(this.demuxer.reader.fileSize===null);let i=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;i;){let e=await this.getNextPacket(i,t);if(!e)break;i=e}return i}getNextPacket(e,t){U(this.demuxer.audioInfo);let n=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/DP);return this.getPacketAtIndex(n+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},kP=e=>{let t=e.filePos,n=new VA(q(e,9));if(n.readBits(12)!==4095||(n.skipBits(1),n.readBits(2)!==0))return null;let r=n.readBits(1),i=n.readBits(2)+1,a=n.readBits(4);if(a===15)return null;n.skipBits(1);let o=n.readBits(3);if(o===0)throw Error(`ADTS frames with channel configuration 0 are not supported.`);n.skipBits(1),n.skipBits(1),n.skipBits(1),n.skipBits(1);let s=n.readBits(13);n.skipBits(11);let c=n.readBits(2)+1;if(c!==1)throw Error(`ADTS frames with more than one AAC frame are not supported.`);let l=null;return r===1?e.filePos-=2:l=n.readBits(16),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:s,numberOfAacFrames:c,crcCheck:l,startPos:t}},AP=1024,jP=class extends TM{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new qk,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();U(this.firstFrameHeader),this.tracks=[new yN(this.input,new MP(this))]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=XF(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=kP(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||=t;let n=HA[t.samplingFrequencyIndex];U(n!==void 0);let r=AP/n,i={timestamp:this.nextTimestampInSamples/n,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(i),this.nextTimestampInSamples+=AP,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return`audio/aac`}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();let e=this.tracks[0];return U(e),e.computeDuration()}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;let n=XF(t);if(!n)break;let r=this.reader.requestSlice(t.filePos,n.size);if(r instanceof Promise&&(r=await r),!r)break;ZF(r,n,this.metadataTags),e=t.filePos+n.size}return this.metadataTags}finally{e()}}},MP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/AP}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return`und`}getCodec(){return`aac`}getInternalCodecId(){return U(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){U(this.demuxer.firstFrameHeader);let e=UA[this.demuxer.firstFrameHeader.channelConfiguration];return U(e!==void 0),e}getSampleRate(){U(this.demuxer.firstFrameHeader);let e=HA[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return U(e!==void 0),e}getDisposition(){return{...zA}}async getDecoderConfig(){return U(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=AM;else{let e=this.demuxer.reader.requestSlice(n.dataStart,n.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=q(e,n.dataSize)}return new jM(r,`key`,n.timestamp,n.duration,e,n.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=Xk(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(n===-1)throw Error(`Packet was not created from this track.`);let r=n+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{n()}}async getPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Zk(this.demuxer.loadedSamples,e,e=>e.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},NP=e=>e===0?null:e===1?192:e>=2&&e<=5?144*2**e:e===6?`uncommon-u8`:e===7?`uncommon-u16`:e>=8&&e<=15?2**e:null,PP=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return`uncommon-u8`;case 13:return`uncommon-u16`;case 14:return`uncommon-u16-10`;default:return null}},FP=e=>{let t=0,n=new VA(q(e,1));for(;n.readBits(1)===1;)t++;if(t===0)return n.readBits(7);let r=[],i=t-1,a=new VA(q(e,i)),o=8-t-1;for(let e=0;e<o;e++)r.unshift(n.readBits(1));for(let e=0;e<i;e++)for(let e=0;e<8;e++){let t=a.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,n)=>e|t<<n,0)},IP=(e,t)=>{if(t===`uncommon-u16`)return jF(e)+1;if(t===`uncommon-u8`)return J(e)+1;if(typeof t==`number`)return t;iA(t),U(!1)},LP=(e,t)=>t===`uncommon-u16`?jF(e):t===`uncommon-u16-10`?jF(e)*10:t===`uncommon-u8`?J(e):typeof t==`number`?t:null,RP=e=>{let t=0;for(let n of e){t^=n;for(let e=0;e<8;e++)t&128?t=t<<1^7:t<<=1,t&=255}return t},zP=class extends TM{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new qk,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),U(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),U(this.track),[this.track]}async getMimeType(){return`audio/flac`}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;this.reader.fileSize===null||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,t===null)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);U(t);let n=J(t),r=MF(t),i=(n&128)!=0;switch(n&127){case mM.STREAMINFO:{let t=this.reader.requestSlice(e,r);if(t instanceof Promise&&(t=await t),U(t),t===null)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let n=q(t,34),i=new VA(n),a=i.readBits(16),o=i.readBits(16),s=i.readBits(24),c=i.readBits(24),l=i.readBits(20),u=i.readBits(3)+1;i.readBits(5);let d=i.readBits(36);i.skipBits(128);let f=new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(n,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:a,maximumBlockSize:o,minimumFrameSize:s,maximumFrameSize:c,description:f},this.track=new yN(this.input,new BP(this));break}case mM.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),U(t),hM(q(t,r),this.metadataTags);break}case mM.PICTURE:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),U(t);let n=Y(t),i=Y(t),a=Ik.decode(q(t,i)),o=Y(t),s=Ik.decode(q(t,o));t.skip(16);let c=Y(t),l=q(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:l,mimeType:a,kind:n===3?`coverFront`:n===4?`coverBack`:`unknown`,description:s});break}default:break}if(e+=r,i){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){U(this.audioInfo);let n=this.audioInfo.maximumFrameSize+16,r=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,n);if(!r)return null;let i=this.readFlacFrameHeader({slice:r,isFirstPacket:t});if(!i)return null;for(r.filePos=e+this.audioInfo.minimumFrameSize;;){if(r.filePos>r.end-6)return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:r.end-e,isLastFrame:!0};if(J(r)===255){let t=r.filePos;if(J(r)!==(this.blockingBit===1?249:248)){r.filePos=t;continue}r.skip(-2);let n=r.filePos-e,a=this.readFlacFrameHeader({slice:r,isFirstPacket:!1});if(!a){r.filePos=t;continue}if(this.blockingBit===0){if(a.num-i.num!==1){r.filePos=t;continue}}else if(a.num-i.num!==i.blockSize){r.filePos=t;continue}return{num:i.num,blockSize:i.blockSize,sampleRate:i.sampleRate,size:n,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let n=e.filePos,r=new VA(q(e,4));if(r.readBits(15)!==32764)return null;if(this.blockingBit===null)U(t),this.blockingBit=r.readBits(1);else if(this.blockingBit===1){if(U(!t),r.readBits(1)!==1)return null}else if(this.blockingBit===0){if(U(!t),r.readBits(1)!==0)return null}else throw Error(`Invalid blocking bit`);let i=NP(r.readBits(4));if(!i)return null;U(this.audioInfo);let a=PP(r.readBits(4),this.audioInfo.sampleRate);if(!a||(r.readBits(4),r.readBits(3),r.readBits(1)!==0))return null;let o=FP(e),s=IP(e,i),c=LP(e,a);if(c===null||c!==this.audioInfo.sampleRate)return null;let l=e.filePos-n,u=J(e);return e.skip(-l),e.skip(-1),u===RP(q(e,l))?{num:o,blockSize:s,sampleRate:c}:null}async advanceReader(){await this.readMetadata(),U(this.lastLoadedPos!==null),U(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}let n=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:n?n.blockOffset+n.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos+=t.size,this.loadedSamples.push(r),t.isLastFrame){this.lastSampleLoaded=!0;return}}},BP=class{constructor(e){this.demuxer=e}getId(){return 1}getNumber(){return 1}getCodec(){return`flac`}getInternalCodecId(){return null}getNumberOfChannels(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return`und`}getTimeResolution(){return U(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...zA}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return U(this.demuxer.audioInfo),{codec:`flac`,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(U(this.demuxer.audioInfo),e<0)throw Error(`Timestamp cannot be negative`);let n=await this.demuxer.readingMutex.acquire();try{for(;;){let n=Zk(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[n];if(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{n()}}async getNextPacket(e,t){let n=await this.demuxer.readingMutex.acquire();try{let n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{n()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let n=this.demuxer.loadedSamples[e];if(!n)return null;let r;if(t.metadataOnly)r=AM;else{let e=this.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;r=q(e,n.byteSize)}U(this.demuxer.audioInfo);let i=n.blockOffset/this.demuxer.audioInfo.sampleRate,a=n.blockSize/this.demuxer.audioInfo.sampleRate;return new jM(r,`key`,i,a,e,n.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},VP=9e4,HP=e=>{let t=`video/MP2T`,n=[...new Set(e.filter(Boolean))];return n.length>0&&(t+=`; codecs="${n.join(`, `)}"`),t},UP=class extends TM{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.tracks=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),U(e);let t=q(e,205);if(t[0]===71&&t[188]===71)this.packetOffset=0,this.packetStride=188;else if(t[0]===71&&t[204]===71)this.packetOffset=0,this.packetStride=204;else if(t[4]===71&&t[196]===71)this.packetOffset=4,this.packetStride=192;else throw Error(`Unreachable.`);this.minReferencePointByteDistance=256*this.packetStride;let n=this.packetOffset,r=null,i=!1,a=!1;for(;;){let e=await this.readPacketHeader(n);if(!e)break;if(e.payloadUnitStartIndicator===0){n+=this.packetStride;continue}let t=await this.readSection(n,!0,!a);if(!t)break;let o=!1;if(!a&&t.pid!==0&&!(t.payload[0]===0&&t.payload[1]===0&&t.payload[2]===1)){let e=new VA(t.payload),n=e.readAlignedByte();e.skipBits(8*n),o=e.readBits(8)===2}if(t.pid===0&&!i){let e=new VA(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(14);let a=e.readBits(10);for(e.skipBits(40);8*(a+3)-e.pos>32;){let t=e.readBits(16);if(e.skipBits(3),t!==0){if(r!==null)throw Error(`Only files with a single program are supported.`);r=e.readBits(13)}}if(r===null)throw Error(`Program Association Table must link to a Program Map Table.`);i=!0}else if((t.pid===r||o)&&!a){let e=new VA(t.payload),n=e.readAlignedByte();e.skipBits(8*n),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let i=e.readBits(10);for(e.skipBits(8*i);8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let n=e.readBits(13);e.skipBits(6);let r=e.readBits(10),i=e.pos+8*r,a=!1,o=!1;for(;e.pos<i;){let t=e.readBits(8),n=e.readBits(8);t===106?a=!0:(t===122||t===204)&&(o=!0),e.skipBits(8*n)}let s=null;switch(t){case 3:case 4:case 15:s={type:`audio`,codec:t===15?`aac`:`mp3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 27:case 36:s={type:`video`,codec:t===27?`avc`:`hevc`,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 129:s={type:`audio`,codec:`ac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 135:s={type:`audio`,codec:`eac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1};break;case 6:o?s={type:`audio`,codec:`eac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:a&&(s={type:`audio`,codec:`ac3`,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:console.warn(`Unsupported stream_type 0x${t.toString(16)}; ignoring stream.`)}s&&this.elementaryStreams.push({demuxer:this,pid:n,streamType:t,initialized:!1,firstSection:null,info:s,referencePesPackets:[]})}a=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);if(e&&!e.initialized){let n=GP(t);if(!n)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.info.type===`video`)if(e.info.codec===`avc`){if(e.info.avcCodecInfo=Hj(n.data),!e.info.avcCodecInfo)throw Error(`Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from first packet.`);let t=e.info.avcCodecInfo.sequenceParameterSets[0];U(t);let r=Kj(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:Bk[r.colourPrimaries],transfer:Hk[r.transferCharacteristics],matrix:Wk[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering,e.initialized=!0}else if(e.info.codec===`hevc`){if(e.info.hevcCodecInfo=Zj(n.data),!e.info.hevcCodecInfo)throw Error(`Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.`);let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Mj.SPS_NUT).nalUnits[0];U(t);let r=Xj(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:Bk[r.colourPrimaries],transfer:Hk[r.transferCharacteristics],matrix:Wk[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering,e.initialized=!0}else throw Error(`Unhandled.`);else if(e.info.codec===`aac`){let t=kP(OF.tempFromBytes(n.data));if(!t)throw Error(`Invalid AAC audio stream; could not read ADTS frame header from first packet.`);e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=UA[t.channelConfiguration],e.info.sampleRate=HA[t.samplingFrequencyIndex],e.initialized=!0}else if(e.info.codec===`mp3`){let t=Dj(Y(OF.tempFromBytes(n.data)),n.data.byteLength);if(!t.header)throw Error(`Invalid MP3 audio stream; could not read frame header from first packet.`);e.info.numberOfChannels=t.header.channel===3?1:2,e.info.sampleRate=t.header.sampleRate,e.initialized=!0}else if(e.info.codec===`ac3`){let t=_M(n.data);if(!t)throw Error(`Invalid AC-3 audio stream; could not read sync frame from first packet.`);if(t.fscod===3)throw Error(`Invalid AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=gM[t.acmod]+t.lfeon,e.info.sampleRate=kj[t.fscod],e.initialized=!0}else if(e.info.codec===`eac3`){let t=xM(n.data);if(!t)throw Error(`Invalid E-AC-3 audio stream; could not read sync frame from first packet.`);let r=CM(t);if(r===null)throw Error(`Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.`);e.info.numberOfChannels=wM(t),e.info.sampleRate=r,e.initialized=!0}else throw Error(`Unhandled.`)}}if(a&&this.elementaryStreams.every(e=>e.initialized))break;n+=this.packetStride}if(!a)throw i?Error(`No Program Map Table found in the file.`):Error(`No Program Association Table found in the file.`);for(let e of this.elementaryStreams)e.info.type===`video`?this.tracks.push(new vN(this.input,new qP(e))):this.tracks.push(new yN(this.input,new JP(e)))})()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return{}}async computeDuration(){let e=await this.getTracks(),t=await Promise.all(e.map(e=>e.computeDuration()));return Math.max(0,...t)}async getMimeType(){await this.readMetadata();let e=await this.getTracks();return HP(await Promise.all(e.map(e=>e.getCodecParameterString())))}async readSection(e,t,n=!1){let r=e,i=e,a=[],o=0,s=null,c=!0,l=0;for(;;){let e=await this.readPacket(i);if(i+=this.packetStride,!e)break;if(s){if(e.pid!==s.pid){if(n)break;continue}if(e.payloadUnitStartIndicator===1)break}else{if(e.payloadUnitStartIndicator===0)break;s=e}let u=!!(e.adaptationFieldControl&2),d=!!(e.adaptationFieldControl&1),f=0;if(u&&(f=1+e.body[0],e===s&&f>1&&(l=e.body[1]>>6&1)),d&&(f===0?(a.push(e.body),o+=e.body.byteLength):(a.push(e.body.subarray(f)),o+=e.body.byteLength-f)),r=i,!t&&o>=64){c=!1;break}if(Xk(this.sectionEndPositions,r,e=>e)!==-1){c=!1;break}}if(c){let e=Zk(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!s)return null;let u;if(a.length===1)u=a[0];else{let e=a.reduce((e,t)=>e+t.length,0);u=new Uint8Array(e);let t=0;for(let e of a)u.set(e,t),t+=e.length}return{startPos:e,endPos:t?r:null,pid:s.pid,payload:u,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(J(t)!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let n=jF(t);n>>15;let r=n>>14&1;n>>13&1;let i=n&8191,a=J(t);a>>6;let o=a>>4&3;return a&15,{payloadUnitStartIndicator:r,pid:i,adaptationFieldControl:o}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let n=q(t,188);if(n[0]!==71)throw Error(`Invalid TS packet sync byte. Likely an internal bug, please report this file.`);let r=(n[1]<<8)+n[2];r>>15;let i=r>>14&1;r>>13&1;let a=r&8191,o=n[3];o>>6;let s=o>>4&3;return o&15,{payloadUnitStartIndicator:i,pid:a,adaptationFieldControl:s,body:n.subarray(4)}}},WP=e=>{if(e.payload.byteLength<3)return null;let t=new VA(e.payload);if(t.readBits(24)!==1)return null;let n=t.readBits(8);if(t.skipBits(16),n===188||n===190||n===191||n===240||n===241||n===255||n===242||n===248)return null;t.skipBits(8);let r=t.readBits(2);t.skipBits(14);let i=0;if(r===2||r===3)t.skipBits(4),i+=t.readBits(3)*(1<<30),t.skipBits(1),i+=t.readBits(15)*32768,t.skipBits(1),i+=t.readBits(15);else throw Error(`PES packets without PTS are not currently supported. If you think this file should be supported, please report it.`);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:i,randomAccessIndicator:e.randomAccessIndicator}},GP=e=>{U(e.endPos!==null);let t=WP(e);if(!t)return null;let n=new VA(e.payload);n.skipBits(32);let r=n.readBits(16);n.skipBits(16);let i=n.readBits(8),a=n.pos+8*i;n.pos=a;let o=a/8;U(Number.isInteger(o));let s=e.payload.subarray(o,r>0?6+r:e.payload.byteLength);return{...t,data:s}},KP=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let t=this.elementaryStream.demuxer,n=this.elementaryStream.info.type,r=0;for(let i of t.tracks)if(i.type===n&&r++,U(i._backing instanceof e),i._backing.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw Error(`Not implemented on base class.`)}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return`und`}getDisposition(){return zA}getTimeResolution(){return VP}async computeDuration(){let e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){return(await this.getFirstPacket({metadataOnly:!0}))?.timestamp??0}createEncodedPacket(e,t,n){let r;return r=this.allPacketsAreKeyPackets()||e.randomAccessIndicator===1?`key`:`delta`,new jM(n.metadataOnly?AM:e.data,r,e.pts/VP,Math.max(t/VP,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;U(t);let n=GP(t);U(n);let r=new ZP(this.elementaryStream,n),i=new QP(this,r),a=await i.readNext();if(!a)return null;let o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,i),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let n=this.packetBuffers.get(e);if(n){let r=await n.readNext();if(!r)return null;this.packetBuffers.delete(e);let i=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(i,n),this.packetSectionStarts.set(i,r.packet.sectionStartPos),i}let r=this.packetSectionStarts.get(e);if(r===void 0)throw Error(`Packet was not created from this track.`);let i=await this.elementaryStream.demuxer.readSection(r,!0);U(i);let a=GP(i);U(a);let o=new ZP(this.elementaryStream,a);n=new QP(this,o);let s=e.sequenceNumber;for(;;){let e=await n.readNext();if(!e)return null;if(e.packet.sequenceNumber>s){let r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,n),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let n=e;for(;;){if(n=await this.getNextPacket(n,t),!n)return null;if(n.type===`key`)return n}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,n){let r=dA(e*VP),i=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=i,s=this.elementaryStream.pid,c=async(e,t)=>{let n=e;for(;n<t;){let e=await i.readPacketHeader(n);if(!e)return null;if(e.pid===s&&e.payloadUnitStartIndicator===1){let e=await i.readSection(n,!1);if(!e)return null;let t=WP(e);if(t)return t}n+=i.packetStride}return null},l=this.elementaryStream.firstSection;U(l);let u=WP(l);if(U(u),r<u.pts)return null;let d,f=this.elementaryStream.referencePesPackets,p=Zk(f,r,e=>e.pts),m=p===-1?null:f[p];if(m&&r-m.pts<9e4/2)d=m.sectionStartPos;else{let e=0;if(a.fileSize!==null){let t=Math.ceil(a.fileSize/o);if(t>1){let n=0,a=t-1;for(e=n;n<=a;){let t=Math.floor((n+a)/2),s=pA(t*o,i.packetStride)+u.sectionStartPos,l=await c(s,s+o);if(!l){a=t-1;continue}l.pts<=r?(e=t,n=t+1):a=t-1}}}d=pA(e*o,i.packetStride)+u.sectionStartPos}let h=await c(d,a.fileSize??1/0);h||=u;let g=this.getReorderSize(),_=async(e,t)=>{let a=await i.readSection(e,!0);U(a);let o=GP(a);U(o);let s=new ZP(this.elementaryStream,o),c=new QP(this,s);for(;!((jk(c.presentationOrderPackets)?.pts??-1/0)>=r||!await c.readNextPacket()););let l=tA(c.presentationOrderPackets,t);if(l===-1)return null;let u=c.presentationOrderPackets[l],d=l===0?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=d;let f=await c.readNext();U(f);let p=this.createEncodedPacket(f.packet,f.duration,n);return this.packetBuffers.set(p,c),this.packetSectionStarts.set(p,f.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){outer:for(;;){let e=h.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=WP(t);if(e){if(e.pts>r)break outer;h=e,YP(this.elementaryStream,e);break}}}e+=i.packetStride}}outer:for(let e=0;e<g;e++){let e=h.sectionStartPos-i.packetStride;for(;e>=i.packetOffset;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t){let e=WP(t);if(e){h=e;break}}}e-=i.packetStride}}return _(h.sectionStartPos,e=>e.pts<=r)}else{let e=d,t=null;for(;;){let n=null,l=e<=u.sectionStartPos,d;l?(d=u,n=u):d=await c(e,a.fileSize??1/0);let f=!1,p=0;outer:for(;d&&!(t!==null&&d.sectionStartPos>=t||(d.randomAccessIndicator===1&&d.pts<=r&&(n=d),d.pts>r&&(f=!0),f&&(p++,p>=g)));){let e=d.sectionStartPos+i.packetStride;for(;;){let t=await i.readPacketHeader(e);if(!t)break outer;if(t.pid===s&&t.payloadUnitStartIndicator===1){let t=await i.readSection(e,!1);if(t&&(d=WP(t),d)){YP(this.elementaryStream,d);break}}e+=i.packetStride}}if(n){let e=n;if(p===0)outer:for(let t=0;t<g-1;t++){let t=e.sectionStartPos-i.packetStride;for(;t>=i.packetOffset;){let n=await i.readPacketHeader(t);if(!n)break outer;if(n.pid===s&&n.payloadUnitStartIndicator===1){let n=await i.readSection(t,!1);if(n){let t=WP(n);if(t){e=t;break}}}t-=i.packetStride}}let t=await _(e.sectionStartPos,e=>e.pts<=r&&e.randomAccessIndicator===1);return U(t),t}U(!l),t=e,e=Math.max(pA(e-u.sectionStartPos-o,i.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}},qP=class extends KP{constructor(e){super(e),this.elementaryStream=e,this.decoderConfig={codec:aj({width:this.elementaryStream.info.width,height:this.elementaryStream.info.height,codec:this.elementaryStream.info.codec,codecDescription:null,colorSpace:this.elementaryStream.info.colorSpace,avcType:1,avcCodecInfo:this.elementaryStream.info.avcCodecInfo,hevcCodecInfo:this.elementaryStream.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:this.elementaryStream.info.width,codedHeight:this.elementaryStream.info.height,displayAspectWidth:this.elementaryStream.info.squarePixelWidth,displayAspectHeight:this.elementaryStream.info.squarePixelHeight,colorSpace:this.elementaryStream.info.colorSpace}}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return this.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},JP=class extends KP{constructor(e){super(e),this.elementaryStream=e}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return{codec:sj({codec:this.elementaryStream.info.codec,codecDescription:null,aacCodecInfo:this.elementaryStream.info.aacCodecInfo}),numberOfChannels:this.elementaryStream.info.numberOfChannels,sampleRate:this.elementaryStream.info.sampleRate}}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 1}},YP=(e,t)=>{let n=e.referencePesPackets,r=Zk(n,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let i=n[r];if(t.pts<=i.pts)return!1;let a=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-i.sectionStartPos<a)return!1;if(r<n.length-1){let e=n[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<a)return!1}}return n.splice(r+1,0,t),!0},XP=async e=>{U(!e.suppliedPacket);let t=e.elementaryStream;if(t.info.type===`video`){let n=t.info.codec,r=1024;if(n!==`avc`&&n!==`hevc`)throw Error(`Unhandled.`);let i=null;for(;;){let t=e.ensureBuffered(r);if(t instanceof Promise&&(t=await t),t===0)break;let a=e.currentPos,o=e.readBytes(t),s=o.byteLength,c=0;for(;c<s;){let t=o.indexOf(0,c);if(t===-1||t>=s)break;c=t;let r=a+c;if(c+4>=s){e.seekTo(r);break}let l=o[c+1],u=o[c+2],d=o[c+3],f=0,p=null;if(l===0&&u===0&&d===1?(f=4,p=o[c+4]):l===0&&u===1&&(f=3,p=d),f===0){c++;continue}let m=r;if(i===null){i=m,c+=f;continue}if(p!==null){let t=n===`avc`?Ij(p):Yj(p);if(n===`avc`?t===jj.AUD:t===Mj.AUD_NUT){let t=m-i;return e.seekTo(i),e.supplyPacket(t,0)}}c+=f}if(t<r)break}if(i!==null){let t=e.endPos-i;return e.seekTo(i),e.supplyPacket(t,0)}}else{let n=t.info.codec;for(;;){let r=e.ensureBuffered(128);r instanceof Promise&&(r=await r);let i=e.currentPos;for(;e.currentPos-i<r;){let r=e.readU8();if(n===`aac`){if(r!==255)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(9);if(i instanceof Promise&&(i=await i),i<9)return;let a=e.readBytes(9),o=kP(OF.tempFromBytes(a));if(o){e.seekTo(n);let r=e.ensureBuffered(o.frameLength);return r instanceof Promise&&(r=await r),e.supplyPacket(r,Math.round(AP*VP/t.info.sampleRate))}else e.seekTo(n+1)}else if(n===`mp3`){if(r!==255)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;let a=Dj(Fk(e.readBytes(4)).getUint32(0),null);if(a.header){e.seekTo(n);let r=e.ensureBuffered(a.header.totalSize);r instanceof Promise&&(r=await r);let i=a.header.audioSamplesInFrame*VP/t.info.sampleRate;return e.supplyPacket(r,Math.round(i))}else e.seekTo(n+1)}else if(n===`ac3`){if(r!==11)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=e.readBytes(5);if(a[0]!==11||a[1]!==119){e.seekTo(n+1);continue}let o=a[4]>>6,s=a[4]&63;if(o===3||s>37){e.seekTo(n+1);continue}let c=vM[3*s+o];U(c!==void 0),e.seekTo(n),i=e.ensureBuffered(c),i instanceof Promise&&(i=await i);let l=Math.round(yM*VP/t.info.sampleRate);return e.supplyPacket(i,l)}else if(n===`eac3`){if(r!==11)continue;e.skip(-1);let n=e.currentPos,i=e.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=e.readBytes(5);if(a[0]!==11||a[1]!==119){e.seekTo(n+1);continue}let o=(((a[2]&7)<<8|a[3])+1)*2,s=bM[a[4]>>6==3?3:a[4]>>4&3];e.seekTo(n),i=e.ensureBuffered(o),i instanceof Promise&&(i=await i);let c=s*256,l=Math.round(c*VP/t.info.sampleRate);return e.supplyPacket(i,l)}else throw Error(`Unhandled.`)}if(r<128)break}}},ZP=class e{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.nextPts=0,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}clone(){let t=new e(this.elementaryStream,this.startingPesPacket);return t.currentPos=this.currentPos,t.pesPackets=[...this.pesPackets],t.currentPesPacketIndex=this.currentPesPacketIndex,t.currentPesPacketPos=this.currentPesPacketPos,t.endPos=this.endPos,t.nextPts=this.nextPts,t}ensureBuffered(e){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return U(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(this.pesPackets.length===0)e=this.startingPesPacket;else{let t=jk(this.pesPackets).sectionEndPos;for(U(t!==null);;){let n=await this.demuxer.readPacketHeader(t);if(!n)return;if(n.pid===this.pid){let n=await this.demuxer.readSection(t,!0);if(!n)return;let r=GP(n);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength,this.pesPackets.length===1&&(this.nextPts=e.pts)}}readBytes(e){let t=this.getCurrentPesPacket(),n=this.currentPos-this.currentPesPacketPos,r=n+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(n,r);let i=new Uint8Array(e);i.set(t.data.subarray(n));let a=t.data.byteLength-n;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),n=e-a;if(n<=t.data.byteLength){i.set(t.data.subarray(0,n),a);break}i.set(t.data,a),a+=t.data.byteLength}return i}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength,this.nextPts=e.pts}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++,this.nextPts=this.getCurrentPesPacket().pts}supplyPacket(e,t){let n=this.getCurrentPesPacket();YP(this.elementaryStream,n);let r=this.nextPts;this.nextPts+=t;let i=n.sectionStartPos,a=i+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),s=n.randomAccessIndicator;U(this.elementaryStream.firstSection),n.sectionStartPos===this.elementaryStream.firstSection.startPos&&(s=1),this.suppliedPacket={pts:r,data:o,sequenceNumber:a,sectionStartPos:i,randomAccessIndicator:s},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},QP=class{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),U(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);U(t!==-1);let n;for(t===this.presentationOrderPackets.length-1?n=this.lastDuration:(n=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=n),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:n}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await XP(this.context),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){let e=this.decodeOrderPackets[0];for(U(e);;){let t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>=this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer.splice(e,1)[0];this.presentationOrderPackets.push(t)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},$P=class{},eF=class extends $P{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);return t instanceof Promise&&(t=await t),!t||(t.skip(4),WF(t,4)!==`ftyp`)?null:WF(t,4)}_createDemuxer(e){return new DN(e)}},tF=class extends eF{async _canReadInput(e){let t=await this._getMajorBrand(e);return!!t&&t!==`qt `}get name(){return`MP4`}get mimeType(){return`video/mp4`}},nF=class extends eF{async _canReadInput(e){return await this._getMajorBrand(e)===`qt `}get name(){return`QuickTime File Format`}get mimeType(){return`video/quicktime`}},rF=class extends $P{async isSupportedEBMLOfDocType(e,t){let n=e._reader.requestSlice(0,16);if(n instanceof Promise&&(n=await n),!n)return!1;let r=VN(n);if(r===null||r<1||r>8||K(n,r)!==G.EBML)return!1;let i=GN(n);if(typeof i!=`number`)return!1;let a=e._reader.requestSlice(n.filePos,i);if(a instanceof Promise&&(a=await a),!a)return!1;let o=n.filePos;for(;a.filePos<=o+i-2;){let e=KN(a);if(!e)break;let{id:n,size:r}=e,i=a.filePos;if(r===void 0)return!1;switch(n){case G.EBMLVersion:if(K(a,r)!==1)return!1;break;case G.EBMLReadVersion:if(K(a,r)!==1)return!1;break;case G.DocType:if(qN(a,r)!==t)return!1;break;case G.DocTypeVersion:if(K(a,r)>4)return!1;break}a.filePos=i+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`matroska`)}_createDemuxer(e){return new oP(e)}get name(){return`Matroska`}get mimeType(){return`video/x-matroska`}},iF=class extends rF{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,`webm`)}get name(){return`WebM`}get mimeType(){return`video/webm`}},aF=class extends $P{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=XF(n);if(!r)break;t=n.filePos+r.size}let n=await uP(e._reader,t,t+4096);if(!n)return!1;let r=n.header,i=Ej(r.mpegVersionId,r.channel),a=e._reader.requestSlice(n.startPos+i,4);if(a instanceof Promise&&(a=await a),!a)return!1;let o=Y(a);if(o===1483304551||o===1231971951)return!0;t=n.startPos+n.header.totalSize;let s=await uP(e._reader,t,t+4);if(!s)return!1;let c=s.header;return!(r.channel!==c.channel||r.sampleRate!==c.sampleRate)}_createDemuxer(e){return new dP(e)}get name(){return`MP3`}get mimeType(){return`audio/mpeg`}},oF=class extends $P{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let n=WF(t,4);return n!==`RIFF`&&n!==`RIFX`&&n!==`RF64`?!1:(t.skip(4),WF(t,4)===`WAVE`)}_createDemuxer(e){return new EP(e)}get name(){return`WAVE`}get mimeType(){return`audio/wav`}},sF=class extends $P{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?WF(t,4)===`OggS`:!1}_createDemuxer(e){return new xP(e)}get name(){return`Ogg`}get mimeType(){return`application/ogg`}},cF=class extends $P{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?WF(t,4)===`fLaC`:!1}get name(){return`FLAC`}get mimeType(){return`audio/flac`}_createDemuxer(e){return new zP(e)}},lF=class extends $P{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,10);if(n instanceof Promise&&(n=await n),!n)break;let r=XF(n);if(!r)break;t=n.filePos+r.size}let n=e._reader.requestSliceRange(t,7,9);if(n instanceof Promise&&(n=await n),!n)return!1;let r=kP(n);if(!r||(t+=r.frameLength,n=e._reader.requestSliceRange(t,7,9),n instanceof Promise&&(n=await n),!n))return!1;let i=kP(n);return i?r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration:!1}_createDemuxer(e){return new jP(e)}get name(){return`ADTS`}get mimeType(){return`audio/aac`}},uF=class extends $P{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let n=q(t,205);return n[0]===71&&n[188]===71||n[0]===71&&n[204]===71?!0:n[4]===71&&n[196]===71}_createDemuxer(e){return new UP(e)}get name(){return`MPEG Transport Stream`}get mimeType(){return`video/MP2T`}},dF=new tF,fF=new nF,pF=new rF,mF=new iF,hF=new aF,gF=new oF,_F=new sF,vF=new lF,yF=[dF,fF,pF,mF,gF,_F,new cF,hF,vF,new uF];n(e(((e,t)=>{t.exports={}}))(),1);var bF=class{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new EF;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new EF;let e=await this.getSizeOrNull();if(e===null)throw Error(`Cannot determine the size of an unsized source.`);return e}},xF=class extends bF{constructor(e,t={}){if(!(e instanceof Blob))throw TypeError(`blob must be a Blob.`);if(!t||typeof t!=`object`)throw TypeError(`options must be an object.`);if(t.maxCacheSize!==void 0&&(!NA(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError(`options.maxCacheSize, when provided, must be a non-negative number.`);super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new wF({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:CF.fileSystem})}_retrieveSize(){let e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);for(t===void 0&&(t=(`stream`in this._blob)&&!xA()?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:n,value:r}=await t.read();if(n)throw this._orchestrator.forgetWorker(e),Error(`Blob reader stopped unexpectedly before all requested data was read.`);if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else{let t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1,e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}},SF=.5*2**20,CF={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{let n=2**16;return e=Math.floor((e-n)/n)*n,t=Math.ceil((t+n)/n)*n,{start:e,end:t}},network:(e,t,n)=>{let r=2**16;e=Math.max(0,Math.floor((e-r)/r)*r);for(let r of n){let n=8*2**20,i=Math.max((r.startPos+r.targetPos)/2,r.targetPos-n);if(kA(e,t,i,r.targetPos)){let e=r.targetPos-r.startPos,i=Math.ceil((e+1)/n)*n,a=2**Math.ceil(Math.log2(e+1)),o=Math.min(a,i);t=Math.max(t,r.startPos+o)}}return t=Math.max(t,e+SF),{start:e,end:t}}},wF=class{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,t){U(this.fileSize!==null);let n=this.options.prefetchProfile(e,t,this.workers),r=Math.max(n.start,0),i=Math.min(n.end,this.fileSize);U(r<=e&&t<=i);let a=null,o=Zk(this.cache,e,e=>e.start),s=o===-1?null:this.cache[o];s&&s.start<=e&&t<=s.end&&(s.age=this.nextAge++,a={bytes:s.bytes,view:s.view,offset:s.start});let c=Zk(this.cache,r,e=>e.start),l=a?null:new Uint8Array(t-e),u=0,d=r,f=[];if(c!==-1){for(let n=c;n<this.cache.length;n++){let a=this.cache[n];if(a.start>=i)break;if(a.end<=r)continue;let o=Math.max(r,a.start),s=Math.min(i,a.end);if(U(o<=s),d<o&&f.push({start:d,end:o}),d=s,l){let n=Math.max(e,a.start),r=Math.min(t,a.end);if(n<r){let t=n-e;l.set(a.bytes.subarray(n-a.start,r-a.start),t),t===u&&(u=r-e)}}a.age=this.nextAge++}d<i&&f.push({start:d,end:i})}else f.push({start:r,end:i});if(l&&u>=l.length&&(a={bytes:l,view:Fk(l),offset:e}),f.length===0)return U(a),a;let{promise:p,resolve:m,reject:h}=$k(),g=[];for(let n of f){let r=Math.max(e,n.start),i=Math.min(t,n.end);r===n.start&&i===n.end?g.push(n):r<i&&g.push({start:r,end:i})}for(let t of f){let n=l&&{start:e,bytes:l,holes:g,resolve:m,reject:h},r=!1;for(let e of this.workers)if(kA(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),r=!0,n&&!e.pendingSlices.includes(n)&&e.pendingSlices.push(n),e.running||this.runWorker(e);break}if(!r){let e=this.createWorker(t.start,t.end);n&&(e.pendingSlices=[n]),this.runWorker(e)}}return a||=(U(l),p.then(t=>({bytes:t,view:Fk(t),offset:e}))),a}createWorker(e,t){let n={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(n);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let n=1;n<this.workers.length;n++){let r=this.workers[n];r.age<t.age&&(e=n,t=r)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return n}runWorker(e){U(!e.running),U(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else throw t})}supplyWorkerData(e,t){U(!e.aborted);let n=e.currentPos,r=n+t.length;this.insertIntoCache({start:n,end:r,bytes:t,view:Fk(t),age:this.nextAge++}),e.currentPos+=t.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let i=0;i<e.pendingSlices.length;i++){let a=e.pendingSlices[i],o=Math.max(n,a.start),s=Math.min(r,a.start+a.bytes.length);o<s&&a.bytes.set(t.subarray(o-n,s-n),o-a.start);for(let e=0;e<a.holes.length;e++){let t=a.holes[e];n<=t.start&&r>t.start&&(t.start=r),t.end<=t.start&&(a.holes.splice(e,1),e--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;t<this.workers.length;t++){let i=this.workers[t];e===i||i.running||kA(n,r,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){let t=this.workers.indexOf(e);U(t!==-1),this.workers.splice(t,1)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=Zk(this.cache,e.start,e=>e.start)+1;if(t>0){let n=this.cache[t-1];if(n.end>=e.end)return;if(n.end>e.start){let r=new Uint8Array(e.end-n.start);r.set(n.bytes,0),r.set(e.bytes,e.start-n.start),this.currentCacheSize+=e.end-n.end,n.bytes=r,n.view=Fk(r),n.end=e.end,t--,e=n}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let n=t+1;n<this.cache.length;n++){let t=this.cache[n];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(n,1),this.currentCacheSize-=t.bytes.length,n--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=Fk(r),e.end=t.end,this.cache.splice(n,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let n=1;n<this.cache.length;n++){let r=this.cache[n];r.age<t.age&&(e=n,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}};MA();var TF=class{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof $P)))throw TypeError(`options.formats must be an array of InputFormat.`);if(!(e.source instanceof bF))throw TypeError(`options.source must be a Source.`);if(e.source._disposed)throw Error(`options.source must not be disposed.`);this._formats=e.formats,this._source=e.source,this._reader=new DF(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(let e of this._formats)if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this);throw Error(`Input has an unsupported or unrecognizable format.`)})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),U(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getFirstTimestamp(){let e=await this.getTracks();if(e.length===0)return 0;let t=await Promise.all(e.map(e=>e.getFirstTimestamp()));return Math.min(...t)}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter(e=>e.isVideoTrack())}async getAudioTracks(){return(await this.getTracks()).filter(e=>e.isAudioTrack())}async getPrimaryVideoTrack(){return(await this.getTracks()).find(e=>e.isVideoTrack())??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find(e=>e.isAudioTrack())??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}},EF=class extends Error{constructor(e=`Input has been disposed.`){super(e),this.name=`InputDisposedError`}},DF=class{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new EF;if(e<0||this.fileSize!==null&&e+t>this.fileSize)return null;let n=e+t,r=this.source._read(e,n);return r instanceof Promise?r.then(t=>t?new OF(t.bytes,t.view,t.offset,e,n):null):r?new OF(r.bytes,r.view,r.offset,e,n):null}requestSliceRange(e,t,n){if(this.source._disposed)throw new EF;if(e<0)return null;if(this.fileSize!==null)return this.requestSlice(e,uA(this.fileSize-e,t,n));{let r=this.requestSlice(e,n),i=r=>{if(r)return r;let i=r=>(U(r!==null),this.requestSlice(e,uA(r-e,t,n))),a=this.source._retrieveSize();return a instanceof Promise?a.then(i):i(a)};return r instanceof Promise?r.then(i):i(r)}}},OF=class e{constructor(e,t,n,r,i){this.bytes=e,this.view=t,this.offset=n,this.start=r,this.end=i,this.bufferPos=r-n}static tempFromBytes(t){return new e(t,Fk(t),0,0,t.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(t,n=this.end-t){if(t<this.start||t+n>this.end)throw RangeError(`Slicing outside of original slice.`);return new e(this.bytes,this.view,this.offset,t,t+n)}},kF=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},q=(e,t)=>{kF(e,t);let n=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,n},J=e=>(kF(e,1),e.view.getUint8(e.bufferPos++)),AF=(e,t)=>{kF(e,2);let n=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,n},jF=e=>{kF(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},MF=e=>{kF(e,3);let t=aA(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},NF=e=>{kF(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},PF=(e,t)=>{kF(e,4);let n=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,n},Y=e=>{kF(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},FF=e=>{kF(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},IF=e=>{kF(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},LF=e=>{kF(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},RF=(e,t)=>{let n,r;return t?(n=PF(e,!0),r=PF(e,!0)):(r=PF(e,!1),n=PF(e,!1)),r*4294967296+n},zF=e=>{let t=Y(e),n=Y(e);return t*4294967296+n},BF=e=>{let t=IF(e),n=Y(e);return t*4294967296+n},VF=e=>{let t=FF(e);return LF(e)*4294967296+t},HF=e=>{kF(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},UF=e=>{kF(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},WF=(e,t)=>{kF(e,t);let n=``;for(let r=0;r<t;r++)n+=String.fromCharCode(e.bytes[e.bufferPos++]);return n},GF;(function(e){e[e.Unsynchronisation=128]=`Unsynchronisation`,e[e.ExtendedHeader=64]=`ExtendedHeader`,e[e.ExperimentalIndicator=32]=`ExperimentalIndicator`,e[e.Footer=16]=`Footer`})(GF||={});var KF;(function(e){e[e.ISO_8859_1=0]=`ISO_8859_1`,e[e.UTF_16_WITH_BOM=1]=`UTF_16_WITH_BOM`,e[e.UTF_16_BE_NO_BOM=2]=`UTF_16_BE_NO_BOM`,e[e.UTF_8=3]=`UTF_8`})(KF||={});var qF=`Blues.Classic rock.Country.Dance.Disco.Funk.Grunge.Hip-hop.Jazz.Metal.New age.Oldies.Other.Pop.Rhythm and blues.Rap.Reggae.Rock.Techno.Industrial.Alternative.Ska.Death metal.Pranks.Soundtrack.Euro-techno.Ambient.Trip-hop.Vocal.Jazz & funk.Fusion.Trance.Classical.Instrumental.Acid.House.Game.Sound clip.Gospel.Noise.Alternative rock.Bass.Soul.Punk.Space.Meditative.Instrumental pop.Instrumental rock.Ethnic.Gothic.Darkwave.Techno-industrial.Electronic.Pop-folk.Eurodance.Dream.Southern rock.Comedy.Cult.Gangsta.Top 40.Christian rap.Pop/funk.Jungle music.Native US.Cabaret.New wave.Psychedelic.Rave.Showtunes.Trailer.Lo-fi.Tribal.Acid punk.Acid jazz.Polka.Retro.Musical.Rock 'n' roll.Hard rock.Folk.Folk rock.National folk.Swing.Fast fusion.Bebop.Latin.Revival.Celtic.Bluegrass.Avantgarde.Gothic rock.Progressive rock.Psychedelic rock.Symphonic rock.Slow rock.Big band.Chorus.Easy listening.Acoustic.Humour.Speech.Chanson.Opera.Chamber music.Sonata.Symphony.Booty bass.Primus.Porn groove.Satire.Slow jam.Club.Tango.Samba.Folklore.Ballad.Power ballad.Rhythmic Soul.Freestyle.Duet.Punk rock.Drum solo.A cappella.Euro-house.Dance hall.Goa music.Drum & bass.Club-house.Hardcore techno.Terror.Indie.Britpop.Negerpunk.Polsk punk.Beat.Christian gangsta rap.Heavy metal.Black metal.Crossover.Contemporary Christian.Christian rock.Merengue.Salsa.Thrash metal.Anime.Jpop.Synthpop.Christmas.Art rock.Baroque.Bhangra.Big beat.Breakbeat.Chillout.Downtempo.Dub.EBM.Eclectic.Electro.Electroclash.Emo.Experimental.Garage.Global.IDM.Illbient.Industro-Goth.Jam Band.Krautrock.Leftfield.Lounge.Math rock.New romantic.Nu-breakz.Post-punk.Post-rock.Psytrance.Shoegaze.Space rock.Trop rock.World music.Neoclassical.Audiobook.Audio theatre.Neue Deutsche Welle.Podcast.Indie rock.G-Funk.Dubstep.Garage rock.Psybient`.split(`.`),JF=(e,t)=>{let n=e.filePos;t.raw??={},t.raw.TAG??=q(e,125),e.filePos=n;let r=YF(e,30);r&&(t.title??=r);let i=YF(e,30);i&&(t.artist??=i);let a=YF(e,30);a&&(t.album??=a);let o=YF(e,4),s=Number.parseInt(o,10);Number.isInteger(s)&&s>0&&(t.date??=new Date(s,0,1));let c=q(e,30),l;if(c[28]===0&&c[29]!==0){let n=c[29];n>0&&(t.trackNumber??=n),e.skip(-30),l=YF(e,28),e.skip(2)}else e.skip(-30),l=YF(e,30);l&&(t.comment??=l);let u=J(e);u<qF.length&&(t.genre??=qF[u])},YF=(e,t)=>{let n=q(e,t),r=OA(n.indexOf(0),n.length),i=n.subarray(0,r),a=``;for(let e=0;e<i.length;e++)a+=String.fromCharCode(i[e]);return a.trimEnd()},XF=e=>{let t=e.filePos,n=WF(e,3),r=J(e),i=J(e),a=J(e),o=Y(e);return n!==`ID3`||r===255||i===255||o&2155905152?(e.filePos=t,null):{majorVersion:r,revision:i,flags:a,size:Oj(o)}},ZF=(e,t,n)=>{if(![2,3,4].includes(t.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);return}let r=new QF(t,q(e,t.size));if(t.flags&GF.Footer&&r.removeFooter(),t.flags&GF.Unsynchronisation&&t.majorVersion===3&&r.ununsynchronizeAll(),t.flags&GF.ExtendedHeader){let e=r.readU32();t.majorVersion===3?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){let e=r.readId3V2Frame();if(!e)break;let i=r.pos,a=r.pos+e.size,o=!1,s=!1,c=!1;if(t.majorVersion===3?(o=!!(e.flags&64),s=!!(e.flags&128)):t.majorVersion===4&&(o=!!(e.flags&4),s=!!(e.flags&8),c=!!(e.flags&2)||!!(t.flags&GF.Unsynchronisation)),o){console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=a;continue}if(s){console.warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=a;continue}switch(c&&r.ununsynchronizeRegion(r.pos,a),n.raw??={},e.id[0]===`T`?n.raw[e.id]??=r.readId3V2EncodingAndText(a):n.raw[e.id]??=r.readBytes(e.size),r.pos=i,e.id){case`TIT2`:case`TT2`:n.title??=r.readId3V2EncodingAndText(a);break;case`TIT3`:case`TT3`:n.description??=r.readId3V2EncodingAndText(a);break;case`TPE1`:case`TP1`:n.artist??=r.readId3V2EncodingAndText(a);break;case`TALB`:case`TAL`:n.album??=r.readId3V2EncodingAndText(a);break;case`TPE2`:case`TP2`:n.albumArtist??=r.readId3V2EncodingAndText(a);break;case`TRCK`:case`TRK`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.tracksTotal??=i)}break;case`TPOS`:case`TPA`:{let e=r.readId3V2EncodingAndText(a).split(`/`),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(n.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(n.discsTotal??=i)}break;case`TCON`:case`TCO`:{let e=r.readId3V2EncodingAndText(a),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(qF[e]!==void 0){n.genre??=qF[e];break}}if(t=/^\d+$/.exec(e),t){let e=Number.parseInt(t[0]);if(qF[e]!==void 0){n.genre??=qF[e];break}}n.genre??=e}break;case`TDRC`:case`TDAT`:{let e=r.readId3V2EncodingAndText(a),t=new Date(e);Number.isNaN(t.getTime())||(n.date??=t)}break;case`TYER`:case`TYE`:{let e=r.readId3V2EncodingAndText(a),t=Number.parseInt(e,10);Number.isInteger(t)&&(n.date??=new Date(t,0,1))}break;case`USLT`:case`ULT`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.lyrics??=r.readId3V2Text(e,a)}break;case`COMM`:case`COM`:{let e=r.readU8();r.pos+=3,r.readId3V2Text(e,a),n.comment??=r.readId3V2Text(e,a)}break;case`APIC`:case`PIC`:{let e=r.readId3V2TextEncoding(),i;if(t.majorVersion===2){let e=r.readAscii(3);i=e===`PNG`?`image/png`:e===`JPG`?`image/jpeg`:`image/*`}else i=r.readId3V2Text(e,a);let o=r.readU8(),s=r.readId3V2Text(e,a).trimEnd(),c=a-r.pos;if(c>=0){let e=r.readBytes(c);n.images||=[],n.images.push({data:e,mimeType:i,kind:o===3?`coverFront`:o===4?`coverBack`:`unknown`,description:s})}}break;default:r.pos+=e.size;break}r.pos=a}},QF=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let n=this.bytes[t];e.push(n),n===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let n=[];for(let r=e;r<t;r++){let e=this.bytes[r];n.push(e),e===255&&r!==t-1&&this.bytes[r+1]===0&&r++}let r=this.bytes.subarray(0,e),i=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+n.length+i.length),this.bytes.set(r,0),this.bytes.set(n,r.length),this.bytes.set(i,r.length+n.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,e*256+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t=``;for(let n=0;n<e;n++)t+=String.fromCharCode(this.view.getUint8(this.pos+n));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){let e=this.readAscii(3);return e===`\0\0\0`?null:{id:e,size:this.readU24(),flags:0}}else{let e=this.readAscii(4);if(e===`\0\0\0\0`)return null;let t=this.readU32(),n=this.header.majorVersion===4?Oj(t):t,r=this.readU16(),i=this.pos,a=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if(t!==`\0\0\0\0`&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!a(n)){let e=this.header.majorVersion===4?t:Oj(t);a(e)&&(n=e)}return this.pos=i,{id:e,size:n,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let n=this.pos,r=this.readBytes(t-this.pos);switch(e){case KF.ISO_8859_1:{let e=``;for(let t=0;t<r.length;t++){let i=r[t];if(i===0){this.pos=n+t+1;break}e+=String.fromCharCode(i)}return e}case KF.UTF_16_WITH_BOM:if(r[0]===255&&r[1]===254){let e=new TextDecoder(`utf-16le`),t=OA(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else if(r[0]===254&&r[1]===255){let e=new TextDecoder(`utf-16be`),t=OA(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}else{let e=OA(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Ik.decode(r.subarray(0,e))}case KF.UTF_16_BE_NO_BOM:{let e=new TextDecoder(`utf-16be`),t=OA(r.findIndex((e,t)=>e===0&&r[t+1]===0&&t%2==0),r.length);return this.pos=n+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case KF.UTF_8:{let e=OA(r.findIndex(e=>e===0),r.length);return this.pos=n+Math.min(e+1,r.length),Ik.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return``;let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},$F=class{constructor(e){this.mutex=new qk,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,n){if(t+=e.source._timestampOffset,t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(n&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),r.maxTimestampBeforeLastKeyPacket!==null&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!n)throw Error(`First packet must be a key packet.`);r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}return t}},eI=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,tI=e=>{let t=Math.floor(e/(3600*1e3)),n=Math.floor(e%(3600*1e3)/(60*1e3)),r=Math.floor(e%(60*1e3)/1e3),i=e%1e3;return t.toString().padStart(2,`0`)+`:`+n.toString().padStart(2,`0`)+`:`+r.toString().padStart(2,`0`)+`.`+i.toString().padStart(3,`0`)},nI=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let n=this.writer.getPos(),r=e.size??n-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(n)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+(e.largeSize?8:0)}patchBox(e){let t=this.offsets.get(e);U(t!==void 0);let n=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(n)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let n of e.children)n&&(t+=this.measureBox(n));return t}}},X=new Uint8Array(8),rI=new DataView(X.buffer),iI=e=>[(e%256+256)%256],Z=e=>(rI.setUint16(0,e,!1),[X[0],X[1]]),aI=e=>(rI.setInt16(0,e,!1),[X[0],X[1]]),oI=e=>(rI.setUint32(0,e,!1),[X[1],X[2],X[3]]),Q=e=>(rI.setUint32(0,e,!1),[X[0],X[1],X[2],X[3]]),sI=e=>(rI.setInt32(0,e,!1),[X[0],X[1],X[2],X[3]]),cI=e=>(rI.setUint32(0,Math.floor(e/2**32),!1),rI.setUint32(4,e,!1),[X[0],X[1],X[2],X[3],X[4],X[5],X[6],X[7]]),lI=e=>(rI.setInt16(0,2**8*e,!1),[X[0],X[1]]),uI=e=>(rI.setInt32(0,2**16*e,!1),[X[0],X[1],X[2],X[3]]),dI=e=>(rI.setInt32(0,2**30*e,!1),[X[0],X[1],X[2],X[3]]),fI=(e,t)=>{let n=[],r=e;do{let e=r&127;r>>=7,n.length>0&&(e|=128),n.push(e),t!==void 0&&t--}while(r>0||t);return n.reverse()},pI=(e,t=!1)=>{let n=Array(e.length).fill(null).map((t,n)=>e.charCodeAt(n));return t&&n.push(0),n},mI=e=>{let t=null;for(let n of e)(!t||n.timestamp>t.timestamp)&&(t=n);return t},hI=e=>{let t=e*(Math.PI/180),n=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[n,r,0,-r,n,0,0,0,1]},gI=hI(0),_I=e=>[uI(e[0]),uI(e[1]),dI(e[2]),uI(e[3]),uI(e[4]),dI(e[5]),uI(e[6]),uI(e[7]),dI(e[8])],$=(e,t,n)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:n}),vI=(e,t,n,r,i)=>$(e,[iI(t),oI(n),r??[]],i),yI=e=>e.isQuickTime?$(`ftyp`,[pI(`qt `),Q(512),pI(`qt `)]):e.fragmented?$(`ftyp`,[pI(`iso5`),Q(512),pI(`iso5`),pI(`iso6`),pI(`mp41`)]):$(`ftyp`,[pI(`isom`),Q(512),pI(`isom`),e.holdsAvc?pI(`avc1`):[],pI(`mp41`)]),bI=e=>({type:`mdat`,largeSize:e}),xI=e=>({type:`free`,size:e}),SI=e=>$(`moov`,void 0,[CI(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>wI(t,e.creationTime)),e.isFragmented?uL(e.trackDatas):null,TL(e)]),CI=(e,t)=>{let n=ZL(Math.max(0,...t.filter(e=>e.samples.length>0).map(e=>{let t=mI(e.samples);return t.timestamp+t.duration})),JL),r=Math.max(0,...t.map(e=>e.track.id))+1,i=!Mk(e)||!Mk(n),a=i?cI:Q;return vI(`mvhd`,+i,0,[a(e),a(e),Q(JL),a(n),uI(1),lI(1),Array(10).fill(0),_I(gI),Array(24).fill(0),Q(r)])},wI=(e,t)=>{let n=XL(e);return $(`trak`,void 0,[TI(e,t),EI(e,t),n.name===void 0?null:$(`udta`,void 0,[$(`name`,[...Lk.encode(n.name)])])])},TI=(e,t)=>{let n=mI(e.samples),r=ZL(n?n.timestamp+n.duration:0,JL),i=!Mk(t)||!Mk(r),a=i?cI:Q,o;if(e.type===`video`){let t=e.track.metadata.rotation;o=hI(t??0)}else o=gI;let s=2;return e.track.metadata.disposition?.default!==!1&&(s|=1),vI(`tkhd`,+i,s,[a(t),a(t),Q(e.track.id),Q(0),a(r),Array(8).fill(0),Z(0),Z(e.track.id),lI(e.type===`audio`?1:0),Z(0),_I(o),uI(e.type===`video`?e.info.width:0),uI(e.type===`video`?e.info.height:0)])},EI=(e,t)=>$(`mdia`,void 0,[DI(e,t),AI(!0,OI[e.type],kI[e.type]),jI(e)]),DI=(e,t)=>{let n=mI(e.samples),r=ZL(n?n.timestamp+n.duration:0,e.timescale),i=!Mk(t)||!Mk(r),a=i?cI:Q;return vI(`mdhd`,+i,0,[a(t),a(t),Q(e.timescale),a(r),Z(zL(e.track.metadata.languageCode??`und`)),Z(0)])},OI={video:`vide`,audio:`soun`,subtitle:`text`},kI={video:`MediabunnyVideoHandler`,audio:`MediabunnySoundHandler`,subtitle:`MediabunnyTextHandler`},AI=(e,t,n,r=`\0\0\0\0`)=>vI(`hdlr`,0,0,[e?pI(`mhlr`):Q(0),pI(t),pI(r),Q(0),Q(0),pI(n,!0)]),jI=e=>$(`minf`,void 0,[MI[e.type](),NI(),II(e)]),MI={video:()=>vI(`vmhd`,0,1,[Z(0),Z(0),Z(0),Z(0)]),audio:()=>vI(`smhd`,0,0,[Z(0),Z(0)]),subtitle:()=>vI(`nmhd`,0,0)},NI=()=>$(`dinf`,void 0,[PI()]),PI=()=>vI(`dref`,0,0,[Q(1)],[FI()]),FI=()=>vI(`url `,0,1),II=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>e.sampleCompositionTimeOffset!==0);return $(`stbl`,void 0,[LI(e),rL(e),t?cL(e):null,t?lL(e):null,aL(e),oL(e),sL(e),iL(e)])},LI=e=>{let t;if(e.type===`video`)t=RI(NL(e.track.source._codec,e.info.decoderConfig.codec),e);else if(e.type===`audio`){let n=FL(e.track.source._codec,e.muxer.isQuickTime);U(n),t=GI(n,e)}else e.type===`subtitle`&&(t=tL(LL[e.track.source._codec],e));return U(t),vI(`stsd`,0,0,[Q(1)],[t])},RI=(e,t)=>$(e,[[,,,,,,].fill(0),Z(1),Z(0),Z(0),Array(12).fill(0),Z(t.info.width),Z(t.info.height),Q(4718592),Q(4718592),Q(0),Z(1),Array(32).fill(0),Z(24),aI(65535)],[PL[t.track.source._codec](t),zI(t),Gk(t.info.decoderConfig.colorSpace)?BI(t):null]),zI=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:$(`pasp`,[Q(e.info.pixelAspectRatio.num),Q(e.info.pixelAspectRatio.den)]),BI=e=>$(`colr`,[pI(`nclx`),Z(zk[e.info.decoderConfig.colorSpace.primaries]),Z(Vk[e.info.decoderConfig.colorSpace.transfer]),Z(Uk[e.info.decoderConfig.colorSpace.matrix]),iI((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),VI=e=>e.info.decoderConfig&&$(`avcC`,[...Pk(e.info.decoderConfig.description)]),HI=e=>e.info.decoderConfig&&$(`hvcC`,[...Pk(e.info.decoderConfig.description)]),UI=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,n=t.codec.split(`.`),r=Number(n[1]),i=Number(n[2]),a=Number(n[3]),o=n[4]?Number(n[4]):1,s=n[8]?Number(n[8]):Number(t.colorSpace?.fullRange??0),c=(a<<4)+(o<<1)+s,l=n[5]?Number(n[5]):t.colorSpace?.primaries?zk[t.colorSpace.primaries]:2,u=n[6]?Number(n[6]):t.colorSpace?.transfer?Vk[t.colorSpace.transfer]:2,d=n[7]?Number(n[7]):t.colorSpace?.matrix?Uk[t.colorSpace.matrix]:2;return vI(`vpcC`,1,0,[iI(r),iI(i),iI(c),iI(l),iI(u),iI(d),Z(0)])},WI=e=>$(`av1C`,ij(e.info.decoderConfig.codec)),GI=(e,t)=>{let n=0,r,i=16,a=qA.includes(t.track.source._codec);if(a){let e=t.track.source._codec,{sampleSize:r}=uj(e);i=8*r,i>16&&(n=1)}if(t.muxer.isQuickTime&&(n=1),n===0)r=[[,,,,,,].fill(0),Z(1),Z(n),Z(0),Q(0),Z(t.info.numberOfChannels),Z(i),Z(0),Z(0),Z(t.info.sampleRate<2**16?t.info.sampleRate:0),Z(0)];else{let e=a?0:-2;r=[[,,,,,,].fill(0),Z(1),Z(n),Z(0),Q(0),Z(t.info.numberOfChannels),Z(Math.min(i,16)),aI(e),Z(0),Z(t.info.sampleRate<2**16?t.info.sampleRate:0),Z(0),a?[Q(1),Q(i/8),Q(t.info.numberOfChannels*i/8)]:[Q(0),Q(0),Q(0)],Q(2)]}return $(e,r,[IL(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},KI=e=>{let t;switch(e.track.source._codec){case`aac`:t=64;break;case`mp3`:t=107;break;case`vorbis`:t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let n=[...iI(t),...iI(21),...oI(0),...Q(0),...Q(0)];if(e.info.decoderConfig.description){let t=Pk(e.info.decoderConfig.description);n=[...n,...iI(5),...fI(t.byteLength),...t]}return n=[...Z(1),...iI(0),...iI(4),...fI(n.length),...n,...iI(6),...iI(1),...iI(2)],n=[...iI(3),...fI(n.length),...n],vI(`esds`,0,0,n)},qI=e=>$(`wave`,void 0,[JI(e),YI(e),$(`\0\0\0\0`)]),JI=e=>$(`frma`,[pI(FL(e.track.source._codec,e.muxer.isQuickTime))]),YI=e=>{let{littleEndian:t}=uj(e.track.source._codec);return $(`enda`,[Z(+t)])},XI=e=>{let t=e.info.numberOfChannels,n=3840,r=e.info.sampleRate,i=0,a=0,o=new Uint8Array,s=e.info.decoderConfig?.description;if(s){U(s.byteLength>=18);let e=lM(Pk(s));t=e.outputChannelCount,n=e.preSkip,r=e.inputSampleRate,i=e.outputGain,a=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return $(`dOps`,[iI(0),iI(t),Z(n),Q(r),aI(i),iI(a),...o])},ZI=e=>{let t=e.info.decoderConfig?.description;return U(t),vI(`dfLa`,0,0,[...Pk(t).subarray(4)])},QI=e=>{let{littleEndian:t,sampleSize:n}=uj(e.track.source._codec);return vI(`pcmC`,0,0,[iI(+t),iI(8*n)])},$I=e=>{let t=_M(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=new Uint8Array(3),r=new VA(n);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),$(`dac3`,[...n])},eL=e=>{let t=xM(e.info.firstPacket.data);if(!t)throw Error(`Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).`);let n=16;for(let e of t.substreams)n+=23,e.numDepSub>0?n+=9:n+=1;let r=Math.ceil(n/8),i=new Uint8Array(r),a=new VA(i);a.writeBits(13,t.dataRate),a.writeBits(3,t.substreams.length-1);for(let e of t.substreams)a.writeBits(2,e.fscod),a.writeBits(5,e.bsid),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(3,e.bsmod),a.writeBits(3,e.acmod),a.writeBits(1,e.lfeon),a.writeBits(3,0),a.writeBits(4,e.numDepSub),e.numDepSub>0?a.writeBits(9,e.chanLoc):a.writeBits(1,0);return $(`dec3`,[...i])},tL=(e,t)=>$(e,[[,,,,,,].fill(0),Z(1)],[RL[t.track.source._codec](t)]),nL=e=>$(`vttC`,[...Lk.encode(e.info.config.description)]),rL=e=>vI(`stts`,0,0,[Q(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Q(e.sampleCount),Q(e.sampleDelta)])]),iL=e=>{if(e.samples.every(e=>e.type===`key`))return null;let t=[...e.samples.entries()].filter(([,e])=>e.type===`key`);return vI(`stss`,0,0,[Q(t.length),t.map(([e])=>Q(e+1))])},aL=e=>vI(`stsc`,0,0,[Q(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Q(e.firstChunk),Q(e.samplesPerChunk),Q(1)])]),oL=e=>{if(e.type===`audio`&&e.info.requiresPcmTransformation){let{sampleSize:t}=uj(e.track.source._codec);return vI(`stsz`,0,0,[Q(t*e.info.numberOfChannels),Q(e.samples.reduce((t,n)=>t+ZL(n.duration,e.timescale),0))])}return vI(`stsz`,0,0,[Q(0),Q(e.samples.length),e.samples.map(e=>Q(e.size))])},sL=e=>e.finalizedChunks.length>0&&jk(e.finalizedChunks).offset>=2**32?vI(`co64`,0,0,[Q(e.finalizedChunks.length),e.finalizedChunks.map(e=>cI(e.offset))]):vI(`stco`,0,0,[Q(e.finalizedChunks.length),e.finalizedChunks.map(e=>Q(e.offset))]),cL=e=>vI(`ctts`,1,0,[Q(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Q(e.sampleCount),sI(e.sampleCompositionTimeOffset)])]),lL=e=>{let t=1/0,n=-1/0,r=1/0,i=-1/0;U(e.compositionTimeOffsetTable.length>0),U(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let i=e.compositionTimeOffsetTable[r];t=Math.min(t,i.sampleCompositionTimeOffset),n=Math.max(n,i.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let n=e.samples[t];r=Math.min(r,ZL(n.timestamp,e.timescale)),i=Math.max(i,ZL(n.timestamp+n.duration,e.timescale))}let a=Math.max(-t,0);return i>=2**31?null:vI(`cslg`,0,0,[sI(a),sI(t),sI(n),sI(r),sI(i)])},uL=e=>$(`mvex`,void 0,e.map(dL)),dL=e=>vI(`trex`,0,0,[Q(e.track.id),Q(1),Q(0),Q(0),Q(0)]),fL=(e,t)=>$(`moof`,void 0,[pL(e),...t.map(hL)]),pL=e=>vI(`mfhd`,0,0,[Q(e)]),mL=e=>{let t=0,n=0,r=e.type===`delta`;return n|=+r,r?t|=1:t|=2,t<<24|n<<16|0},hL=e=>$(`traf`,void 0,[gL(e),_L(e),vL(e)]),gL=e=>{U(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;let n=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:n.timescaleUnitsToNextSample,size:n.size,flags:mL(n)};return vI(`tfhd`,0,t,[Q(e.track.id),Q(r.duration),Q(r.size),Q(r.flags)])},_L=e=>(U(e.currentChunk),vI(`tfdt`,1,0,[cI(ZL(e.currentChunk.startTimestamp,e.timescale))])),vL=e=>{U(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),n=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(mL),i=e.currentChunk.samples.map(t=>ZL(t.timestamp-t.decodeTimestamp,e.timescale)),a=new Set(t),o=new Set(n),s=new Set(r),c=new Set(i),l=s.size===2&&r[0]!==r[1],u=a.size>1,d=o.size>1,f=!l&&s.size>1,p=c.size>1||[...c].some(e=>e!==0),m=0;return m|=1,m|=4*l,m|=256*u,m|=512*d,m|=1024*f,m|=2048*p,vI(`trun`,1,m,[Q(e.currentChunk.samples.length),Q(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?Q(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?Q(t[a]):[],d?Q(n[a]):[],f?Q(r[a]):[],p?sI(i[a]):[]])])},yL=e=>$(`mfra`,void 0,[...e.map(bL),xL()]),bL=(e,t)=>vI(`tfra`,1,0,[Q(e.track.id),Q(63),Q(e.finalizedChunks.length),e.finalizedChunks.map(n=>[cI(ZL(n.samples[0].timestamp,e.timescale)),cI(n.moofOffset),Q(t+1),Q(1),Q(1)])]),xL=()=>vI(`mfro`,0,0,[Q(0)]),SL=()=>$(`vtte`),CL=(e,t,n,r,i)=>$(`vttc`,void 0,[i===null?null:$(`vsid`,[sI(i)]),n===null?null:$(`iden`,[...Lk.encode(n)]),t===null?null:$(`ctim`,[...Lk.encode(tI(t))]),r===null?null:$(`sttg`,[...Lk.encode(r)]),$(`payl`,[...Lk.encode(e)])]),wL=e=>$(`vtta`,[...Lk.encode(e)]),TL=e=>{let t=[],n=e.format._options.metadataFormat??`auto`,r=e.output._metadataTags;if(n===`mdir`||n===`auto`&&!e.isQuickTime){let e=AL(r);e&&t.push(e)}else if(n===`mdta`){let e=jL(r);e&&t.push(e)}else (n===`udta`||n===`auto`&&e.isQuickTime)&&EL(t,e.output._metadataTags);return t.length===0?null:$(`udta`,void 0,t)},EL=(e,t)=>{for(let{key:n,value:r}of AA(t))switch(n){case`title`:e.push(DL(`©nam`,r));break;case`description`:e.push(DL(`©des`,r));break;case`artist`:e.push(DL(`©ART`,r));break;case`album`:e.push(DL(`©alb`,r));break;case`albumArtist`:e.push(DL(`albr`,r));break;case`genre`:e.push(DL(`©gen`,r));break;case`date`:e.push(DL(`©day`,r.toISOString().slice(0,10)));break;case`comment`:e.push(DL(`©cmt`,r));break;case`lyrics`:e.push(DL(`©lyr`,r));break;case`raw`:break;case`discNumber`:case`discsTotal`:case`trackNumber`:case`tracksTotal`:case`images`:break;default:iA(n)}if(t.raw)for(let n in t.raw){let r=t.raw[n];r==null||n.length!==4||e.some(e=>e.type===n)||(typeof r==`string`?e.push(DL(n,r)):r instanceof Uint8Array&&e.push($(n,Array.from(r))))}},DL=(e,t)=>{let n=Lk.encode(t);return $(e,[Z(n.length),Z(zL(`und`)),Array.from(n)])},OL={"image/jpeg":13,"image/png":14,"image/bmp":27},kL=(e,t)=>{let n=[];for(let{key:r,value:i}of AA(e))switch(r){case`title`:n.push({key:t?`title`:`©nam`,value:ML(i)});break;case`description`:n.push({key:t?`description`:`©des`,value:ML(i)});break;case`artist`:n.push({key:t?`artist`:`©ART`,value:ML(i)});break;case`album`:n.push({key:t?`album`:`©alb`,value:ML(i)});break;case`albumArtist`:n.push({key:t?`album_artist`:`aART`,value:ML(i)});break;case`comment`:n.push({key:t?`comment`:`©cmt`,value:ML(i)});break;case`genre`:n.push({key:t?`genre`:`©gen`,value:ML(i)});break;case`lyrics`:n.push({key:t?`lyrics`:`©lyr`,value:ML(i)});break;case`date`:n.push({key:t?`date`:`©day`,value:ML(i.toISOString().slice(0,10))});break;case`images`:for(let e of i)e.kind===`coverFront`&&n.push({key:`covr`,value:$(`data`,[Q(OL[e.mimeType]??0),Q(0),Array.from(e.data)])});break;case`trackNumber`:if(t){let t=e.tracksTotal===void 0?i.toString():`${i}/${e.tracksTotal}`;n.push({key:`track`,value:ML(t)})}else n.push({key:`trkn`,value:$(`data`,[Q(0),Q(0),Z(0),Z(i),Z(e.tracksTotal??0),Z(0)])});break;case`discNumber`:t||n.push({key:`disc`,value:$(`data`,[Q(0),Q(0),Z(0),Z(i),Z(e.discsTotal??0),Z(0)])});break;case`tracksTotal`:case`discsTotal`:break;case`raw`:break;default:iA(r)}if(e.raw)for(let r in e.raw){let i=e.raw[r];i==null||!t&&r.length!==4||n.some(e=>e.key===r)||(typeof i==`string`?n.push({key:r,value:ML(i)}):i instanceof Uint8Array?n.push({key:r,value:$(`data`,[Q(0),Q(0),Array.from(i)])}):i instanceof IA&&n.push({key:r,value:$(`data`,[Q(OL[i.mimeType]??0),Q(0),Array.from(i.data)])}))}return n},AL=e=>{let t=kL(e,!1);return t.length===0?null:vI(`meta`,0,0,void 0,[AI(!1,`mdir`,``,`appl`),$(`ilst`,void 0,t.map(e=>$(e.key,void 0,[e.value])))])},jL=e=>{let t=kL(e,!0);return t.length===0?null:$(`meta`,void 0,[AI(!1,`mdta`,``),vI(`keys`,0,0,[Q(t.length)],t.map(e=>$(`mdta`,[...Lk.encode(e.key)]))),$(`ilst`,void 0,t.map((e,t)=>$(String.fromCharCode(...Q(t+1)),void 0,[e.value])))])},ML=e=>$(`data`,[Q(1),Q(0),...Lk.encode(e)]),NL=(e,t)=>{switch(e){case`avc`:return t.startsWith(`avc3`)?`avc3`:`avc1`;case`hevc`:return`hvc1`;case`vp8`:return`vp08`;case`vp9`:return`vp09`;case`av1`:return`av01`}},PL={avc:VI,hevc:HI,vp8:UI,vp9:UI,av1:WI},FL=(e,t)=>{switch(e){case`aac`:return`mp4a`;case`mp3`:return`mp4a`;case`opus`:return`Opus`;case`vorbis`:return`mp4a`;case`flac`:return`fLaC`;case`ulaw`:return`ulaw`;case`alaw`:return`alaw`;case`pcm-u8`:return`raw `;case`pcm-s8`:return`sowt`;case`ac3`:return`ac-3`;case`eac3`:return`ec-3`}if(t)switch(e){case`pcm-s16`:return`sowt`;case`pcm-s16be`:return`twos`;case`pcm-s24`:return`in24`;case`pcm-s24be`:return`in24`;case`pcm-s32`:return`in32`;case`pcm-s32be`:return`in32`;case`pcm-f32`:return`fl32`;case`pcm-f32be`:return`fl32`;case`pcm-f64`:return`fl64`;case`pcm-f64be`:return`fl64`}else switch(e){case`pcm-s16`:return`ipcm`;case`pcm-s16be`:return`ipcm`;case`pcm-s24`:return`ipcm`;case`pcm-s24be`:return`ipcm`;case`pcm-s32`:return`ipcm`;case`pcm-s32be`:return`ipcm`;case`pcm-f32`:return`fpcm`;case`pcm-f32be`:return`fpcm`;case`pcm-f64`:return`fpcm`;case`pcm-f64be`:return`fpcm`}},IL=(e,t)=>{switch(e){case`aac`:return KI;case`mp3`:return KI;case`opus`:return XI;case`vorbis`:return KI;case`flac`:return ZI;case`ac3`:return $I;case`eac3`:return eL}if(t)switch(e){case`pcm-s24`:return qI;case`pcm-s24be`:return qI;case`pcm-s32`:return qI;case`pcm-s32be`:return qI;case`pcm-f32`:return qI;case`pcm-f32be`:return qI;case`pcm-f64`:return qI;case`pcm-f64be`:return qI}else switch(e){case`pcm-s16`:return QI;case`pcm-s16be`:return QI;case`pcm-s24`:return QI;case`pcm-s24be`:return QI;case`pcm-s32`:return QI;case`pcm-s32be`:return QI;case`pcm-f32`:return QI;case`pcm-f32be`:return QI;case`pcm-f64`:return QI;case`pcm-f64be`:return QI}return null},LL={webvtt:`wvtt`},RL={webvtt:nL},zL=e=>{U(e.length===3);let t=0;for(let n=0;n<3;n++)t<<=5,t+=e.charCodeAt(n)-96;return t},BL=class{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let n=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<n;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error(`Internal error: Can't get tracked writes since nothing was tracked.`);let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},VL=2**16,HL=2**32,UL=class extends BL{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize=`resize`in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(VL,{maxByteLength:HL})}catch{this.buffer=new ArrayBuffer(VL),this.supportsResize=!1}else this.buffer=new ArrayBuffer(VL);this.bytes=new Uint8Array(this.buffer)}ensureSize(e){let t=this.buffer.byteLength;for(;t<e;)t*=2;if(t!==this.buffer.byteLength){if(t>HL)throw Error(`ArrayBuffer exceeded maximum size of ${HL} bytes. Please consider using another target.`);if(this.supportsResize)this.buffer.resize(t);else{let e=new ArrayBuffer(t),n=new Uint8Array(e);n.set(this.bytes,0),this.buffer=e,this.bytes=n}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}},WL=class extends BL{constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}},GL=class{constructor(){this._output=null,this.onwrite=null}},KL=class extends GL{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new UL(this)}},qL=class extends GL{_createWriter(){return new WL(this)}},JL=1e3,YL=2082844800,XL=e=>{let t={},n=e.track;return n.metadata.name!==void 0&&(t.name=n.metadata.name),t},ZL=(e,t,n=!0)=>{let r=e*t;return n?Math.round(r):r},QL=class extends $F{constructor(e,t){super(e),this.auxTarget=new KL,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new nI(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=$k(),this.creationTime=Math.floor(Date.now()/1e3)+YL,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new nI(this.writer),this.isQuickTime=t instanceof nR;let n=this.writer instanceof UL?`in-memory`:!1;this.fastStart=t._options.fastStart??n,this.isFragmented=this.fastStart===`fragmented`,(this.fastStart===`in-memory`||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){let e=await this.mutex.acquire(),t=this.output._tracks.some(e=>e.type===`video`&&e.source._codec===`avc`);if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(yI({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented})),this.format._options.onFtyp){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}if(this.ftypSize=this.writer.getPos(),this.fastStart!==`in-memory`)if(this.fastStart===`reserve`){for(let e of this.output._tracks)if(e.metadata.maximumPacketCount===void 0)throw Error(`All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.`)}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=bI(!0),this.boxWriter.writeBox(this.mdat));await this.writer.flush(),e()}allTracksAreKnown(){for(let e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;let e=this.trackDatas.map(e=>e.type===`video`||e.type===`audio`?e.info.decoderConfig.codec:{webvtt:`wvtt`}[e.track.source._codec]);return bN({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>e.type===`video`),hasAudio:this.trackDatas.some(e=>e.type===`audio`),codecStrings:e})}getVideoTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;yj(n),U(n),U(n.decoderConfig);let i={...n.decoderConfig};U(i.codedWidth!==void 0),U(i.codedHeight!==void 0);let a=!1;if(e.source._codec===`avc`&&!i.description){let e=Hj(t.data);if(!e)throw Error(`Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.`);i.description=Uj(e),a=!0}else if(e.source._codec===`hevc`&&!i.description){let e=Zj(t.data);if(!e)throw Error(`Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.`);i.description=aM(e),a=!0}let o=vA(1/(e.metadata.frameRate??57600),1e6).denominator,s=i.displayAspectWidth,c=i.displayAspectHeight,l=s===void 0||c===void 0?{num:1,den:1}:PA({num:s*i.codedHeight,den:c*i.codedWidth}),u={muxer:this,track:e,type:`video`,info:{width:i.codedWidth,height:i.codedHeight,pixelAspectRatio:l,decoderConfig:i,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(u),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,t,n){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;xj(n),U(n),U(n.decoderConfig);let i={...n.decoderConfig},a=!1;if(e.source._codec===`aac`&&!i.description){let e=kP(OF.tempFromBytes(t.data));if(!e)throw Error(`Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.`);let n=HA[e.samplingFrequencyIndex],r=UA[e.channelConfiguration];if(n===void 0||r===void 0)throw Error(`Invalid ADTS frame header.`);i.description=GA({objectType:e.objectType,sampleRate:n,numberOfChannels:r}),a=!0}let o={muxer:this,track:e,type:`audio`,info:{numberOfChannels:n.decoderConfig.numberOfChannels,sampleRate:n.decoderConfig.sampleRate,decoderConfig:i,requiresPcmTransformation:!this.isFragmented&&qA.includes(e.source._codec),requiresAdtsStripping:a,firstPacket:t},timescale:i.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let n=this.trackDatas.find(t=>t.track===e);if(n)return n;Sj(t),U(t),U(t.config);let r={muxer:this,track:e,type:`subtitle`,info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,n),i=t.data;if(r.info.requiresAnnexBTransformation){let e=[...Nj(i)].map(e=>i.subarray(e.offset,e.offset+e.length));if(e.length===0)throw Error(`Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.`);i=Bj(e,4)}let a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type===`key`),o=this.createSampleForTrack(r,i,a,t.duration,t.type);await this.registerSample(r,o)}finally{r()}}async addEncodedAudioPacket(e,t,n){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,n),i=t.data;if(r.info.requiresAdtsStripping){let e=kP(OF.tempFromBytes(i));if(!e)throw Error(`Expected ADTS frame, didn't get one.`);let t=e.crcCheck===null?7:9;i=i.subarray(t)}let a=this.validateAndNormalizeTimestamp(r.track,t.timestamp,t.type===`key`),o=this.createSampleForTrack(r,i,a,t.duration,t.type);r.info.requiresPcmTransformation&&await this.maybePadWithSilence(r,a),await this.registerSample(r,o)}finally{r()}}async maybePadWithSilence(e,t){let n=jk(e.samples),r=n?n.timestamp+n.duration:0,i=t-r,a=ZL(i,e.timescale);if(a>0){let{sampleSize:t,silentValue:n}=uj(e.info.decoderConfig.codec),o=a*e.info.numberOfChannels,s=new Uint8Array(t*o).fill(n),c=this.createSampleForTrack(e,new Uint8Array(s.buffer),r,i,`key`);await this.registerSample(e,c)}}async addSubtitleCue(e,t,n){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,n);this.validateAndNormalizeTimestamp(r.track,t.timestamp,!0),e.source._codec===`webvtt`&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let n=new Set([]);for(let r of e.cueQueue)U(r.timestamp<=t),U(e.lastCueEndTimestamp<=r.timestamp+r.duration),n.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),n.add(r.timestamp+r.duration);let r=[...n].sort((e,t)=>e-t),i=r[0],a=r[1]??i;if(t<a)break;if(e.lastCueEndTimestamp<i){this.auxWriter.seek(0);let t=SL();this.auxBoxWriter.writeBox(t);let n=this.auxWriter.getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,n,e.lastCueEndTimestamp,i-e.lastCueEndTimestamp,`key`);await this.registerSample(e,r),e.lastCueEndTimestamp=i}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let n=e.cueQueue[t];if(n.timestamp>=a)break;eI.lastIndex=0;let r=eI.test(n.text),o=n.timestamp+n.duration,s=e.cueToSourceId.get(n);if(s===void 0&&a<o&&(s=e.nextSourceId++,e.cueToSourceId.set(n,s)),n.notes){let e=wL(n.notes);this.auxBoxWriter.writeBox(e)}let c=CL(n.text,r?i:null,n.identifier??null,n.settings??null,s??null);this.auxBoxWriter.writeBox(c),o===a&&e.cueQueue.splice(t--,1)}let o=this.auxWriter.getSlice(0,this.auxWriter.getPos()),s=this.createSampleForTrack(e,o,i,a-i,`key`);await this.registerSample(e,s),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,n,r,i){return{timestamp:n,decodeTimestamp:n,duration:r,data:t,size:t.byteLength,type:i,timescaleUnitsToNextSample:ZL(r,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type===`audio`&&e.info.requiresPcmTransformation){let t=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){let r=e.timestampProcessingQueue[n],i=ZL(r.duration,e.timescale);t+=i}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let n=jk(e.timeToSampleTable);n.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let n=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=n[t],!this.isFragmented&&e.lastTimescaleUnits===null&&(r.decodeTimestamp=0);let i=ZL(r.timestamp-r.decodeTimestamp,e.timescale),a=ZL(r.duration,e.timescale);if(e.lastTimescaleUnits!==null){U(e.lastSample);let t=ZL(r.decodeTimestamp,e.timescale,!1),n=Math.round(t-e.lastTimescaleUnits);if(U(n>=0),e.lastTimescaleUnits+=n,e.lastSample.timescaleUnitsToNextSample=n,!this.isFragmented){let t=jk(e.timeToSampleTable);if(U(t),t.sampleCount===1){t.sampleDelta=n;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];r&&r.sampleDelta===n&&(r.sampleCount++,e.timeToSampleTable.pop(),t=r)}else t.sampleDelta!==n&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:n}));t.sampleDelta===a?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:a});let r=jk(e.compositionTimeOffsetTable);U(r),r.sampleCompositionTimeOffset===i?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i})}}else e.lastTimescaleUnits=ZL(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:a}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:i}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,U(e.lastSample),U(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){U(t.type===`key`);let n=ZL(t.timestamp,e.timescale,!1),r=Math.round(n-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){t.type===`key`&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart===`reserve`?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart===`reserve`)){let t=e.track.metadata.maximumPacketCount;if(U(t!==void 0),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let n=!1;if(!e.currentChunk)n=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let i=this.trackDatas.every(n=>{if(e===n)return t.type===`key`;let r=n.sampleQueue[0];return r?r.type===`key`:n.track.source._closed});r>=this.minimumFragmentDuration&&i&&t.timestamp>this.maxWrittenTimestamp&&(n=!0,await this.finalizeFragment())}else n=r>=.5}n&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),U(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(U(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type===`audio`&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,n)=>t+ZL(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||jk(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart===`in-memory`){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(let t of e.currentChunk.samples)U(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(U(this.isFragmented),!(!e&&!this.allTracksAreKnown()))outer:for(;;){let t=null,n=1/0;for(let r of this.trackDatas){if(!e&&r.sampleQueue.length===0&&!r.track.source._closed)break outer;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<n&&(t=r,n=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!0){U(this.isFragmented);let t=this.nextFragmentNumber++;if(t===1){this.format._options.onMoov&&this.writer.startTrackingWrites();let e=SI(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}let n=this.trackDatas.filter(e=>e.currentChunk),r=fL(t,n),i=this.writer.getPos(),a=i+this.boxWriter.measureBox(r),o=a+8,s=1/0;for(let e of n){e.currentChunk.offset=o,e.currentChunk.moofOffset=i;for(let t of e.currentChunk.samples)o+=t.size;s=Math.min(s,e.currentChunk.startTimestamp)}let c=o-a,l=c>=2**32;if(l)for(let e of n)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();let u=fL(t,n);if(this.boxWriter.writeBox(u),this.format._options.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,s)}U(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();let d=bI(l);d.size=c,this.boxWriter.writeBox(d),this.writer.seek(a+(l?16:8));for(let e of n)for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(let e of n)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(this.allTracksAreKnown()){if(!this.mdat){let e=SI(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;U(this.ftypSize!==null),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=bI(!0),this.boxWriter.writeBox(this.mdat);for(let e of this.trackDatas){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){U(this.fastStart===`reserve`);let e=0;for(let t of this.trackDatas){let n=t.track.metadata.maximumPacketCount;U(n!==void 0),e+=8*Math.ceil(2/3*n),e+=4*n,e+=8*Math.ceil(2/3*n),e+=12*Math.ceil(2/3*n),e+=4*n,e+=8*n}return e}async onTrackClose(e){let t=await this.mutex.acquire(),n=this.trackDatas.find(t=>t.track===e);n&&(n.type===`subtitle`&&e.source._codec===`webvtt`&&await this.processWebVTTCues(n,1/0),this.processTimestamps(n)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){let e=await this.mutex.acquire();this.allTracksKnown.resolve();for(let e of this.trackDatas)e.type===`subtitle`&&e.track.source._codec===`webvtt`&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)await this.finalizeCurrentChunk(e);if(this.fastStart===`in-memory`){this.mdat=bI(!1);let e;for(let t=0;t<2;t++){let t=SI(this),n=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+n+e;for(let t of this.finalizedChunks){t.offset=r;for(let{data:n}of t.samples)U(n),r+=n.byteLength,e+=n.byteLength}if(r<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();let t=SI(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(let e of this.finalizedChunks)for(let t of e.samples)U(t.data),this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented){let e=this.writer.getPos(),t=yL(this.trackDatas);this.boxWriter.writeBox(t);let n=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{U(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);U(e!==void 0);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}let n=SI(this);if(this.fastStart===`reserve`){U(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(xI(e))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(n);if(this.format._options.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}e()}},$L=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>KA.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>YA.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>XA.includes(e))}_codecUnsupportedHint(e){return``}},eR=class extends $L{constructor(e={}){if(!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(e.fastStart!==void 0&&![!1,`in-memory`,`reserve`,`fragmented`].includes(e.fastStart))throw TypeError(`options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.`);if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError(`options.minimumFragmentDuration, when provided, must be a non-negative number.`);if(e.onFtyp!==void 0&&typeof e.onFtyp!=`function`)throw TypeError(`options.onFtyp, when provided, must be a function.`);if(e.onMoov!==void 0&&typeof e.onMoov!=`function`)throw TypeError(`options.onMoov, when provided, must be a function.`);if(e.onMdat!==void 0&&typeof e.onMdat!=`function`)throw TypeError(`options.onMdat, when provided, must be a function.`);if(e.onMoof!==void 0&&typeof e.onMoof!=`function`)throw TypeError(`options.onMoof, when provided, must be a function.`);if(e.metadataFormat!==void 0&&![`mdir`,`mdta`,`udta`,`auto`].includes(e.metadataFormat))throw TypeError(`options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.`);super(),this._options=e}getSupportedTrackCounts(){let e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new QL(e,this)}},tR=class extends eR{constructor(e){super(e)}get _name(){return`MP4`}get fileExtension(){return`.mp4`}get mimeType(){return`video/mp4`}getSupportedCodecs(){return[...KA,...JA,`pcm-s16`,`pcm-s16be`,`pcm-s24`,`pcm-s24be`,`pcm-s32`,`pcm-s32be`,`pcm-f32`,`pcm-f32be`,`pcm-f64`,`pcm-f64be`,...XA]}_codecUnsupportedHint(e){return new nR().getSupportedCodecs().includes(e)?` Switching to MOV will grant support for this codec.`:``}},nR=class extends eR{constructor(e){super(e)}get _name(){return`MOV`}get fileExtension(){return`.mov`}get mimeType(){return`video/quicktime`}getSupportedCodecs(){return[...KA,...YA]}_codecUnsupportedHint(e){return new tR().getSupportedCodecs().includes(e)?` Switching to MP4 will grant support for this codec.`:``}},rR=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!KA.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${KA.join(`, `)}.`);if(!(e.bitrate instanceof lR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate must be a positive integer or a quality.`);if(e.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`config.keyFrameInterval, when provided, must be a non-negative number.`);if(e.sizeChangeBehavior!==void 0&&![`deny`,`passThrough`,`fill`,`contain`,`cover`].includes(e.sizeChangeBehavior))throw TypeError(`config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.`);if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedChunk, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);iR(e.codec,e)},iR=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.alpha!==void 0&&![`discard`,`keep`].includes(t.alpha))throw TypeError(`options.alpha, when provided, must be 'discard' or 'keep'.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.latencyMode!==void 0&&![`quality`,`realtime`].includes(t.latencyMode))throw TypeError(`latencyMode, when provided, must be 'quality' or 'realtime'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&dj(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(t.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(t.hardwareAcceleration))throw TypeError(`hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`);if(t.scalabilityMode!==void 0&&typeof t.scalabilityMode!=`string`)throw TypeError(`scalabilityMode, when provided, must be a string.`);if(t.contentHint!==void 0&&typeof t.contentHint!=`string`)throw TypeError(`contentHint, when provided, must be a string.`)},aR=e=>{let t=e.bitrate instanceof lR?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??rj(e.codec,e.width,e.height,t),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??`discard`,framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...fj(e.codec)}},oR=e=>{if(!e||typeof e!=`object`)throw TypeError(`Encoding config must be an object.`);if(!YA.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${YA.join(`, `)}.`);if(e.bitrate===void 0&&(!qA.includes(e.codec)||e.codec===`flac`))throw TypeError(`config.bitrate must be provided for compressed audio codecs.`);if(e.bitrate!==void 0&&!(e.bitrate instanceof lR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`config.bitrate, when provided, must be a positive integer or a quality.`);if(e.onEncodedPacket!==void 0&&typeof e.onEncodedPacket!=`function`)throw TypeError(`config.onEncodedChunk, when provided, must be a function.`);if(e.onEncoderConfig!==void 0&&typeof e.onEncoderConfig!=`function`)throw TypeError(`config.onEncoderConfig, when provided, must be a function.`);sR(e.codec,e)},sR=(e,t)=>{if(!t||typeof t!=`object`)throw TypeError(`Encoding options must be an object.`);if(t.bitrateMode!==void 0&&![`constant`,`variable`].includes(t.bitrateMode))throw TypeError(`bitrateMode, when provided, must be 'constant' or 'variable'.`);if(t.fullCodecString!==void 0&&typeof t.fullCodecString!=`string`)throw TypeError(`fullCodecString, when provided, must be a string.`);if(t.fullCodecString!==void 0&&dj(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},cR=e=>{let t=e.bitrate instanceof lR?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??oj(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...pj(e.codec)}},lR=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,n){let r=3e6*(t*n/(1920*1080))**.95*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[e]*this._factor;return Math.ceil(r/1e3)*1e3}_toAudioBitrate(e){if(qA.includes(e)||e===`flac`)return;let t={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!t)throw Error(`Unhandled codec: ${e}`);let n=t*this._factor;return e===`aac`?n=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e):e===`opus`||e===`vorbis`?n=Math.max(6e3,n):e===`mp3`&&(n=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-n)<Math.abs(e-n)?t:e)),Math.round(n/1e3)*1e3}},uR=new lR(2),dR=async(e,t={})=>{let{width:n=1280,height:r=720,bitrate:i=1e6,...a}=t;if(!KA.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`width must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`height must be a positive integer.`);if(!(i instanceof lR)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer or a quality.`);iR(e,a);let o=null;return OM.length>0&&(o??=aR({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a}),OM.some(t=>t.supports(e,o)))?!0:typeof VideoEncoder>`u`||(n%2==1||r%2==1)&&(e===`avc`||e===`hevc`)||(o??=aR({codec:e,width:n,height:r,bitrate:i,framerate:void 0,...a,alpha:`discard`}),!(await VideoEncoder.isConfigSupported(o)).supported)?!1:CA()?new Promise(async e=>{try{let t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(o);let i=new Uint8Array(n*r*4),a=new VideoFrame(i,{format:`RGBA`,codedWidth:n,codedHeight:r,timestamp:0});t.encode(a),a.close(),await t.flush(),e(!0)}catch{e(!1)}}):!0},fR=async(e,t={})=>{let{numberOfChannels:n=2,sampleRate:r=48e3,bitrate:i=128e3,...a}=t;if(!YA.includes(e))return!1;if(!Number.isInteger(n)||n<=0)throw TypeError(`numberOfChannels must be a positive integer.`);if(!Number.isInteger(r)||r<=0)throw TypeError(`sampleRate must be a positive integer.`);if(!(i instanceof lR)&&(!Number.isInteger(i)||i<=0))throw TypeError(`bitrate must be a positive integer.`);sR(e,a);let o=null;return kM.length>0&&(o??=cR({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),kM.some(t=>t.supports(e,o)))||qA.includes(e)?!0:typeof AudioEncoder>`u`?!1:(o??=cR({codec:e,numberOfChannels:n,sampleRate:r,bitrate:i,...a}),(await AudioEncoder.isConfigSupported(o)).supported===!0)},pR=async(e=YA,t)=>{let n=await Promise.all(e.map(e=>fR(e,t)));return e.filter((e,t)=>n[t])},mR=async(e,t)=>{for(let n of e)if(await dR(n,t))return n;return null},hR=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_ensureValidAdd(){if(!this._connectedTrack)throw Error(`Source is not connected to an output track.`);if(this._connectedTrack.output.state===`canceled`)throw Error(`Output has been canceled.`);if(this._connectedTrack.output.state===`finalizing`||this._connectedTrack.output.state===`finalized`)throw Error(`Output has been finalized.`);if(this._connectedTrack.output.state===`pending`)throw Error(`Output has not started.`);if(this._closed)throw Error(`Source is closed.`)}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error(`Cannot call close without connecting the source to an output track.`);if(e.output.state===`pending`)throw Error(`Cannot call close before output has been started.`);this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state===`finalizing`||e.output.state===`finalized`)&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},gR=class extends hR{constructor(e){if(super(),this._connectedTrack=null,!KA.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${KA.join(`, `)}.`);this._codec=e}},_R=class extends gR{constructor(e){super(e)}add(e,t){if(!(e instanceof jM))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},vR=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.codedWidth=null,this.codedHeight=null,this.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new yA,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null}async add(e,t,n){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.codedWidth!==null&&this.codedHeight!==null){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){let n=this.encodingConfig.sizeChangeBehavior??`deny`;if(n!==`passThrough`){if(n===`deny`)throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'strict' in the encoding options.`);{let r=!1;this.resizeCanvas||(typeof document<`u`?(this.resizeCanvas=document.createElement(`canvas`),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),r=!0);let i=this.resizeCanvas.getContext(`2d`,{alpha:CA()});U(i),r||(CA()?(i.fillStyle=`black`,i.fillRect(0,0,this.codedWidth,this.codedHeight)):i.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(i,{fit:n}),t&&e.close(),e=new VM(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),t=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),U(this.encoderInitialized);let r=this.encodingConfig.keyFrameInterval??5,i=Math.floor(e.timestamp/r),a={...n,keyFrame:n?.keyFrame||r===0||i!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=i,this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,a)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n}else{U(this.encoder);let n=e.toVideoFrame();if(!this.alphaEncoder)this.encoder.encode(n,a),n.close();else if(n.format&&!n.format.includes(`A`)||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(n,a),n.close();else{let e=n.displayWidth,t=n.displayHeight;if(!this.splitter)try{this.splitter=new yR(e,t)}catch(e){console.error(`Due to an error, only color data will be encoded.`,e),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(n,a),n.close()}if(this.splitter){let e=this.splitter.extractColor(n),t=this.splitter.extractAlpha(n);this.alphaFrameQueue.push(t),this.encoder.encode(e,a),e.close(),n.close()}}t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0}))}await this.muxer.mutex.currentPromise}finally{t&&e.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t=aR({width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);let n=OM.find(e=>e.supports(this.encodingConfig.codec,t));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof jM))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if(typeof VideoEncoder>`u`)throw Error(`VideoEncoder is not supported by this browser.`);if(t.alpha=`discard`,this.encodingConfig.alpha===`keep`&&(t.latencyMode=`quality`),(t.width%2==1||t.height%2==1)&&(this.encodingConfig.codec===`avc`||this.encodingConfig.codec===`hevc`))throw Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??`no-preference`}) is not supported by this browser. Consider using another codec or changing your video parameters.`);let e=[],n=[],r=0,i=0,a=(e,t,n)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let i=jM.fromEncodedChunk(e,r);this.encodingConfig.onEncodedPacket?.(i,n),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,i,n).catch(e=>{this.error??=e})},o=Error(`Encoding error`).stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder){a(t,null,o);return}let s=this.alphaFrameQueue.shift();U(s!==void 0),s?(this.alphaEncoder.encode(s,{keyFrame:t.type===`key`}),i++,s.close(),e.push({chunk:t,meta:o})):i===0?a(t,null,o):(n.push(r+i),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),this.encodingConfig.alpha===`keep`){let o=Error(`Encoding error`).stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{i--;let s=e.shift();for(U(s!==void 0),a(s.chunk,t,s.meta),r++;n.length>0&&n[0]===r;){n.shift();let t=e.shift();U(t!==void 0),a(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}U(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await this.alphaEncoder?.flush()),this.encoder.state!==`closed`&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!==`closed`&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},yR=class{constructor(e,t){this.lastFrame=null,typeof OffscreenCanvas<`u`?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement(`canvas`),this.canvas.width=e,this.canvas.height=t);let n=this.canvas.getContext(`webgl2`,{alpha:!0});if(!n)throw Error(`Couldn't acquire WebGL 2 context.`);this.gl=n,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,`u_resolution`),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,`u_sourceTexture`),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,`u_sourceTexture`),0)}createVertexShader(){return this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
2124
2124
  in vec2 a_position;
2125
2125
  in vec2 a_texCoord;
2126
2126
  out vec2 v_texCoord;
@@ -2184,7 +2184,7 @@ ${t.slice(l+2)}`,d+=1;else break}t.push({indent:l,number:parseInt(s,10),content:
2184
2184
 
2185
2185
  fragColor = result;
2186
2186
  }
2187
- `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||console.error(`Shader compile error:`,this.gl.getShaderInfoLog(n)),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.colorProgram,`a_position`),i=this.gl.getAttribLocation(this.colorProgram,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:`discard`})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:t,height:n}=this.canvas,r=Math.ceil(t/2)*Math.ceil(n/2),i=t*n+r*2,a=Math.ceil(i/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,i),U(o[t*n]===128),U(o[o.length-1]===128);let s={format:`I420`,codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,s)}close(){this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null}},dR=class extends sR{constructor(e){JL(e),super(e.codec),this._encoder=new lR(this,e)}add(e,t){if(!(e instanceof MM))throw TypeError(`videoSample must be a VideoSample.`);return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},fR=class extends oR{constructor(e){if(super(),this._connectedTrack=null,!BA.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${BA.join(`, `)}.`);this._codec=e}},pR=class extends fR{constructor(e){super(e)}add(e,t){if(!(e instanceof SM))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},mR=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new uA,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),U(this.encoderInitialized);{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new VM({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{U(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){U(this.outputSampleSize),U(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let c=e.allocationSize({planeIndex:0,format:`f32-planar`}),l=new Float32Array(c/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<n;t++){e.copyTo(l,{planeIndex:t,format:`f32-planar`});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,l[e*o+a])}}t&&e.close();let u={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,c=e*o,l=new SM(new Uint8Array(r),`key`,a+c/i,t/i);this.encodingConfig.onEncodedPacket?.(l,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=$L({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(r);let i=bM.find(e=>e.supports(this.encodingConfig.codec,r));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof SM))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else if(RA.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(`AudioEncoder is not supported by this browser.`);if(!(await AudioEncoder.isConfigSupported(r)).supported)throw Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.numberOfChannels} channels, ${r.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let e=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2?!0:FA(Tk(t.decoderConfig.description)).objectType===0,e){let e=Number(Sk(r.codec.split(`.`)));t.decoderConfig.description=IA({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=SM.fromEncodedChunk(e);this.encodingConfig.onEncodedPacket?.(n,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.error??=e})},error:t=>{t.stack=e,this.error??=t}}),this.encoder.configure(r)}U(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=tj(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,tA((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,tA(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=tA(Math.floor(n*32767),-32768,32767);e.setUint8(t,CM(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=tA(Math.floor(n*32767),-32768,32767);e.setUint8(t,TM(r))}:U(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,tA((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,tA(Math.round(n*32767),-32768,32767),r):U(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>Qk(e,t,tA((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>$k(e,t,tA(Math.round(n*8388607),-8388608,8388607),r):U(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,tA((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,tA(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):U(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):U(!1);break;default:Yk(n),U(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!==`closed`&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},hR=class extends fR{constructor(e){ZL(e),super(e.codec),this._encoder=new mR(this,e)}add(e){if(!(e instanceof VM))throw TypeError(`audioSample must be an AudioSample.`);return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},gR=class extends oR{constructor(e){if(super(),this._connectedTrack=null,!VA.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${VA.join(`, `)}.`);this._codec=e}},_R=[`video`,`audio`,`subtitle`],vR=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!sA(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&jA(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`)},yR=class{constructor(e){if(this.state=`pending`,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new Rk,this._metadataTags={},!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof WL))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof IL))throw TypeError(`options.target must be a Target.`);if(e.target._output)throw Error(`Target is already used for another output.`);e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof sR))throw TypeError(`source must be a VideoSource.`);if(vR(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack(`video`,e,t)}addAudioTrack(e,t={}){if(!(e instanceof fR))throw TypeError(`source must be an AudioSource.`);vR(t),this._addTrack(`audio`,e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof gR))throw TypeError(`source must be a SubtitleSource.`);vR(t),this._addTrack(`subtitle`,e,t)}setMetadataTags(e){if(kA(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e,t,n){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(t._connectedTrack)throw Error(`Source is already used for a track.`);let r=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((t,n)=>t+(n.type===e?1:0),0),a=r[e].max;if(i===a)throw Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?``:`s`}.`);let o=r.total.max;if(this._tracks.length===o)throw Error(`${this.format._name} does not support more than ${o} tracks${o===1?``:`s`} in total.`);let s={id:this._tracks.length+1,output:this,type:e,source:t,metadata:n};if(s.type===`video`){let e=this.format.getSupportedVideoCodecs();if(e.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}else if(s.type===`audio`){let e=this.format.getSupportedAudioCodecs();if(e.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}else if(s.type===`subtitle`){let e=this.format.getSupportedSubtitleCodecs();if(e.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}this._tracks.push(s),t._connectedTrack=s}async start(){let e=this.format.getSupportedTrackCounts();for(let t of _R){let n=this._tracks.reduce((e,n)=>e+(n.type===t?1:0),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this._tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(console.warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`,this._writer.start();let e=await this._mutex.acquire();await this._muxer.start();let t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){console.warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(console.warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state=`finalized`,e()})()}},bR=e=>{if(e!==void 0&&(!e||typeof e!=`object`))throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!LA.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${LA.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof eR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.`);if(e?.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&IM(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`)},xR=e=>{if(e!==void 0&&(!e||typeof e!=`object`))throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!BA.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${BA.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof eR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`)},SR=2,CR=48e3,wR=class e{static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new DR,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof gF))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof yR))throw TypeError(`options.output must be an Output.`);if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(typeof e.video!=`function`&&bR(e.video),typeof e.audio!=`function`&&xR(e.audio),e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a finite number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw TypeError(`options.trim.start must be less than options.trim.end.`);if(e.tags!==void 0&&(typeof e.tags!=`object`||!e.tags)&&typeof e.tags!=`function`)throw TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&kA(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this.input=e.input,this.output=e.output;let{promise:t,resolve:n}=Wk();this._started=t,this._start=n}async _init(){this._startTimestamp=this._options.trim?.start??Math.max(await this.input.getFirstTimestamp(),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);let e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts(),n=1,r=1;for(let i of e){let e;if(i.isVideoTrack()?this._options.video&&(typeof this._options.video==`function`?(e=await this._options.video(i,n),bR(e),n++):e=this._options.video):i.isAudioTrack()?this._options.audio&&(typeof this._options.audio==`function`?(e=await this._options.audio(i,r),xR(e),r++):e=this._options.audio):U(!1),e?.discard){this.discardedTracks.push({track:i,reason:`discarded_by_user`});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:i,reason:`max_track_count_reached`});continue}if(this._addedCounts[i.type]===t[i.type].max){this.discardedTracks.push({track:i,reason:`max_track_count_of_type_reached`});continue}i.isVideoTrack()?await this._processVideoTrack(i,e??{}):i.isAudioTrack()&&await this._processAudioTrack(i,e??{})}let i=await this.input.getMetadataTags(),a;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(i):this._options.tags;kA(e),a=e}else a=i;let o=(await this.input.getFormat()).mimeType===this.output.format.mimeType,s=i.raw===a.raw;if(i.raw&&s&&!o&&delete a.raw,this.output.setMetadataTags(a),this.isValid=this._totalTrackCount>=t.total.min&&this._addedCounts.video>=t.video.min&&this._addedCounts.audio>=t.audio.min&&this._addedCounts.subtitle>=t.subtitle.min,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||e.push(`
2187
+ `),n=this.gl.createProgram();return this.gl.attachShader(n,e),this.gl.attachShader(n,t),this.gl.linkProgram(n),n}createShader(e,t){let n=this.gl.createShader(e);return this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)||console.error(`Shader compile error:`,this.gl.getShaderInfoLog(n)),n}createVAO(){let e=this.gl.createVertexArray();this.gl.bindVertexArray(e);let t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),n=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,n),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);let r=this.gl.getAttribLocation(this.colorProgram,`a_position`),i=this.gl.getAttribLocation(this.colorProgram,`a_texCoord`);return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,8),e}createTexture(){let e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateTexture(e){this.lastFrame!==e&&((e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:`discard`})}extractAlpha(e){this.updateTexture(e),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);let{width:t,height:n}=this.canvas,r=Math.ceil(t/2)*Math.ceil(n/2),i=t*n+r*2,a=Math.ceil(i/(t*4)),o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,i),U(o[t*n]===128),U(o[o.length-1]===128);let s={format:`I420`,codedWidth:t,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,s)}close(){this.gl.getExtension(`WEBGL_lose_context`)?.loseContext(),this.gl=null}},bR=class extends gR{constructor(e){rR(e),super(e.codec),this._encoder=new vR(this,e)}add(e,t){if(!(e instanceof VM))throw TypeError(`videoSample must be a VideoSample.`);return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},xR=class extends hR{constructor(e){if(super(),this._connectedTrack=null,!YA.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${YA.join(`, `)}.`);this._codec=e}},SR=class extends xR{constructor(e){super(e)}add(e,t){if(!(e instanceof jM))throw TypeError(`packet must be an EncodedPacket.`);if(e.isMetadataOnly)throw TypeError(`Metadata-only packets cannot be added.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`meta, when provided, must be an object.`);return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},CR=class{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new yA,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),U(this.encoderInitialized);{let t=Math.round(e.timestamp*e.sampleRate),n=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=n;else{let n=t-this.lastEndSampleIndex;if(n>=64){let t=new XM({data:new Float32Array(n*e.numberOfChannels),format:`f32-planar`,sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),n=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await n,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{U(this.encoder);let n=e.toAudioData();this.encoder.encode(n),n.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener(`dequeue`,e,{once:!0})),await this.muxer.mutex.currentPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){U(this.outputSampleSize),U(this.writeOutputValue);let{numberOfChannels:n,numberOfFrames:r,sampleRate:i,timestamp:a}=e,o=2048,s=[];for(let t=0;t<r;t+=o){let r=Math.min(o,e.numberOfFrames-t),i=r*n*this.outputSampleSize,a=new ArrayBuffer(i),c=new DataView(a);s.push({frameCount:r,view:c})}let c=e.allocationSize({planeIndex:0,format:`f32-planar`}),l=new Float32Array(c/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<n;t++){e.copyTo(l,{planeIndex:t,format:`f32-planar`});for(let e=0;e<s.length;e++){let{frameCount:r,view:i}=s[e];for(let a=0;a<r;a++)this.writeOutputValue(i,(a*n+t)*this.outputSampleSize,l[e*o+a])}}t&&e.close();let u={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:n,sampleRate:i}};for(let e=0;e<s.length;e++){let{frameCount:t,view:n}=s[e],r=n.buffer,c=e*o,l=new jM(new Uint8Array(r),`key`,a+c/i,t/i);this.encodingConfig.onEncodedPacket?.(l,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:n}=e,r=cR({numberOfChannels:t,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(r);let i=kM.find(e=>e.supports(this.encodingConfig.codec,r));if(i)this.customEncoder=new i,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=r,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof jM))throw TypeError(`The first argument passed to onPacket must be an EncodedPacket.`);if(t!==void 0&&(!t||typeof t!=`object`))throw TypeError(`The second argument passed to onPacket must be an object or undefined.`);this.encodingConfig.onEncodedPacket?.(e,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else if(qA.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>`u`)throw Error(`AudioEncoder is not supported by this browser.`);if(!(await AudioEncoder.isConfigSupported(r)).supported)throw Error(`This specific encoder configuration (${r.codec}, ${r.bitrate} bps, ${r.numberOfChannels} channels, ${r.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let e=Error(`Encoding error`).stack;this.encoder=new AudioEncoder({output:(e,t)=>{if(this.encodingConfig.codec===`aac`&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2?!0:WA(Pk(t.decoderConfig.description)).objectType===0,e){let e=Number(jk(r.codec.split(`.`)));t.decoderConfig.description=GA({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let n=jM.fromEncodedChunk(e);this.encodingConfig.onEncodedPacket?.(n,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,n,t).catch(e=>{this.error??=e})},error:t=>{t.stack=e,this.error??=t}}),this.encoder.configure(r)}U(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let e=this.encodingConfig.codec,{dataType:t,sampleSize:n,littleEndian:r}=uj(e);switch(this.outputSampleSize=n,n){case 1:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint8(t,uA((n+1)*127.5,0,255)):t===`signed`?this.writeOutputValue=(e,t,n)=>{e.setInt8(t,uA(Math.round(n*128),-128,127))}:t===`ulaw`?this.writeOutputValue=(e,t,n)=>{let r=uA(Math.floor(n*32767),-32768,32767);e.setUint8(t,MM(r))}:t===`alaw`?this.writeOutputValue=(e,t,n)=>{let r=uA(Math.floor(n*32767),-32768,32767);e.setUint8(t,PM(r))}:U(!1);break;case 2:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint16(t,uA((n+1)*32767.5,0,65535),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt16(t,uA(Math.round(n*32767),-32768,32767),r):U(!1);break;case 3:t===`unsigned`?this.writeOutputValue=(e,t,n)=>sA(e,t,uA((n+1)*8388607.5,0,16777215),r):t===`signed`?this.writeOutputValue=(e,t,n)=>cA(e,t,uA(Math.round(n*8388607),-8388608,8388607),r):U(!1);break;case 4:t===`unsigned`?this.writeOutputValue=(e,t,n)=>e.setUint32(t,uA((n+1)*2147483647.5,0,4294967295),r):t===`signed`?this.writeOutputValue=(e,t,n)=>e.setInt32(t,uA(Math.round(n*2147483647),-2147483648,2147483647),r):t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat32(t,n,r):U(!1);break;case 8:t===`float`?this.writeOutputValue=(e,t,n)=>e.setFloat64(t,n,r):U(!1);break;default:iA(n),U(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!==`closed`&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},wR=class extends xR{constructor(e){oR(e),super(e.codec),this._encoder=new CR(this,e)}add(e){if(!(e instanceof XM))throw TypeError(`audioSample must be an AudioSample.`);return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},TR=class extends hR{constructor(e){if(super(),this._connectedTrack=null,!XA.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${XA.join(`, `)}.`);this._codec=e}},ER=[`video`,`audio`,`subtitle`],DR=e=>{if(!e||typeof e!=`object`)throw TypeError(`metadata must be an object.`);if(e.languageCode!==void 0&&!gA(e.languageCode))throw TypeError(`metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.`);if(e.name!==void 0&&typeof e.name!=`string`)throw TypeError(`metadata.name, when provided, must be a string.`);if(e.disposition!==void 0&&BA(e.disposition),e.maximumPacketCount!==void 0&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError(`metadata.maximumPacketCount, when provided, must be a non-negative integer.`)},OR=class{constructor(e){if(this.state=`pending`,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new qk,this._metadataTags={},!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.format instanceof $L))throw TypeError(`options.format must be an OutputFormat.`);if(!(e.target instanceof GL))throw TypeError(`options.target must be a Target.`);if(e.target._output)throw Error(`Target is already used for another output.`);e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof gR))throw TypeError(`source must be a VideoSource.`);if(DR(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);this._addTrack(`video`,e,t)}addAudioTrack(e,t={}){if(!(e instanceof xR))throw TypeError(`source must be an AudioSource.`);DR(t),this._addTrack(`audio`,e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof TR))throw TypeError(`source must be a SubtitleSource.`);DR(t),this._addTrack(`subtitle`,e,t)}setMetadataTags(e){if(RA(e),this.state!==`pending`)throw Error(`Cannot set metadata tags after output has been started or canceled.`);this._metadataTags=e}_addTrack(e,t,n){if(this.state!==`pending`)throw Error(`Cannot add track after output has been started or canceled.`);if(t._connectedTrack)throw Error(`Source is already used for a track.`);let r=this.format.getSupportedTrackCounts(),i=this._tracks.reduce((t,n)=>t+(n.type===e?1:0),0),a=r[e].max;if(i===a)throw Error(a===0?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${a} ${e} track${a===1?``:`s`}.`);let o=r.total.max;if(this._tracks.length===o)throw Error(`${this.format._name} does not support more than ${o} tracks${o===1?``:`s`} in total.`);let s={id:this._tracks.length+1,output:this,type:e,source:t,metadata:n};if(s.type===`video`){let e=this.format.getSupportedVideoCodecs();if(e.length===0)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}else if(s.type===`audio`){let e=this.format.getSupportedAudioCodecs();if(e.length===0)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}else if(s.type===`subtitle`){let e=this.format.getSupportedSubtitleCodecs();if(e.length===0)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(s.source._codec));if(!e.includes(s.source._codec))throw Error(`Codec '${s.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map(e=>`'${e}'`).join(`, `)}.`+this.format._codecUnsupportedHint(s.source._codec))}this._tracks.push(s),t._connectedTrack=s}async start(){let e=this.format.getSupportedTrackCounts();for(let t of ER){let n=this._tracks.reduce((e,n)=>e+(n.type===t?1:0),0),r=e[t].min;if(n<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${r===1?``:`s`}.`:`${this.format._name} requires at least ${r} ${t} track${r===1?``:`s`}.`)}let t=e.total.min;if(this._tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?``:`s`}.`:`${this.format._name} requires at least ${t} track${t===1?``:`s`}.`);if(this.state===`canceled`)throw Error(`Output has been canceled.`);return this._startPromise?(console.warn(`Output has already been started.`),this._startPromise):this._startPromise=(async()=>{this.state=`started`,this._writer.start();let e=await this._mutex.acquire();await this._muxer.start();let t=this._tracks.map(e=>e.source._start());await Promise.all(t),e()})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn(`Output has already been canceled.`),this._cancelPromise;if(this.state===`finalizing`||this.state===`finalized`){console.warn(`Output has already been finalized.`);return}return this._cancelPromise=(async()=>{this.state=`canceled`;let e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await this._writer.close(),e()})()}async finalize(){if(this.state===`pending`)throw Error(`Cannot finalize before starting.`);if(this.state===`canceled`)throw Error(`Cannot finalize after canceling.`);return this._finalizePromise?(console.warn(`Output has already been finalized.`),this._finalizePromise):this._finalizePromise=(async()=>{this.state=`finalizing`;let e=await this._mutex.acquire(),t=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state=`finalized`,e()})()}},kR=e=>{if(e!==void 0&&(!e||typeof e!=`object`))throw TypeError(`options.video, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.video.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.video.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!KA.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${KA.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof lR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.video.bitrate, when provided, must be a positive integer or a quality.`);if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError(`options.video.width, when provided, must be a positive integer.`);if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError(`options.video.height, when provided, must be a positive integer.`);if(e?.fit!==void 0&&![`fill`,`contain`,`cover`].includes(e.fit))throw TypeError(`options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.`);if(e?.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw TypeError(`When both options.video.width and options.video.height are provided, options.video.fit must also be provided.`);if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError(`options.video.rotate, when provided, must be 0, 90, 180 or 270.`);if(e?.allowRotationMetadata!==void 0&&typeof e.allowRotationMetadata!=`boolean`)throw TypeError(`options.video.allowRotationMetadata, when provided, must be a boolean.`);if(e?.crop!==void 0&&GM(e.crop,`options.video.`),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError(`options.video.frameRate, when provided, must be a finite positive number.`);if(e?.alpha!==void 0&&![`discard`,`keep`].includes(e.alpha))throw TypeError(`options.video.alpha, when provided, must be either 'discard' or 'keep'.`);if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError(`options.video.keyFrameInterval, when provided, must be a non-negative number.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.video.process, when provided, must be a function.`);if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError(`options.video.processedWidth, when provided, must be a positive integer.`);if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError(`options.video.processedHeight, when provided, must be a positive integer.`);if(e?.hardwareAcceleration!==void 0&&![`no-preference`,`prefer-hardware`,`prefer-software`].includes(e.hardwareAcceleration))throw TypeError(`options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.`)},AR=e=>{if(e!==void 0&&(!e||typeof e!=`object`))throw TypeError(`options.audio, when provided, must be an object.`);if(e?.discard!==void 0&&typeof e.discard!=`boolean`)throw TypeError(`options.audio.discard, when provided, must be a boolean.`);if(e?.forceTranscode!==void 0&&typeof e.forceTranscode!=`boolean`)throw TypeError(`options.audio.forceTranscode, when provided, must be a boolean.`);if(e?.codec!==void 0&&!YA.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${YA.join(`, `)}.`);if(e?.bitrate!==void 0&&!(e.bitrate instanceof lR)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError(`options.audio.bitrate, when provided, must be a positive integer or a quality.`);if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError(`options.audio.numberOfChannels, when provided, must be a positive integer.`);if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError(`options.audio.sampleRate, when provided, must be a positive integer.`);if(e?.process!==void 0&&typeof e.process!=`function`)throw TypeError(`options.audio.process, when provided, must be a function.`);if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError(`options.audio.processedNumberOfChannels, when provided, must be a positive integer.`);if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError(`options.audio.processedSampleRate, when provided, must be a positive integer.`)},jR=2,MR=48e3,NR=class e{static async init(t){let n=new e(t);return await n._init(),n}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new IR,this._totalDuration=null,this._maxTimestamps=new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!=`object`)throw TypeError(`options must be an object.`);if(!(e.input instanceof TF))throw TypeError(`options.input must be an Input.`);if(!(e.output instanceof OR))throw TypeError(`options.output must be an Output.`);if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!==`pending`)throw TypeError(`options.output must be fresh: no tracks or metadata tags added and not started.`);if(typeof e.video!=`function`&&kR(e.video),typeof e.audio!=`function`&&AR(e.audio),e.trim!==void 0&&(!e.trim||typeof e.trim!=`object`))throw TypeError(`options.trim, when provided, must be an object.`);if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError(`options.trim.start, when provided, must be a finite number.`);if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw TypeError(`options.trim.end, when provided, must be a finite number.`);if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw TypeError(`options.trim.start must be less than options.trim.end.`);if(e.tags!==void 0&&(typeof e.tags!=`object`||!e.tags)&&typeof e.tags!=`function`)throw TypeError(`options.tags, when provided, must be an object or a function.`);if(typeof e.tags==`object`&&RA(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!=`boolean`)throw TypeError(`options.showWarnings, when provided, must be a boolean.`);this._options=e,this.input=e.input,this.output=e.output;let{promise:t,resolve:n}=$k();this._started=t,this._start=n}async _init(){this._startTimestamp=this._options.trim?.start??Math.max(await this.input.getFirstTimestamp(),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);let e=await this.input.getTracks(),t=this.output.format.getSupportedTrackCounts(),n=1,r=1;for(let i of e){let e;if(i.isVideoTrack()?this._options.video&&(typeof this._options.video==`function`?(e=await this._options.video(i,n),kR(e),n++):e=this._options.video):i.isAudioTrack()?this._options.audio&&(typeof this._options.audio==`function`?(e=await this._options.audio(i,r),AR(e),r++):e=this._options.audio):U(!1),e?.discard){this.discardedTracks.push({track:i,reason:`discarded_by_user`});continue}if(this._totalTrackCount===t.total.max){this.discardedTracks.push({track:i,reason:`max_track_count_reached`});continue}if(this._addedCounts[i.type]===t[i.type].max){this.discardedTracks.push({track:i,reason:`max_track_count_of_type_reached`});continue}i.isVideoTrack()?await this._processVideoTrack(i,e??{}):i.isAudioTrack()&&await this._processAudioTrack(i,e??{})}let i=await this.input.getMetadataTags(),a;if(this._options.tags){let e=typeof this._options.tags==`function`?await this._options.tags(i):this._options.tags;RA(e),a=e}else a=i;let o=(await this.input.getFormat()).mimeType===this.output.format.mimeType,s=i.raw===a.raw;if(i.raw&&s&&!o&&delete a.raw,this.output.setMetadataTags(a),this.isValid=this._totalTrackCount>=t.total.min&&this._addedCounts.video>=t.video.min&&this._addedCounts.audio>=t.audio.min&&this._addedCounts.subtitle>=t.subtitle.min,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>e.reason!==`discarded_by_user`);t.length>0&&e.push(`Some tracks had to be discarded from the conversion:`,t),this.isValid||e.push(`
2188
2188
 
2189
2189
  `+this._getInvalidityExplanation().join(``)),e.length>0&&console.warn(...e)}}_getInvalidityExplanation(){let e=[];if(this.discardedTracks.length===0)e.push(`Due to missing tracks, this conversion cannot be executed.`);else{let t=this.discardedTracks.every(e=>e.reason===`discarded_by_user`||e.reason===`no_encodable_target_codec`);if(e.push(`Due to discarded tracks, this conversion cannot be executed.`),t){let t=this.discardedTracks.flatMap(e=>e.reason===`discarded_by_user`?[]:e.track.type===`video`?this.output.format.getSupportedVideoCodecs():e.track.type===`audio`?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs());t.length===1?e.push(`\nTracks were discarded because your environment is not able to encode '${t[0]}'.`):e.push(`
2190
2190
  Tracks were discarded because your environment is not able to encode any of the following codecs: ${t.map(e=>`'${e}'`).join(`, `)}.`),t.includes(`mp3`)&&e.push(`
@@ -2193,7 +2193,7 @@ The @mediabunny/aac-encoder extension package provides support for encoding AAC.
2193
2193
  The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),t.includes(`flac`)&&e.push(`
2194
2194
  The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
2195
2195
  Check the discardedTracks field for more info.`)}return e}async execute(){if(!this.isValid)throw Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
2196
- `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new TR;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=xk(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&FM(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??tR,s=await aR(_,{width:t.process&&t.processedWidth?t.processedWidth:f,height:t.process&&t.processedHeight?t.processedHeight:p,bitrate:n});if(!s){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}let c={codec:s,bitrate:n,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:y,hardwareAcceleration:t.hardwareAcceleration},m=new dR(c);r=m;let h=f!==u||p!==d||i!==0&&(!o||t.process!==void 0)||!!l||e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight;if(!h){let t=new yR({format:new KL,target:new RL}),n=new dR(c);t.addVideoTrack(n),await t.start();let r=await new rN(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new iN(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new MM(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new MM(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(U(c!==null),U(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new rN(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{U(i),U(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(U(o!==null),U(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new cR(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new ZM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:sA(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof MM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new MM(e):new MM(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new pR(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new ZM(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??tR,a=await iR(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>zA.includes(e))&&u.some(e=>zA.includes(e))&&(s!==SR||c!==CR)){let e=(await iR(u,{numberOfChannels:SR,sampleRate:CR,bitrate:i})).find(e=>zA.includes(e));e&&(l=!0,n=e,s=SR,c=CR)}else n=a[0]??null;if(n===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}if(l)r=this._resampleAudio(e,t,n,s,c,i);else{let a=new hR({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new sN(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:sA(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof VM))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new hR({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new OR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new sN(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=tA(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},TR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},ER=5,DR=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<ER&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){return this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0)),t-this.computeMinAndMaybeResolve()>=ER}wait(e){let{promise:t,resolve:n}=Wk();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},OR=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){U(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;U(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new VM({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function kR(){return typeof AudioEncoder<`u`}async function AR(e,t){let n=new gF({source:new fF(e),formats:uF}),r=new LL,i=new yR({format:new KL({fastStart:`in-memory`}),target:r});try{let a=await wR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:tR}});t&&(a.onProgress=t),await a.execute();let o=r.buffer;if(!o)throw Error(`Audio processing produced no output`);let s=e.name.replace(/\.[^.]+$/,``);return{file:new File([o],`${s}.m4a`,{type:`audio/mp4`})}}finally{n.dispose()}}var jR={isSupported:kR,processToFile:AR},MR=new Set([`moov`,`trak`]);function NR(e){return 12+(e===1?32:20)+8+2}function PR(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+NR(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else MR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var FR=1920,IR=1080,LR=640,RR=32;function zR(){return typeof VideoEncoder<`u`}async function BR(e){let t=new gF({source:new fF(e),formats:uF});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=l(a),s=Math.min(a*.1,1),c=await new iN(e).getCanvas(s);if(!c)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=c.canvas,d=u.width,f=u.height,p=Math.min(LR/d,1),m=Math.round(d*p),h=Math.round(f*p),g=document.createElement(`canvas`);g.width=m,g.height=h;let _=g.getContext(`2d`);if(!_)return{sourceWidth:n,sourceHeight:r};_.drawImage(u,0,0,m,h);let v=await new Promise(e=>{g.toBlob(t=>e(t??void 0),`image/webp`,.8)}),y=Math.min(RR/d,RR/f,1),b=Math.max(Math.round(d*y),1),x=Math.max(Math.round(f*y),1),S=document.createElement(`canvas`);S.width=b,S.height=x;let C=S.getContext(`2d`);return C?(C.drawImage(u,0,0,b,x),{poster:v,blurhash:JC(C.getImageData(0,0,b,x).data,b,x,4,3),sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o}):{poster:v,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function VR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await BR(e),c=i||FR,l=a||IR;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(FR/e,IR/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new gF({source:new fF(e),formats:uF}),d=new LL,f=new yR({format:new KL({fastStart:`in-memory`}),target:d});try{let i=await wR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:tR},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);PR(a);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await GR(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&(WR(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await GR(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var HR=[65536,0,0,0,65536,0,0,0,1073741824];function UR(e,t,n,r){let i=t;for(;i+8<=n;){let t=e.getUint32(i),a=String.fromCharCode(e.getUint8(i+4),e.getUint8(i+5),e.getUint8(i+6),e.getUint8(i+7));if(t===0&&(t=n-i),t<8||i+t>n)break;r(i,t,a),(a===`moov`||a===`trak`||a===`mdia`||a===`edts`)&&UR(e,i+8,i+t,r),i+=t}}function WR(e){let t=new DataView(e);UR(t,0,e.byteLength,(n,r,i)=>{if(i!==`tkhd`)return;let a=n+8,o=a+(t.getUint8(a)===0?40:52);if(o+36>e.byteLength)return;let s=!0;for(let e=0;e<9;e++)if(t.getInt32(o+e*4)!==HR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,HR[e])})}function GR(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=document.createElement(`video`);i.preload=`metadata`,i.onloadedmetadata=()=>{URL.revokeObjectURL(r),t({width:i.videoWidth,height:i.videoHeight})},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(`Failed to probe transcoded video dimensions`))},i.src=r})}var KR={isSupported:zR,processToFile:VR};function qR(){return document.querySelector(`jant-compose-dialog`)}function JR(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function YR(e=document){if(e===document){let e=document.querySelector(`[data-page='post'] article[data-post]:hover`);if(e)return e}return e.querySelector(`[data-post-current] article[data-post]`)||e.querySelector(`[data-post-view] article[data-post]`)||(e===document?document.querySelector(`article[data-post]:hover`):null)}function XR(e){let t=e.closest(`[data-post-view]`)?.dataset.postViewId;if(t)return{kind:`post-view`,id:t};let n=e.closest(`[data-timeline-item]`),r=n?.dataset.threadRootId??e.dataset.threadRootId??e.dataset.postId;if(n&&r)return{kind:`timeline-item`,id:r};let i=e.dataset.postId;return i?{kind:`post-card`,id:i}:null}function ZR(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function QR(e){await qR()?.openNew(e)}async function $R(e){let t=e.dataset.postId;if(!t)return;let n=qR();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,ZR(e),r,XR(e)??void 0)}function ez(e){b(e),S(e),C(e)}function tz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function nz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function rz(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function iz(e){try{let t=document.querySelector(`[data-timeline-item][data-thread-root-id="${e}"]`)?.querySelector(`[data-timeline-item-content]`);if(!t)return!1;let n=await rz(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,ez(t),!0):!1}catch{return!1}}async function az(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await rz(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,ez(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&ez(i),!0}catch{return!1}}async function oz(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await rz(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&ez(r),!0}catch{return!1}}async function sz(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?iz(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?oz(e.replyRefreshId):az(e.replyRefreshId)}var cz=new Map,lz=new Set,uz=new Map,dz=null;function fz(){if(!dz)return;let{clientIds:e,baseMsg:t}=dz;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=uz.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let i=e.length,a=Math.floor(n/i*100),o=Math.min(r+1,i);g(`compose-deferred`,i===1?`${t} ${a}%`:`${t} ${a}% ${o}/${i}`)}var pz=new Map;function mz(e){return new Promise(t=>{let n=setTimeout(()=>{a(),t(null)},3e3),r=URL.createObjectURL(e),i=document.createElement(`video`);i.muted=!0,i.playsInline=!0,i.preload=`auto`;function a(){clearTimeout(n),i.removeAttribute(`src`),i.load(),URL.revokeObjectURL(r)}i.onloadeddata=()=>{try{let e=i.videoWidth,n=i.videoHeight;if(!e||!n){a(),t(null);return}let r=Math.min(640/e,1),o=Math.round(e*r),s=Math.round(n*r),c=document.createElement(`canvas`);c.width=o,c.height=s;let l=c.getContext(`2d`);if(!l){a(),t(null);return}l.drawImage(i,0,0,o,s),c.toBlob(e=>{a(),t(e)},`image/webp`,.6)}catch{a(),t(null)}},i.onerror=()=>{a(),t(null)},i.src=r})}async function hz(e,t,n){let r=e.type,i=e.name;try{let o,s,c,l,u,d,f;if(r.startsWith(`video/`)){if(!KR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;mz(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let r=await KR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});o=r.file,e=null,s=r.width,c=r.height,l=r.durationSeconds,u=r.blurhash,f=r.poster,f&&n?.updateAttachmentPoster(t,f)}else if(r.startsWith(`audio/`)){if(!jR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{d=await ZC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),o=(await jR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file,e=null}else if(r.startsWith(`image/`)||/\.heic$/i.test(i)||/\.heif$/i.test(i)){let r=e;try{let{isHeic:a,heicTo:l}=await pk(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(r)){n?.updateAttachmentStatus(t,`processing`,null,null);let e=await l({blob:r,type:`image/jpeg`,quality:.92});r=new File([e],i.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,r)}let u=await oe.processToFile(r);o=u.file,s=u.width,c=u.height,e=null,r=null}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else o=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!r.startsWith(`video/`)){let e=await QC(o);s??=e.width,c??=e.height,u??=e.blurhash,d??=e.waveform,!f&&e.poster&&(f=e.poster,n?.updateAttachmentPoster(t,f))}let p,m;if(TS(r)===`text`)try{let e=await o.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}uz.set(t,0),fz();let h=await uw(o,{width:s,height:c,durationSeconds:l,blurhash:u,waveform:d,poster:f,summary:p,chars:m},e=>{n?.updateAttachmentProgress(t,e),uz.set(t,e),fz()});return uz.set(t,1),fz(),n?.updateAttachmentStatus(t,`done`,h.id,null),pz.set(t,h.id),h.id}catch(e){uz.delete(t),fz();let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||a(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;pz.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):lz.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=tz(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=hz(e,r,n).then(e=>lz.has(r)?(lz.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);cz.set(r,t),t.finally(()=>cz.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&$R(n)});function gz(e,t){let n=e.format===`quote`,r=e.format===`link`,i=!!e.editPostId,a=e=>e||void 0,o=e=>e||null;return{format:e.format,title:n?void 0:i?o(e.title):a(e.title),body:i?o(e.body):a(e.body),url:r?i?o(e.url):a(e.url):i?null:void 0,sourceName:n?i?o(e.quoteAuthor):a(e.quoteAuthor):void 0,sourceUrl:n?i?o(e.url):a(e.url):void 0,quoteText:n?i?o(e.quoteText):a(e.quoteText):i?null:void 0,slug:e.slug||void 0,status:e.status,publishedAt:e.status===`published`?e.publishedAt:void 0,visibility:e.visibility||void 0,rating:i?e.rating>0?e.rating:null:e.rating||void 0,collectionIds:e.collectionIds,attachments:t.length>0?t:void 0,replyToId:e.replyToId||void 0,quietReply:e.quietReply||void 0}}function _z(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function vz(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??pz.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!_z(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:qT(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=nz(t.target)??document.querySelector(`jant-compose-dialog`),i=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>e.body.includes(`"blob:`)):n.body.includes(`"blob:`),u=n.pendingAttachments.length>0||l,d=s?.published??`Published!`,p=s?.view??`View`;u&&(f(`compose-deferred`,c),n.pendingAttachments.length>0&&(dz={clientIds:n.pendingAttachments.map(e=>e.clientId),baseMsg:c},fz()));let m=(e,t=`success`)=>{if(dz){for(let e of dz.clientIds)uz.delete(e);dz=null}u?v(`compose-deferred`,e,t):a(e,t)},g=()=>{!i||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},_=()=>{!i||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||i)){if(te&&n.editPostId){if(typeof r.openEdit!=`function`)return;await r.openEdit(n.editPostId);return}if(n.replyToId){if(typeof r.openReply!=`function`)return;await r.openReply(n.replyToId,void 0,n.replyThreadRootId,n.replyRefreshKind&&n.replyRefreshId?{kind:n.replyRefreshKind,id:n.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:n.format});return}typeof r.openNew==`function`&&await r.openNew({restoreDraft:!0})}},x=async e=>{_(),await b(),m(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{h(e,`success`,t)},ee=()=>!i||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||o(`/`)),!0),te=!!n.editPostId,ne=!!(n.threadPosts&&n.threadPosts.length>=2),re=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>cz.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!pz.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let c=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=a[t];n&&r&&c.set(n,r)}if(ne&&n.threadPosts){let e=n.threadPosts,t=re?`draft`:n.status,a=(await Promise.all(e.map(async e=>{let n=e.body;if(n.includes(`"blob:`))try{let e=await vw(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>gz(e,vz(e,c))),o={posts:a};te&&n.editPostId&&(o.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(o)});if(!l.ok){if(n.status===`published`&&!re){let e={posts:a.map(e=>({...e,status:`draft`}))};if((await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)})).ok){re=`server`,y();let e=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),m(e);return}}await x(w(await fe(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),m(e);return}let u=await fe(l),f=w(u,`status`),h=w(u,`permalink`),_=w(u,`toast`);f===`published`?(y(),i?(await S(),g(),m(d)):(C(d,h?{label:p,href:h}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),m(_??`Draft saved.`),yz(r,`draft`));return}let u=vz(n,c);if(l)try{let e=await vw(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let f=te?`/api/posts/${n.editPostId}`:`/compose`,h=te?`PUT`:`POST`,_=gz({...n,status:re?`draft`:n.status},u),v=await fetch(f,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!v.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(f,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await fe(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),m(n);let r=w(e,`toast`);r&&m(r);return}}await x(w(await fe(v),`error`)??`Something went wrong`);return}if(te){y();let e=await fe(v),t=n.editPostId??``,r=w(e,`slug`),a=r?o(`/${r}`):null;if(i)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await oz(t)?m(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(a&&a!==globalThis.location.pathname){C(`Post updated.`),globalThis.location.assign(a);return}await oz(t)?m(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await iz(e):await az(t))?m(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),m(e);return}let b=await fe(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),i)await S(),g(),m(d);else if(n.replyToId){if(await S(),!await sz(n)){C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}m(d)}else C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),m(oe??`Draft saved.`),yz(r,`draft`)}catch{await x(`Something went wrong`)}});function yz(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var bz=`.compose-prompt`,xz=`.compose-prompt-trigger`,Sz=`jant.composeOpenShortcutDiscovery`,Cz=`/api/settings/discovery/compose-open-shortcut`,wz=350,Tz=1800,Ez=3,Dz=`compose-prompt-discovery-visible`,Oz=!1,kz=null,Az=null,jz=null;function Mz(){try{return globalThis.localStorage!==void 0}catch{return!1}}function Nz(){if(!Mz())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(Sz);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(Sz),{shownCount:0,completed:!1}}}function Pz(e){if(Mz())try{globalThis.localStorage.setItem(Sz,JSON.stringify(e))}catch{}}function Fz(){kz!==null&&(clearTimeout(kz),kz=null)}function Iz(){Az!==null&&(clearTimeout(Az),Az=null)}function Lz(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function Rz(e){return Nz().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function zz(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Dz)),document.querySelectorAll(bz).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Dz)})}function Bz(){let e=Nz();e.completed||Oz||e.shownCount>=Ez||(Oz=!0,Pz({...e,shownCount:e.shownCount+1}))}function Vz(e){return!Lz()||Rz(e)?!1:Nz().shownCount<Ez||Oz}function Hz(e){Fz(),Iz(),e?e.classList.remove(Dz):jz&&jz.classList.remove(Dz),(!e||e===jz)&&(jz=null)}function Uz(e){Vz(e)&&(Hz(jz),jz=e,e.classList.add(Dz),Bz(),Az=setTimeout(()=>{Hz(e)},Tz))}function Wz(e){Vz(e)&&(e.classList.contains(Dz)||(Fz(),kz=setTimeout(()=>{Uz(e)},wz)))}function Gz(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(xz);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{Wz(e)}),t.addEventListener(`pointerleave`,()=>{Hz(e)}),t.addEventListener(`focusin`,()=>{Wz(e)}),t.addEventListener(`focusout`,()=>{Hz(e)}))}function Kz(e=document){e.querySelectorAll(bz).forEach(e=>Gz(e))}function qz(){let e=Nz();e.completed||Pz({shownCount:Math.max(e.shownCount,Ez),completed:!0}),zz(jz),Hz(jz),typeof globalThis.fetch==`function`&&globalThis.fetch(Cz,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{Kz()}):Kz(),document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{});var Jz=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function Yz(e){return e instanceof globalThis.Element&&e.closest(Jz)!==null}function Xz(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!qR()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return Yz(e.target)||t!==e.target&&Yz(t)}async function Zz(e,t,n){try{if(!(await fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:t})})).ok)throw Error();t?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`),a(t?`Added to Featured.`:`Removed from Featured.`)}catch{a(`Could not update post. Try again.`,`error`)}}document.addEventListener(`keydown`,e=>{let t=e.key.toLowerCase();if(t!==`n`&&t!==`l`&&t!==`q`&&t!==`r`&&t!==`e`&&t!==`c`&&t!==`f`||Xz(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),qz();let n=JR(),r=t===`l`?`link`:t===`q`?`quote`:void 0;QR({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=YR();if(n){if(t===`r`){e.preventDefault(),$R(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=qR();r&&r.openEdit(t);return}if(t===`c`){e.preventDefault();let t=document.querySelector(`jant-post-menu`);t&&t.openCollectionsForPost(n);return}if(t===`f`){let t=n.dataset.postId;if(!t)return;e.preventDefault(),Zz(t,!n.hasAttribute(`data-post-featured`),n);return}}});var Qz=[`en`,`zh-Hans`,`zh-Hant`];function $z(e){return typeof e==`string`&&Qz.includes(e)}function eB(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if($z(n.baseName))return n.baseName;if(n.language===`zh`){let e=n.region;return n.script===`Hant`||e===`TW`||e===`HK`||e===`MO`?`zh-Hant`:`zh-Hans`}return`en`}var tB={en:1,"zh-Hans":1,"zh-Hant":1},nB=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX`.split(`.`),rB=null;function iB(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:aB(e)}}function aB(e){let t=eB(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return tB[t]}function oB(){return rB||(rB=nB.map(iB),rB)}function sB(e){let t=e.trim();return oB().find(e=>e.tag===t)||iB(t)}var cB=class extends _{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},dashboardLanguages:{type:Array,attribute:`dashboard-languages`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},archiveFeedUrl:{type:String,attribute:`archive-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_dashboardLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.dashboardLanguages=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/latest/feed`,this.featuredFeedUrl=`/featured/feed`,this.archiveFeedUrl=`/archive/feed`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._dashboardLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,dashboardLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._dashboardLanguage=e.dashboardLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,dashboardLanguage:e.dashboardLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,dashboardLanguage:this._dashboardLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=XT({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=YT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`3rem`)}_initFooterEditor(){let e=this.querySelector(`[data-settings-footer-editor]`);if(!e||this._footerEditor)return;this._footerEditor=XT({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=YT(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._dashboardLanguage!==this._origLocale.dashboardLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,dashboardLanguage:this._dashboardLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=oB(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.isComposing||e.keyCode===229||e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=sB(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
2196
+ `+this._getInvalidityExplanation().join(``));if(this._executed)throw Error(`Conversion cannot be executed twice.`);if(this._executed=!0,this.onProgress){let e=this.utilizedTracks.map(e=>e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(let e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new PR;await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}async cancel(){if(!(this.output.state===`finalizing`||this.output.state===`finalized`)){if(this._canceled){console.warn(`Conversion already canceled.`);return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=Ak(e.rotation+(t.rotate??0)),a=i,o=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),[s,c]=i%180==0?[e.squarePixelWidth,e.squarePixelHeight]:[e.squarePixelHeight,e.squarePixelWidth],l=t.crop;l&&WM(l,s,c);let[u,d]=l?[l.width,l.height]:[s,c],f=u,p=d,m=f/p,h=e=>Math.ceil(e/2)*2;t.width!==void 0&&t.height===void 0?(f=h(t.width),p=h(Math.round(f/m))):t.width===void 0&&t.height!==void 0?(p=h(t.height),f=h(Math.round(p*m))):t.width!==void 0&&t.height!==void 0&&(f=h(t.width),p=h(t.height));let g=await e.getFirstTimestamp(),_=this.output.format.getSupportedVideoCodecs(),v=!!t.forceTranscode||g<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!_.includes(n)||t.codec&&t.codec!==n||f!==u||p!==d||i!==0&&!o||!!l,y=t.alpha??`discard`;if(v){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}t.codec&&(_=_.filter(e=>e===t.codec));let n=t.bitrate??uR,s=await mR(_,{width:t.process&&t.processedWidth?t.processedWidth:f,height:t.process&&t.processedHeight?t.processedHeight:p,bitrate:n});if(!s){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}let c={codec:s,bitrate:n,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??`passThrough`,alpha:y,hardwareAcceleration:t.hardwareAcceleration},m=new bR(c);r=m;let h=f!==u||p!==d||i!==0&&(!o||t.process!==void 0)||!!l||e.squarePixelWidth!==e.codedWidth||e.squarePixelHeight!==e.codedHeight;if(!h){let t=new OR({format:new tR,target:new qL}),n=new bR(c);t.addVideoTrack(n),await t.start();let r=await new fN(e).getSample(g);if(r)try{await n.add(r),r.close(),await t.finalize()}catch(e){console.info(`Error when probing encoder support. Falling back to rerender path.`,e),h=!0,t.cancel()}else await t.cancel()}h?this._trackPromises.push((async()=>{await this._started;let n=new pN(e,{width:f,height:p,fit:t.fit??`fill`,rotation:i,crop:t.crop,poolSize:1,alpha:y===`keep`}).canvases(this._startTimestamp,this._endTimestamp),r=t.frameRate;a=0;let o=null,s=null,c=null,l=async n=>{U(o),U(r!==void 0);let i=Math.round((n-s)*r);for(let n=1;n<i;n++){let i=new VM(o,{timestamp:s+n/r,duration:1/r});await this._registerVideoSample(e,t,m,i),i.close()}};for await(let{canvas:i,timestamp:a,duration:u}of n){if(this._canceled)return;let n=Math.max(a-this._startTimestamp,0);if(c=n+u,r!==void 0){let e=Math.floor(n*r)/r;if(o!==null)if(e<=s){o=i,s=e;continue}else await l(e);n=e}let d=new VM(i,{timestamp:n,duration:r===void 0?u:1/r});await this._registerVideoSample(e,t,m,d),d.close(),r!==void 0&&(o=i,s=n)}o&&(U(c!==null),U(r!==void 0),await l(Math.floor(c*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;let n=new fN(e),r=t.frameRate,i=null,a=null,o=null,s=async n=>{U(i),U(r!==void 0);let o=Math.round((n-a)*r);for(let n=1;n<o;n++)i.setTimestamp(a+n/r),i.setDuration(1/r),await this._registerVideoSample(e,t,m,i);i.close()};for await(let c of n.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){c.close(),i?.close();return}let n=Math.max(c.timestamp-this._startTimestamp,0);if(o=n+c.duration,r!==void 0){let e=Math.floor(n*r)/r;if(i!==null)if(e<=a){i.close(),i=c,a=e;continue}else await s(e);n=e,c.setDuration(1/r)}c.setTimestamp(n),await this._registerVideoSample(e,t,m,c),r===void 0?c.close():(i=c,a=n)}i&&(U(o!==null),U(r!==void 0),await s(Math.floor(o*r)/r)),m.close(),this._synchronizer.closeTrack(e.id)})())}else{let t=new _R(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new oN(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i,{verifyKeyPackets:!0})){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp,sideData:y===`discard`?{}:a.sideData});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:gA(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:a}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),i=e.map(e=>e instanceof VM?e:typeof VideoFrame<`u`&&e instanceof VideoFrame?new VM(e):new VM(e,{timestamp:r.timestamp,duration:r.duration}))}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}async _processAudioTrack(e,t){let n=e.codec;if(!n){this.discardedTracks.push({track:e,reason:`unknown_source_codec`});return}let r,i=e.numberOfChannels,a=e.sampleRate,o=await e.getFirstTimestamp(),s=t.numberOfChannels??i,c=t.sampleRate??a,l=s!==i||c!==a||o<this._startTimestamp||o>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,u=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!l&&u.includes(n)&&(!t.codec||t.codec===n)&&!t.process){let t=new SR(n);r=t,this._trackPromises.push((async()=>{await this._started;let n=new oN(e),r={decoderConfig:await e.getDecoderConfig()??void 0},i=Number.isFinite(this._endTimestamp)?await n.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(let a of n.packets(void 0,i)){if(this._canceled)return;let n=a.clone({timestamp:a.timestamp-this._startTimestamp});U(n.timestamp>=0),this._reportProgress(e.id,n.timestamp),await t.add(n,r),this._synchronizer.shouldWait(e.id,n.timestamp)&&await this._synchronizer.wait(n.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:`undecodable_source_codec`});return}let n=null;t.codec&&(u=u.filter(e=>e===t.codec));let i=t.bitrate??uR,a=await pR(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:s,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:i});if(!a.some(e=>JA.includes(e))&&u.some(e=>JA.includes(e))&&(s!==jR||c!==MR)){let e=(await pR(u,{numberOfChannels:jR,sampleRate:MR,bitrate:i})).find(e=>JA.includes(e));e&&(l=!0,n=e,s=jR,c=MR)}else n=a[0]??null;if(n===null){this.discardedTracks.push({track:e,reason:`no_encodable_target_codec`});return}if(l)r=this._resampleAudio(e,t,n,s,c,i);else{let a=new wR({codec:n,bitrate:i});r=a,this._trackPromises.push((async()=>{await this._started;let n=new gN(e);for await(let r of n.samples(void 0,this._endTimestamp)){if(this._canceled){r.close();return}r.setTimestamp(r.timestamp-this._startTimestamp),await this._registerAudioSample(e,t,a,r),r.close()}a.close(),this._synchronizer.closeTrack(e.id)})())}}this.output.addAudioTrack(r,{languageCode:gA(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,n,r){if(this._canceled)return;this._reportProgress(e.id,r.timestamp);let i;if(!t.process)i=[r];else{let e=t.process(r);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=e===null?[]:[e]),!e.every(e=>e instanceof XM))throw TypeError(`The audio process function must return an AudioSample, null, or an array of AudioSamples.`);i=e}for(let t of i){if(this._canceled)break;await n.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(let e of i)e!==r&&e.close()}_resampleAudio(e,t,n,r,i,a){let o=new wR({codec:n,bitrate:a});return this._trackPromises.push((async()=>{await this._started;let n=new LR({targetNumberOfChannels:r,targetSampleRate:i,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async n=>{await this._registerAudioSample(e,t,o,n),n.close()}}),a=new gN(e).samples(this._startTimestamp,this._endTimestamp);for await(let e of a){if(this._canceled){e.close();return}await n.add(e),e.close()}await n.finalize(),o.close(),this._synchronizer.closeTrack(e.id)})()),o}_reportProgress(e,t){if(!this._computeProgress)return;U(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let n=uA(Math.min(...this._maxTimestamps.values())/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n))}},PR=class extends Error{constructor(e=`Conversion has been canceled.`){super(e),this.name=`ConversionCanceledError`}},FR=5,IR=class{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let n=this.resolvers[t];n.timestamp-e<FR&&(n.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){return this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0)),t-this.computeMinAndMaybeResolve()>=FR}wait(e){let{promise:t,resolve:n}=$k();return this.resolvers.push({timestamp:e,resolve:n}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}},LR=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){U(this.sourceNumberOfChannels!==null);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(t,n)=>t[n*e]:e===1&&t===4?this.channelMixer=(t,n,r)=>t[n*e]*+(r<2):e===1&&t===6?this.channelMixer=(t,n,r)=>t[n*e]*+(r===2):e===2&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .5*(t[r]+t[r+1])}:e===2&&t===4||e===2&&t===6?this.channelMixer=(t,n,r)=>t[n*e+r]*+(r<2):e===4&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:e===4&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return .5*(t[i+r]+t[i+r+2])}:e===4&&t===6?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]:r===2||r===3?0:t[i+r-2]}:e===6&&t===1?this.channelMixer=(t,n)=>{let r=n*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:e===6&&t===2?this.channelMixer=(t,n,r)=>{let i=n*e;return t[i+r]+Math.SQRT1_2*(t[i+2]+t[i+r+4])}:e===6&&t===4?this.channelMixer=(t,n,r)=>{let i=n*e;return r<2?t[i+r]+Math.SQRT1_2*t[i+2]:t[i+r+2]}:this.channelMixer=(t,n,r)=>r<e?t[n*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let n=e.allocationSize({planeIndex:0,format:`f32`}),r=new Float32Array(this.tempSourceBuffer.buffer,0,n/4);e.copyTo(r,{planeIndex:0,format:`f32`});let i=e.timestamp-this.startTime,a=e.numberOfFrames/this.sourceSampleRate,o=Math.min(i+a,this.endTime-this.startTime),s=Math.floor(i*this.targetSampleRate),c=Math.ceil(o*this.targetSampleRate);for(let t=s;t<c;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let n=t-this.bufferStartFrame;U(n<this.bufferSizeInFrames);let a=(t/this.targetSampleRate-i)*this.sourceSampleRate,o=Math.floor(a),s=Math.ceil(a),c=a-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,a=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(r,o,t)),s>=0&&s<e.numberOfFrames&&(a=this.channelMixer(r,s,t));let l=i+c*(a-i),u=n*this.targetNumberOfChannels+t;this.outputBuffer[u]+=l}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,n)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let n=this.bufferStartFrame/this.targetSampleRate,r=new XM({format:`f32`,sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:n,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}};function RR(){return typeof AudioEncoder<`u`}async function zR(e,t){let n=new TF({source:new xF(e),formats:yF}),r=new KL,i=new OR({format:new tR({fastStart:`in-memory`}),target:r});try{let a=await NR.init({input:n,output:i,video:{discard:!0},audio:{codec:`aac`,bitrate:uR}});t&&(a.onProgress=t),await a.execute();let o=r.buffer;if(!o)throw Error(`Audio processing produced no output`);let s=e.name.replace(/\.[^.]+$/,``);return{file:new File([o],`${s}.m4a`,{type:`audio/mp4`})}}finally{n.dispose()}}var BR={isSupported:RR,processToFile:zR},VR=new Set([`moov`,`trak`]);function HR(e){return 12+(e===1?32:20)+8+2}function UR(e){let t=new DataView(e),n=(e,r)=>{let i=e;for(;i+8<=r;){let e=t.getUint32(i),a=String.fromCharCode(t.getUint8(i+4),t.getUint8(i+5),t.getUint8(i+6),t.getUint8(i+7));if(e===0&&(e=r-i),e<8||i+e>r)break;if(a===`tkhd`){let n=t.getUint8(i+8),r=i+HR(n);r+2<=i+e&&t.getUint16(r)!==0&&t.setUint16(r,0)}else VR.has(a)&&n(i+8,i+e);i+=e}};n(0,e.byteLength)}var WR=1920,GR=1080,KR=640,qR=32;function JR(){return typeof VideoEncoder<`u`}async function YR(e){let t=new TF({source:new xF(e),formats:yF});try{let e=await t.getPrimaryVideoTrack();if(!e)return{};let n=e.displayWidth,r=e.displayHeight,i=e.rotation,a=await t.computeDuration(),o=l(a),s=Math.min(a*.1,1),c=await new pN(e).getCanvas(s);if(!c)return{sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o};let u=c.canvas,d=u.width,f=u.height,p=Math.min(KR/d,1),m=Math.round(d*p),h=Math.round(f*p),g=document.createElement(`canvas`);g.width=m,g.height=h;let _=g.getContext(`2d`);if(!_)return{sourceWidth:n,sourceHeight:r};_.drawImage(u,0,0,m,h);let v=await new Promise(e=>{g.toBlob(t=>e(t??void 0),`image/webp`,.8)}),y=Math.min(qR/d,qR/f,1),b=Math.max(Math.round(d*y),1),x=Math.max(Math.round(f*y),1),S=document.createElement(`canvas`);S.width=b,S.height=x;let C=S.getContext(`2d`);return C?(C.drawImage(u,0,0,b,x),{poster:v,blurhash:JC(C.getImageData(0,0,b,x).data,b,x,4,3),sourceWidth:n,sourceHeight:r,rotation:i,durationSeconds:o}):{poster:v,sourceWidth:n,sourceHeight:r}}catch{return{}}finally{t.dispose()}}async function XR(e,t){let{poster:n,blurhash:r,sourceWidth:i,sourceHeight:a,rotation:o,durationSeconds:s}=await YR(e),c=i||WR,l=a||GR;if(i&&a){let e=Math.max(i,a),t=Math.min(i,a),n=Math.min(WR/e,GR/t,1);c=Math.round(i*n),l=Math.round(a*n)}c+=c%2,l+=l%2;let u=new TF({source:new xF(e),formats:yF}),d=new KL,f=new OR({format:new tR({fastStart:`in-memory`}),target:d});try{let i=await NR.init({input:u,output:f,video:{codec:`avc`,width:c,height:l,fit:`contain`,bitrate:uR},audio:{codec:`aac`}});t&&(i.onProgress=t),await i.execute();let a=d.buffer;if(!a)throw Error(`Video processing produced no output`);UR(a);let p=e.name.replace(/\.[^.]+$/,``),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ez(m),g=Math.abs(h.width-c)<=2&&Math.abs(h.height-l)<=2;return o&&!g&&($R(a),m=new File([a],`${p}.mp4`,{type:`video/mp4`}),h=await ez(m)),{file:m,width:h.width,height:h.height,durationSeconds:s,poster:n,blurhash:r}}finally{u.dispose()}}var ZR=[65536,0,0,0,65536,0,0,0,1073741824];function QR(e,t,n,r){let i=t;for(;i+8<=n;){let t=e.getUint32(i),a=String.fromCharCode(e.getUint8(i+4),e.getUint8(i+5),e.getUint8(i+6),e.getUint8(i+7));if(t===0&&(t=n-i),t<8||i+t>n)break;r(i,t,a),(a===`moov`||a===`trak`||a===`mdia`||a===`edts`)&&QR(e,i+8,i+t,r),i+=t}}function $R(e){let t=new DataView(e);QR(t,0,e.byteLength,(n,r,i)=>{if(i!==`tkhd`)return;let a=n+8,o=a+(t.getUint8(a)===0?40:52);if(o+36>e.byteLength)return;let s=!0;for(let e=0;e<9;e++)if(t.getInt32(o+e*4)!==ZR[e]){s=!1;break}if(!s)for(let e=0;e<9;e++)t.setInt32(o+e*4,ZR[e])})}function ez(e){return new Promise((t,n)=>{let r=URL.createObjectURL(e),i=document.createElement(`video`);i.preload=`metadata`,i.onloadedmetadata=()=>{URL.revokeObjectURL(r),t({width:i.videoWidth,height:i.videoHeight})},i.onerror=()=>{URL.revokeObjectURL(r),n(Error(`Failed to probe transcoded video dimensions`))},i.src=r})}var tz={isSupported:JR,processToFile:XR};function nz(){return document.querySelector(`jant-compose-dialog`)}function rz(){return document.querySelector(`[data-page='collection'][data-collection-id]`)?.dataset.collectionId||void 0}function iz(e=document){if(e===document){let e=document.querySelector(`[data-page='post'] article[data-post]:hover`);if(e)return e}return e.querySelector(`[data-post-current] article[data-post]`)||e.querySelector(`[data-post-view] article[data-post]`)||(e===document?document.querySelector(`article[data-post]:hover`):null)}function az(e){let t=e.closest(`[data-post-view]`)?.dataset.postViewId;if(t)return{kind:`post-view`,id:t};let n=e.closest(`[data-timeline-item]`),r=n?.dataset.threadRootId??e.dataset.threadRootId??e.dataset.postId;if(n&&r)return{kind:`timeline-item`,id:r};let i=e.dataset.postId;return i?{kind:`post-card`,id:i}:null}function oz(e){let t=e.cloneNode(!0);t.querySelector(`[data-post-meta]`)?.remove(),t.querySelector(`.post-status-badges`)?.remove();let n=e.querySelector(`time.dt-published`);return{contentHtml:t.innerHTML,dateText:n?.textContent?.trim()??``}}async function sz(e){await nz()?.openNew(e)}async function cz(e){let t=e.dataset.postId;if(!t)return;let n=nz();if(!n)return;let r=e.dataset.threadRootId??t;await n.openReply(t,oz(e),r,az(e)??void 0)}function lz(e){b(e),S(e),C(e)}function uz(e){try{return Sw(JSON.parse(e))}catch{return!1}}function dz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-editor`):null}function fz(e){return e instanceof globalThis.Element?e.closest(`jant-compose-dialog`):null}async function pz(e){let t=await fetch(e,{headers:{Accept:`text/html`}});return t.ok?t.text():null}async function mz(e){try{let t=document.querySelector(`[data-timeline-item][data-thread-root-id="${e}"]`)?.querySelector(`[data-timeline-item-content]`);if(!t)return!1;let n=await pz(`/_/timeline-item/${encodeURIComponent(e)}`);return n?(t.innerHTML=n,lz(t),!0):!1}catch{return!1}}async function hz(e){try{let t=document.querySelector(`article[data-post-id="${e}"]`)?.closest(`[data-timeline-item]`),n=await pz(`/_/post-card/${encodeURIComponent(e)}`);if(!n)return!1;if(t){let e=t.querySelector(`[data-timeline-item-content]`);return e?(e.innerHTML=n,lz(e),!0):!1}let r=document.querySelector(`article[data-post-id="${e}"]`);if(!r)return!1;r.outerHTML=n;let i=document.querySelector(`article[data-post-id="${e}"]`);return i&&lz(i),!0}catch{return!1}}async function gz(e){try{let t=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);if(!t)return!1;let n=await pz(`/_/post-view/${encodeURIComponent(e)}`);if(!n)return!1;t.outerHTML=n;let r=document.querySelector(`[data-post-view][data-post-view-id="${e}"]`);return r&&lz(r),!0}catch{return!1}}async function _z(e){return!e.replyRefreshKind||!e.replyRefreshId?!1:e.replyRefreshKind===`timeline-item`?mz(e.replyThreadRootId??e.replyRefreshId):e.replyRefreshKind===`post-view`?gz(e.replyRefreshId):hz(e.replyRefreshId)}var vz=new Map,yz=new Set,bz=new Map,xz=null;function Sz(){if(!xz)return;let{clientIds:e,baseMsg:t}=xz;if(e.length===0)return;let n=0,r=0;for(let t of e){let e=bz.get(t)??0;n+=Math.min(1,Math.max(0,e)),e>=1&&(r+=1)}let i=e.length,a=Math.floor(n/i*100),o=Math.min(r+1,i);g(`compose-deferred`,i===1?`${t} ${a}%`:`${t} ${a}% ${o}/${i}`)}var Cz=new Map;function wz(e){return new Promise(t=>{let n=setTimeout(()=>{a(),t(null)},3e3),r=URL.createObjectURL(e),i=document.createElement(`video`);i.muted=!0,i.playsInline=!0,i.preload=`auto`;function a(){clearTimeout(n),i.removeAttribute(`src`),i.load(),URL.revokeObjectURL(r)}i.onloadeddata=()=>{try{let e=i.videoWidth,n=i.videoHeight;if(!e||!n){a(),t(null);return}let r=Math.min(640/e,1),o=Math.round(e*r),s=Math.round(n*r),c=document.createElement(`canvas`);c.width=o,c.height=s;let l=c.getContext(`2d`);if(!l){a(),t(null);return}l.drawImage(i,0,0,o,s),c.toBlob(e=>{a(),t(e)},`image/webp`,.6)}catch{a(),t(null)}},i.onerror=()=>{a(),t(null)},i.src=r})}async function Tz(e,t,n){let r=e.type,i=e.name;try{let o,s,c,l,u,d,f;if(r.startsWith(`video/`)){if(!tz.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support video processing. Use Chrome or Edge to upload videos.`),null;wz(e).then(e=>{e&&n?.updateAttachmentPoster(t,e)}),n?.updateAttachmentStatus(t,`processing`,null,null);let r=await tz.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)});o=r.file,e=null,s=r.width,c=r.height,l=r.durationSeconds,u=r.blurhash,f=r.poster,f&&n?.updateAttachmentPoster(t,f)}else if(r.startsWith(`audio/`)){if(!BR.isSupported())return n?.updateAttachmentStatus(t,`error`,null,`Your browser doesn't support audio processing. Use Chrome or Edge to upload audio.`),null;try{d=await ZC(e)}catch{}n?.updateAttachmentStatus(t,`processing`,null,null),o=(await BR.processToFile(e,e=>{n?.updateAttachmentProgress(t,e)})).file,e=null}else if(r.startsWith(`image/`)||/\.heic$/i.test(i)||/\.heif$/i.test(i)){let r=e;try{let{isHeic:a,heicTo:l}=await Sk(async()=>{let{isHeic:e,heicTo:t}=await import(`./chunks/heic-to-DUUaO23q.js`);return{isHeic:e,heicTo:t}},[]);if(await a(r)){n?.updateAttachmentStatus(t,`processing`,null,null);let e=await l({blob:r,type:`image/jpeg`,quality:.92});r=new File([e],i.replace(/\.heic$/i,`.jpg`),{type:`image/jpeg`}),n?.updateAttachmentPreview(t,r)}let u=await oe.processToFile(r);o=u.file,s=u.width,c=u.height,e=null,r=null}catch{return n?.removeAttachment(t),a(`Image format not supported.`,`error`),null}}else o=e;if(n?.updateAttachmentStatus(t,`uploading`,null,null),!r.startsWith(`video/`)){let e=await QC(o);s??=e.width,c??=e.height,u??=e.blurhash,d??=e.waveform,!f&&e.poster&&(f=e.poster,n?.updateAttachmentPoster(t,f))}let p,m;if(TS(r)===`text`)try{let e=await o.text(),t=e.replace(/\s+/g,` `).trim();m=e.length,p=t.length<=100?t:t.slice(0,100)+`…`}catch{}bz.set(t,0),Sz();let h=await uw(o,{width:s,height:c,durationSeconds:l,blurhash:u,waveform:d,poster:f,summary:p,chars:m},e=>{n?.updateAttachmentProgress(t,e),bz.set(t,e),Sz()});return bz.set(t,1),Sz(),n?.updateAttachmentStatus(t,`done`,h.id,null),Cz.set(t,h.id),h.id}catch(e){bz.delete(t),Sz();let r=e instanceof Error?e.message:`Upload failed`;return n?.updateAttachmentStatus(t,`error`,null,r),n||a(r,`error`),null}}document.addEventListener(`jant:attachment-removed`,e=>{let{clientId:t,mediaId:n}=e.detail;Cz.delete(t),n?fetch(`/api/upload/${n}`,{method:`DELETE`}).catch(()=>{}):yz.add(t)}),document.addEventListener(`jant:files-selected`,e=>{let t=e,n=dz(t.target);for(let{file:e,clientId:r}of t.detail.files){let t=Tz(e,r,n).then(e=>yz.has(r)?(yz.delete(r),e&&fetch(`/api/upload/${e}`,{method:`DELETE`}).catch(()=>{}),null):e);vz.set(r,t),t.finally(()=>vz.delete(r))}}),document.addEventListener(`click`,e=>{let t=e.target.closest(`[data-reply-trigger]`);if(!t)return;let n=t.closest(`article[data-post]`);n&&cz(n)});function Ez(e,t){let n=e.format===`quote`,r=e.format===`link`,i=!!e.editPostId,a=e=>e||void 0,o=e=>e||null;return{format:e.format,title:n?void 0:i?o(e.title):a(e.title),body:i?o(e.body):a(e.body),url:r?i?o(e.url):a(e.url):i?null:void 0,sourceName:n?i?o(e.quoteAuthor):a(e.quoteAuthor):void 0,sourceUrl:n?i?o(e.url):a(e.url):void 0,quoteText:n?i?o(e.quoteText):a(e.quoteText):i?null:void 0,slug:e.slug||void 0,status:e.status,publishedAt:e.status===`published`?e.publishedAt:void 0,visibility:e.visibility||void 0,rating:i?e.rating>0?e.rating:null:e.rating||void 0,collectionIds:e.collectionIds,attachments:t.length>0?t:void 0,replyToId:e.replyToId||void 0,quietReply:e.quietReply||void 0}}function Dz(e){return JSON.stringify(e.bodyJson)!==JSON.stringify(e.originalBodyJson??null)}function Oz(e,t){let n=[];for(let r of e.attachments){if(r.type===`media`){let e=r.mediaId??t.get(r.clientId)??Cz.get(r.clientId);if(!e)continue;n.push({type:`media`,mediaId:e,alt:r.alt});continue}if(r.mediaId&&!Dz(r)){n.push({type:`media`,mediaId:r.mediaId});continue}n.push({type:`text`,contentFormat:`markdown`,content:nE(JSON.stringify(r.bodyJson)),summary:r.summary})}return n}document.addEventListener(`jant:compose-submit-deferred`,async e=>{let t=e,n=t.detail,r=fz(t.target)??document.querySelector(`jant-compose-dialog`),i=!!r?.pageMode,s=r?.labels,c=s?.uploading??`Uploading...`,l=n.threadPosts?n.threadPosts.some(e=>uz(e.body)):uz(n.body),u=n.pendingAttachments.length>0||l,d=s?.published??`Published!`,p=s?.view??`View`;u&&(f(`compose-deferred`,c),n.pendingAttachments.length>0&&(xz={clientIds:n.pendingAttachments.map(e=>e.clientId),baseMsg:c},Sz()));let m=(e,t=`success`)=>{if(xz){for(let e of xz.clientIds)bz.delete(e);xz=null}u?v(`compose-deferred`,e,t):a(e,t)},g=()=>{!i||!r||(r.reset(),r.updateComplete.then(()=>{r.querySelector(`jant-compose-editor`)?.focusInput()}))},_=()=>{!i||!r||(r.loading=!1)},y=()=>{if(te){n.editPostId&&r?.clearEditDraftFromStorage?.(n.editPostId);return}r?.clearLocalDraftFromStorage?.()},b=async()=>{if(!(!r||i)){if(te&&n.editPostId){if(typeof r.openEdit!=`function`)return;await r.openEdit(n.editPostId);return}if(n.replyToId){if(typeof r.openReply!=`function`)return;await r.openReply(n.replyToId,void 0,n.replyThreadRootId,n.replyRefreshKind&&n.replyRefreshId?{kind:n.replyRefreshKind,id:n.replyRefreshId}:void 0,{restoreDraft:!0,initialFormat:n.format});return}typeof r.openNew==`function`&&await r.openNew({restoreDraft:!0})}},x=async e=>{_(),await b(),m(e,`error`)},S=async()=>{await r?.refreshCollections()},C=(e,t)=>{h(e,`success`,t)},ee=()=>!i||!r||!r.consumePageLeaveRequest()?!1:(r.preparePageLeave(),globalThis.location.assign(r.closeHref||o(`/`)),!0),te=!!n.editPostId,ne=!!(n.threadPosts&&n.threadPosts.length>=2),re=null;try{let e=n.pendingAttachments.map(e=>e.clientId),t=e.map(e=>vz.get(e)??Promise.resolve(null)),a=await Promise.all(t);if(a.filter((t,n)=>t===null&&!Cz.has(e[n]??``)).length>0)if(n.status===`published`&&!te)re=`upload`;else{await x(`Upload failed. Post not created.`);return}let c=new Map;for(let t=0;t<e.length;t++){let n=e[t],r=a[t];n&&r&&c.set(n,r)}if(ne&&n.threadPosts){let e=n.threadPosts,t=re?`draft`:n.status,a=(await Promise.all(e.map(async e=>{let n=e.body;if(uz(n))try{let e=await xw(JSON.parse(n));n=e?JSON.stringify(e):``}catch{}return{...e,body:n,status:t}}))).map(e=>Ez(e,Oz(e,c))),o={posts:a};te&&n.editPostId&&(o.replaceThreadId=n.editPostId);let l=await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(o)});if(!l.ok){if(n.status===`published`&&!re){let e={posts:a.map(e=>({...e,status:`draft`}))};if((await fetch(`/compose/thread`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)})).ok){re=`server`,y();let e=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),m(e);return}}await x(w(await fe(l),`error`)??`Something went wrong`);return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),m(e);return}let u=await fe(l),f=w(u,`status`),h=w(u,`permalink`),_=w(u,`toast`);f===`published`?(y(),i?(await S(),g(),m(d)):(C(d,h?{label:p,href:h}:void 0),globalThis.location.reload())):(y(),await S(),ee()||g(),m(_??`Draft saved.`),kz(r,`draft`));return}let u=Oz(n,c);if(l)try{let e=await xw(JSON.parse(n.body));n.body=e?JSON.stringify(e):``}catch{}let f=te?`/api/posts/${n.editPostId}`:`/compose`,h=te?`PUT`:`POST`,_=Ez({...n,status:re?`draft`:n.status},u),v=await fetch(f,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(_)});if(!v.ok){if(n.status===`published`&&!te&&!re){let e={..._,status:`draft`},t=await fetch(f,{method:h,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e)});if(t.ok){re=`server`,y();let e=await fe(t),n=s?.publishFailedDraft??`Couldn't publish. Saved as draft.`;await S(),ee()||g(),m(n);let r=w(e,`toast`);r&&m(r);return}}await x(w(await fe(v),`error`)??`Something went wrong`);return}if(te){y();let e=await fe(v),t=n.editPostId??``,r=w(e,`slug`),a=r?o(`/${r}`):null;if(i)a&&a!==globalThis.location.pathname?(C(`Post updated.`),globalThis.location.assign(a)):t&&await gz(t)?m(`Post updated.`):(C(`Post updated.`),globalThis.location.assign(globalThis.location.pathname));else if(t)if(document.querySelector(`[data-post-view][data-post-view-id="${t}"]`)){if(a&&a!==globalThis.location.pathname){C(`Post updated.`),globalThis.location.assign(a);return}await gz(t)?m(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else{let e=document.querySelector(`article[data-post-id="${t}"]`)?.closest(`[data-timeline-item]`)?.dataset.threadRootId;(e?await mz(e):await hz(t))?m(`Post updated.`):(C(`Post updated.`),globalThis.location.reload())}else C(`Post updated.`),globalThis.location.reload();return}if(re===`upload`){y();let e=s?.uploadFailedDraft??`Some uploads failed. Saved as draft.`;await S(),g(),m(e);return}let b=await fe(v),ie=w(b,`status`),ae=w(b,`permalink`),oe=w(b,`toast`);if(ie===`published`){if(y(),i)await S(),g(),m(d);else if(n.replyToId){if(await S(),!await _z(n)){C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}m(d)}else C(d,ae?{label:p,href:ae}:void 0),globalThis.location.reload();return}else y(),await S(),ee()||g(),m(oe??`Draft saved.`),kz(r,`draft`)}catch{await x(`Something went wrong`)}});function kz(e,t){(e??document).dispatchEvent(new CustomEvent(`jant:compose-submit-complete`,{bubbles:!0,detail:{status:t}}))}var Az=`.compose-prompt`,jz=`.compose-prompt-trigger`,Mz=`jant.composeOpenShortcutDiscovery`,Nz=`/api/settings/discovery/compose-open-shortcut`,Pz=350,Fz=1800,Iz=3,Lz=`compose-prompt-discovery-visible`,Rz=!1,zz=null,Bz=null,Vz=null;function Hz(){try{return globalThis.localStorage!==void 0}catch{return!1}}function Uz(){if(!Hz())return{shownCount:0,completed:!1};let e=globalThis.localStorage.getItem(Mz);if(!e)return{shownCount:0,completed:!1};try{let t=JSON.parse(e);return{shownCount:typeof t.shownCount==`number`&&t.shownCount>=0?t.shownCount:0,completed:t.completed===!0}}catch{return globalThis.localStorage.removeItem(Mz),{shownCount:0,completed:!1}}}function Wz(e){if(Hz())try{globalThis.localStorage.setItem(Mz,JSON.stringify(e))}catch{}}function Gz(){zz!==null&&(clearTimeout(zz),zz=null)}function Kz(){Bz!==null&&(clearTimeout(Bz),Bz=null)}function qz(){return typeof globalThis.matchMedia==`function`&&globalThis.matchMedia(`(min-width: 700px)`).matches}function Jz(e){return Uz().completed?!0:e?.dataset.composeOpenShortcutDiscovered===`true`}function Yz(e){e&&(e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Lz)),document.querySelectorAll(Az).forEach(e=>{e.dataset.composeOpenShortcutDiscovered=`true`,e.classList.remove(Lz)})}function Xz(){let e=Uz();e.completed||Rz||e.shownCount>=Iz||(Rz=!0,Wz({...e,shownCount:e.shownCount+1}))}function Zz(e){return!qz()||Jz(e)?!1:Uz().shownCount<Iz||Rz}function Qz(e){Gz(),Kz(),e?e.classList.remove(Lz):Vz&&Vz.classList.remove(Lz),(!e||e===Vz)&&(Vz=null)}function $z(e){Zz(e)&&(Qz(Vz),Vz=e,e.classList.add(Lz),Xz(),Bz=setTimeout(()=>{Qz(e)},Fz))}function eB(e){Zz(e)&&(e.classList.contains(Lz)||(Gz(),zz=setTimeout(()=>{$z(e)},Pz)))}function tB(e){if(e.dataset.composeOpenShortcutDiscoveryBound===`true`)return;let t=e.querySelector(jz);t&&(e.dataset.composeOpenShortcutDiscoveryBound=`true`,t.addEventListener(`pointerenter`,()=>{eB(e)}),t.addEventListener(`pointerleave`,()=>{Qz(e)}),t.addEventListener(`focusin`,()=>{eB(e)}),t.addEventListener(`focusout`,()=>{Qz(e)}))}function nB(e=document){e.querySelectorAll(Az).forEach(e=>tB(e))}function rB(){let e=Uz();e.completed||Wz({shownCount:Math.max(e.shownCount,Iz),completed:!0}),Yz(Vz),Qz(Vz),typeof globalThis.fetch==`function`&&globalThis.fetch(Nz,{method:`POST`,headers:{Accept:`application/json`},credentials:`same-origin`}).catch(()=>{})}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,()=>{nB()}):nB(),document.readyState===`loading`&&document.addEventListener(`DOMContentLoaded`,()=>{});var iB=[`input`,`textarea`,`select`,`button`,`a[href]`,`[contenteditable='']`,`[contenteditable='true']`,`[role='textbox']`,`.ProseMirror`].join(`, `);function aB(e){return e instanceof globalThis.Element&&e.closest(iB)!==null}function oB(e){if(e.defaultPrevented||e.isComposing||e.repeat||e.metaKey||e.ctrlKey||e.altKey||!nz()||document.querySelector(`[data-page="compose"]`)||document.querySelector(`dialog[open]`))return!0;let t=document.activeElement;return aB(e.target)||t!==e.target&&aB(t)}async function sB(e,t,n){try{if(!(await fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:t})})).ok)throw Error();t?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`),a(t?`Added to Featured.`:`Removed from Featured.`)}catch{a(`Could not update post. Try again.`,`error`)}}document.addEventListener(`keydown`,e=>{let t=e.key.toLowerCase();if(t!==`n`&&t!==`l`&&t!==`q`&&t!==`r`&&t!==`e`&&t!==`c`&&t!==`f`||oB(e))return;if(t===`n`||t===`l`||t===`q`){e.preventDefault(),rB();let n=rz(),r=t===`l`?`link`:t===`q`?`quote`:void 0;sz({...n?{collectionId:n}:void 0,...r?{initialFormat:r}:void 0});return}let n=iz();if(n){if(t===`r`){e.preventDefault(),cz(n);return}if(t===`e`){let t=n.dataset.postId;if(!t)return;e.preventDefault();let r=nz();r&&r.openEdit(t);return}if(t===`c`){e.preventDefault();let t=document.querySelector(`jant-post-menu`);t&&t.openCollectionsForPost(n);return}if(t===`f`){let t=n.dataset.postId;if(!t)return;e.preventDefault(),sB(t,!n.hasAttribute(`data-post-featured`),n);return}}});var cB=[`en`,`zh-Hans`,`zh-Hant`];function lB(e){return typeof e==`string`&&cB.includes(e)}function uB(e){let t=e.trim();if(!t)return`en`;let n;try{n=new Intl.Locale(t)}catch{return`en`}if(lB(n.baseName))return n.baseName;if(n.language===`zh`){let e=n.region;return n.script===`Hant`||e===`TW`||e===`HK`||e===`MO`?`zh-Hant`:`zh-Hans`}return`en`}var dB={en:1,"zh-Hans":1,"zh-Hant":1},fB=`en.zh-Hans.zh-Hant.ja.ko.es.fr.de.it.pt.ru.ar.hi.bn.ur.tr.vi.th.id.fa.he.nl.pl.sv.da.no.fi.cs.hu.el.ro.uk.en-GB.en-US.fr-CA.pt-BR.es-MX`.split(`.`),pB=null;function mB(e){let t=e,n=e;try{let n=new Intl.DisplayNames([e],{type:`language`}).of(e);typeof n==`string`&&n.length>0&&(t=n)}catch{}try{let t=new Intl.DisplayNames([`en`],{type:`language`}).of(e);typeof t==`string`&&t.length>0&&(n=t)}catch{}return{tag:e,native:t,english:n,coverage:hB(e)}}function hB(e){let t=uB(e);if(t===`en`){let t;try{t=new Intl.Locale(e).language}catch{return 0}if(t!==`en`)return 0}return dB[t]}function gB(){return pB||(pB=fB.map(mB),pB)}function _B(e){let t=e.trim();return gB().find(e=>e.tag===t)||mB(t)}var vB=class extends _{static properties={labels:{type:Object},timezones:{type:Array},cjkFonts:{type:Array,attribute:`cjk-fonts`},siteNameFallback:{type:String,attribute:`sitename-fallback`},siteDescriptionFallback:{type:String,attribute:`sitedescription-fallback`},dashboardLanguages:{type:Array,attribute:`dashboard-languages`},demoMode:{type:Boolean,attribute:`demo-mode`},mainFeedUrl:{type:String,attribute:`main-feed-url`},latestFeedUrl:{type:String,attribute:`latest-feed-url`},featuredFeedUrl:{type:String,attribute:`featured-feed-url`},archiveFeedUrl:{type:String,attribute:`archive-feed-url`},_siteName:{state:!0},_siteDescription:{state:!0},_siteFooter:{state:!0},_origSite:{state:!0},_siteDirty:{state:!0},_siteLoading:{state:!0},_siteLanguage:{state:!0},_dashboardLanguage:{state:!0},_localeOpen:{state:!0},_localeQuery:{state:!0},_cjkSerifFont:{state:!0},_timeZone:{state:!0},_origLocale:{state:!0},_localeDirty:{state:!0},_localeLoading:{state:!0},_mainRssFeed:{state:!0},_origMainRssFeed:{state:!0},_feedDirty:{state:!0},_feedLoading:{state:!0},_showJantBrandingOnHome:{state:!0},_origShowJantBrandingOnHome:{state:!0},_homeLoading:{state:!0},_noindex:{state:!0},_origNoindex:{state:!0},_searchLoading:{state:!0}};_descEditor=null;_footerEditor=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.timezones=[],this.cjkFonts=[],this.dashboardLanguages=[],this.siteNameFallback=``,this.siteDescriptionFallback=``,this.demoMode=!1,this.mainFeedUrl=`/feed`,this.latestFeedUrl=`/latest/feed`,this.featuredFeedUrl=`/featured/feed`,this.archiveFeedUrl=`/archive/feed`,this._siteName=``,this._siteDescription=``,this._siteFooter=``,this._origSite={siteName:``,siteDescription:``,siteFooter:``},this._siteDirty=!1,this._siteLoading=!1,this._siteLanguage=`en`,this._dashboardLanguage=`en`,this._localeOpen=!1,this._localeQuery=``,this._cjkSerifFont=`off`,this._timeZone=`UTC`,this._origLocale={siteLanguage:`en`,dashboardLanguage:`en`,cjkSerifFont:`off`,timeZone:`UTC`},this._localeDirty=!1,this._localeLoading=!1,this._mainRssFeed=`featured`,this._origMainRssFeed=`featured`,this._feedDirty=!1,this._feedLoading=!1,this._noindex=!1,this._origNoindex=!1,this._showJantBrandingOnHome=!1,this._origShowJantBrandingOnHome=!1,this._homeLoading=!1,this._searchLoading=!1}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this._onLocalePickerDocumentClick),document.addEventListener(`keydown`,this._onLocalePickerKeydown)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this._onLocalePickerDocumentClick),document.removeEventListener(`keydown`,this._onLocalePickerKeydown),this._descEditor?.destroy(),this._descEditor=null,this._footerEditor?.destroy(),this._footerEditor=null}initData(e){this._siteName=e.siteName,this._siteDescription=e.siteDescription,this._siteFooter=e.siteFooter,this._siteLanguage=e.siteLanguage,this._dashboardLanguage=e.dashboardLanguage,this._cjkSerifFont=e.cjkSerifFont,this._timeZone=e.timeZone,this._origLocale={siteLanguage:e.siteLanguage,dashboardLanguage:e.dashboardLanguage,cjkSerifFont:e.cjkSerifFont,timeZone:e.timeZone},this._mainRssFeed=e.mainRssFeed,this._origMainRssFeed=e.mainRssFeed,this._showJantBrandingOnHome=e.showJantBrandingOnHome,this._origShowJantBrandingOnHome=e.showJantBrandingOnHome,this._noindex=e.noindex,this._origNoindex=e.noindex,this.updateComplete.then(()=>{this._initEditors(),this._origSite={siteName:e.siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter}})}sectionSaved(e){e===`site`?(this._origSite={siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},this._siteDirty=!1,this._siteLoading=!1):e===`language-time`?(this._origLocale={siteLanguage:this._siteLanguage,dashboardLanguage:this._dashboardLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},this._localeDirty=!1,this._localeLoading=!1):e===`feeds`?(this._origMainRssFeed=this._mainRssFeed,this._feedDirty=!1,this._feedLoading=!1):e===`home`?(this._origShowJantBrandingOnHome=this._showJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._origNoindex=this._noindex,this._searchLoading=!1)}sectionError(e){e===`site`?this._siteLoading=!1:e===`language-time`?this._localeLoading=!1:e===`feeds`?this._feedLoading=!1:e===`home`?(this._showJantBrandingOnHome=this._origShowJantBrandingOnHome,this._homeLoading=!1):e===`search`&&(this._noindex=this._origNoindex,this._searchLoading=!1)}_initEditors(){this._initDescEditor(),this._initFooterEditor()}_initDescEditor(){let e=this.querySelector(`[data-settings-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=aE({element:e,placeholder:this.siteDescriptionFallback,content:this._siteDescription||void 0,onUpdate:e=>{this._siteDescription=e,this._syncSiteDirty()}}),this._siteDescription=iE(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`3rem`)}_initFooterEditor(){let e=this.querySelector(`[data-settings-footer-editor]`);if(!e||this._footerEditor)return;this._footerEditor=aE({element:e,content:this._siteFooter||void 0,onUpdate:e=>{this._siteFooter=e,this._syncSiteDirty()}}),this._siteFooter=iE(this._footerEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`6rem`)}_syncSiteDirty(){this._siteDirty=this._siteName!==this._origSite.siteName||this._siteDescription!==this._origSite.siteDescription||this._siteFooter!==this._origSite.siteFooter}_saveSite(){this._siteLoading||!this._siteDirty||(this._siteLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general`,data:{siteName:this._siteName,siteDescription:this._siteDescription,siteFooter:this._siteFooter},section:`site`}})))}_syncLocaleDirty(){this._localeDirty=this._siteLanguage!==this._origLocale.siteLanguage||this._dashboardLanguage!==this._origLocale.dashboardLanguage||this._cjkSerifFont!==this._origLocale.cjkSerifFont||this._timeZone!==this._origLocale.timeZone}_saveLocale(){this._localeLoading||!this._localeDirty||(this._localeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/general/language-time`,data:{siteLanguage:this._siteLanguage,dashboardLanguage:this._dashboardLanguage,cjkSerifFont:this._cjkSerifFont,timeZone:this._timeZone},section:`language-time`}})))}_filteredLocaleEntries(){let e=gB(),t=this._localeQuery.trim().toLowerCase();return t?e.filter(e=>e.tag.toLowerCase().includes(t)||e.native.toLowerCase().includes(t)||e.english.toLowerCase().includes(t)):e}_toggleLocalePicker=()=>{this._localeOpen=!this._localeOpen,this._localeOpen?this.updateComplete.then(()=>{this.querySelector(`[data-locale-search]`)?.focus()}):this._localeQuery=``};_selectLocale(e){this._siteLanguage=e,this._localeOpen=!1,this._localeQuery=``,this._syncLocaleDirty()}_onLocalePickerDocumentClick=e=>{if(!this._localeOpen)return;let t=e.target,n=this.querySelector(`[data-locale-picker]`);n&&t&&!n.contains(t)&&(this._localeOpen=!1)};_onLocalePickerKeydown=e=>{e.isComposing||e.keyCode===229||e.key===`Escape`&&this._localeOpen&&(this._localeOpen=!1,this._localeQuery=``)};_renderLanguagePicker(){let e=_B(this._siteLanguage||`en`),t=this._filteredLocaleEntries(),n=this.labels.siteLanguageSearchPlaceholder||`Search…`,r=this.labels.siteLanguageNoMatches||`No matches.`;return u`
2197
2197
  <div class="relative w-fit max-w-full" data-locale-picker>
2198
2198
  <button
2199
2199
  type="button"
@@ -2516,7 +2516,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2516
2516
  <div class="flex flex-col">
2517
2517
  ${this._renderGeneralForm()} ${this._renderSearchForm()}
2518
2518
  </div>
2519
- `}};customElements.define(`jant-settings-general`,cB);var lB=class extends _{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await De({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
2519
+ `}};customElements.define(`jant-settings-general`,vB);var yB=class extends _{static properties={avatarUrl:{type:String,attribute:`avatar-url`},showInHeader:{type:Boolean,attribute:`show-in-header`},labels:{type:Object},_showInHeader:{state:!0},_origShowInHeader:{state:!0},_dirty:{state:!0},_loading:{state:!0},_removeLoading:{state:!0}};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.avatarUrl=``,this.showInHeader=!1,this.labels={},this._showInHeader=!1,this._origShowInHeader=!1,this._dirty=!1,this._loading=!1,this._removeLoading=!1}connectedCallback(){super.connectedCallback(),this._showInHeader=this.showInHeader,this._origShowInHeader=this.showInHeader}saved(){this._origShowInHeader=this._showInHeader,this._dirty=!1,this._loading=!1}saveError(){this._loading=!1}removeError(){this._removeLoading=!1}_toggleDisplay(){this._showInHeader=!this._showInHeader,this._dirty=this._showInHeader!==this._origShowInHeader}_cancelDisplay(){this._showInHeader=this._origShowInHeader,this._dirty=!1}_saveDisplay(){this._loading||!this._dirty||(this._loading=!0,this.dispatchEvent(new CustomEvent(`jant:settings-save`,{bubbles:!0,detail:{endpoint:`/settings/avatar/display`,data:{showHeaderAvatar:this._showInHeader?`true`:``},section:`avatar-display`}})))}async _removeAvatar(){await De({message:this.labels.confirmRemoveAvatar,confirmLabel:this.labels.remove,cancelLabel:this.labels.cancel,tone:`danger`})&&(this._removeLoading||(this._removeLoading=!0,this.dispatchEvent(new CustomEvent(`jant:avatar-remove`,{bubbles:!0,detail:{endpoint:`/settings/avatar/remove`}}))))}_renderPreview(){let e=`rounded-full size-16 overflow-hidden border border-border/70 bg-muted/40 flex items-center justify-center shrink-0`;return this.avatarUrl?u`
2520
2520
  <div class=${e}>
2521
2521
  <img
2522
2522
  src=${this.avatarUrl}
@@ -2624,7 +2624,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2624
2624
  </div>
2625
2625
  </div>
2626
2626
  </div>
2627
- `}};customElements.define(`jant-settings-avatar`,lB);function uB(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`dashboardLanguage`)??``,a=w(e,`cjkSerifFont`),o=w(e,`mainRssFeed`),s=w(e,`timeZone`),c=w(e,`siteFooter`),l=ue(e,`showJantBrandingOnHome`),u=ue(e,`noindex`);return t===void 0||n===void 0||r===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,dashboardLanguage:i,cjkSerifFont:a,mainRssFeed:o,timeZone:s,siteFooter:c,showJantBrandingOnHome:l,noindex:u}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),o=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n)});if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await fe(e),c=w(s,`status`),l=w(s,`url`),u=w(s,`toast`);if(c===`redirect`&&l){window.location.href=l;return}u&&a(u),r===`avatar-display`?o?.saved():i?.sectionSaved(r)}catch{a(`Failed to save. Please try again.`,`error`),r===`avatar-display`?o?.saveError():i?.sectionError(r)}}),document.addEventListener(`jant:avatar-remove`,async e=>{let{endpoint:t}=e.detail,n=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await fe(e),r=w(n,`status`),i=w(n,`url`);if(r===`redirect`&&i){window.location.href=i;return}}catch{a(`Failed to remove avatar. Please try again.`,`error`),n?.removeError()}});function dB(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=uB(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,dB):queueMicrotask(dB);var fB=300,pB=1,mB=class extends _{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<pB){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},fB)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(e.isComposing||e.keyCode===229||(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1))};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
2627
+ `}};customElements.define(`jant-settings-avatar`,yB);function bB(e){let t=w(e,`siteName`),n=w(e,`siteDescription`),r=w(e,`siteLanguage`),i=w(e,`dashboardLanguage`)??``,a=w(e,`cjkSerifFont`),o=w(e,`mainRssFeed`),s=w(e,`timeZone`),c=w(e,`siteFooter`),l=ue(e,`showJantBrandingOnHome`),u=ue(e,`noindex`);return t===void 0||n===void 0||r===void 0||a===void 0||o===void 0||s===void 0||c===void 0||l===void 0||u===void 0?null:{siteName:t,siteDescription:n,siteLanguage:r,dashboardLanguage:i,cjkSerifFont:a,mainRssFeed:o,timeZone:s,siteFooter:c,showJantBrandingOnHome:l,noindex:u}}document.addEventListener(`jant:settings-save`,async e=>{let{endpoint:t,data:n,section:r}=e.detail,i=document.querySelector(`jant-settings-general`),o=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n)});if(!e.ok)throw Error(`HTTP ${e.status}`);let s=await fe(e),c=w(s,`status`),l=w(s,`url`),u=w(s,`toast`);if(c===`redirect`&&l){window.location.href=l;return}u&&a(u),r===`avatar-display`?o?.saved():i?.sectionSaved(r)}catch{a(`Failed to save. Please try again.`,`error`),r===`avatar-display`?o?.saveError():i?.sectionError(r)}}),document.addEventListener(`jant:avatar-remove`,async e=>{let{endpoint:t}=e.detail,n=document.querySelector(`jant-settings-avatar`);try{let e=await fetch(t,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);let n=await fe(e),r=w(n,`status`),i=w(n,`url`);if(r===`redirect`&&i){window.location.href=i;return}}catch{a(`Failed to remove avatar. Please try again.`,`error`),n?.removeError()}});function xB(){let e=document.querySelector(`jant-settings-general`);if(!e)return;let t=document.getElementById(`settings-initial-data`);if(t?.textContent)try{let n=bB(JSON.parse(t.textContent));n&&e.initData(n)}catch{}}document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,xB):queueMicrotask(xB);var SB=300,CB=1,wB=class extends _{static properties={labels:{type:Object},apiBase:{type:String,attribute:`api-base`},connectUrl:{type:String,attribute:`connect-url`},installUrl:{type:String,attribute:`install-url`},cancelUrl:{type:String,attribute:`cancel-url`},createRepoNameHint:{type:String,attribute:`create-repo-name-hint`},_installations:{state:!0},_selectedOwner:{state:!0},_ownerOpen:{state:!0},_repos:{state:!0},_totalCount:{state:!0},_hasMore:{state:!0},_nextPage:{state:!0},_reposMode:{state:!0},_repoOpen:{state:!0},_repoSearch:{state:!0},_loadingRepos:{state:!0},_selectedRepo:{state:!0},_classification:{state:!0},_classifying:{state:!0},_confirmText:{state:!0},_connecting:{state:!0},_error:{state:!0}};#e=null;#t=0;#n=!1;#r=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.apiBase=``,this.connectUrl=``,this.installUrl=``,this.cancelUrl=``,this.createRepoNameHint=``,this._installations=[],this._selectedOwner=null,this._ownerOpen=!1,this._repos=[],this._totalCount=0,this._hasMore=!1,this._nextPage=null,this._reposMode=`list`,this._repoOpen=!1,this._repoSearch=``,this._loadingRepos=!1,this._selectedRepo=null,this._classification=null,this._classifying=!1,this._confirmText=``,this._connecting=!1,this._error=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#m),document.addEventListener(`keydown`,this.#h),window.addEventListener(`focus`,this.#g),this.#i()}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#m),document.removeEventListener(`keydown`,this.#h),window.removeEventListener(`focus`,this.#g),this.#e&&clearTimeout(this.#e)}async#i(){try{let e=await fetch(`${this.apiBase}/installations`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._installations=t.installations;let n=t.installations.length===1?t.installations[0]:null;n&&this.#u(n)}catch(e){this._error=e instanceof Error?e.message:String(e)}}async#a(e,t={}){let n=++this.#t;this._loadingRepos=!0;try{let r=new URLSearchParams({installationId:e});t.q&&r.set(`q`,t.q);let i=await fetch(`${this.apiBase}/repos?${r.toString()}`,{headers:{Accept:`application/json`},credentials:`same-origin`});if(n!==this.#t)return;if(i.status===410){this._installations=this._installations.filter(t=>t.installationId!==e),this._selectedOwner=null,this._repos=[];return}if(!i.ok){let e=await i.json().catch(()=>({}));throw Error(e.error??`HTTP ${i.status}`)}let a=await i.json();this._repos=a.repos,this._totalCount=a.totalCount,this._hasMore=a.hasMore,this._nextPage=a.nextPage,this._reposMode=a.mode}catch(e){n===this.#t&&(this._error=e instanceof Error?e.message:String(e))}finally{n===this.#t&&(this._loadingRepos=!1)}}async#o(e,t){this._classifying=!0,this._classification=null,this._confirmText=``;try{let n=await fetch(`${this.apiBase}/classify`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:e,repo:t})}),r=await n.json();if(!n.ok||!r.classification)throw Error(r.error??`HTTP ${n.status}`);this._classification=r.classification}catch(e){this._error=e instanceof Error?e.message:String(e)}finally{this._classifying=!1}}async#s(){if(!(!this._selectedOwner||!this._selectedRepo||!this._classification)){this._connecting=!0,this._error=null;try{let e=this._classification.kind===`foreign`||this._classification.kind===`owned-by-other-site`,t=await fetch(this.connectUrl,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},credentials:`same-origin`,body:JSON.stringify({installationId:this._selectedOwner.installationId,repo:this._selectedRepo.fullName,confirmForeign:e})}),n=await t.json().catch(()=>({}));if(!t.ok||!n.ok)throw Error(n.error??`HTTP ${t.status}`);window.location.href=n.redirect??this.cancelUrl}catch(e){this._error=e instanceof Error?e.message:String(e),this._connecting=!1}}}#c(){let e=this._selectedOwner;if(!e)return;let t=this.createRepoNameHint||``,n=new URL(`https://github.com/new`);t&&n.searchParams.set(`name`,t),n.searchParams.set(`owner`,e.account.login),n.searchParams.set(`visibility`,`private`),this.#n=!0,this.#r=t||null,window.open(n.toString(),`_blank`,`noopener,noreferrer`),this._repoOpen=!1}#l(){if(!this._selectedOwner)return;let e=this._repoSearch.trim();this.#a(this._selectedOwner.installationId,e?{q:e}:{})}#u(e){if(this._selectedOwner?.installationId===e.installationId){this._ownerOpen=!1;return}this._selectedOwner=e,this._ownerOpen=!1,this._selectedRepo=null,this._classification=null,this._confirmText=``,this._repoSearch=``,this.#a(e.installationId)}#d(e){this._selectedRepo=e,this._repoOpen=!1,this._repoSearch=``,this._selectedOwner&&this.#o(this._selectedOwner.installationId,e.fullName)}#f(e){let t=e.target.value;if(this._repoSearch=t,this.#e&&clearTimeout(this.#e),!this._selectedOwner)return;let n=t.trim();if(n.length<CB){this._reposMode===`search`&&this.#a(this._selectedOwner.installationId);return}this.#e=setTimeout(()=>{this._selectedOwner&&this.#a(this._selectedOwner.installationId,{q:n})},SB)}#p(){let e=this._repoSearch.trim().toLowerCase();return!e||this._reposMode===`search`?this._repos:this._repos.filter(t=>t.name.toLowerCase().includes(e)||t.fullName.toLowerCase().includes(e))}#m=e=>{if(!this._ownerOpen&&!this._repoOpen)return;let t=e.target,n=this.querySelector(`.repo-picker-owner`),r=this.querySelector(`.repo-picker-repo`);n&&!n.contains(t)&&(this._ownerOpen=!1),r&&!r.contains(t)&&(this._repoOpen=!1)};#h=e=>{e.key===`Escape`&&(e.isComposing||e.keyCode===229||(this._ownerOpen||this._repoOpen)&&(this._ownerOpen=!1,this._repoOpen=!1))};#g=()=>{if(!this.#n)return;let e=this._selectedOwner;if(!e){this.#n=!1;return}let t=this.#r;this.#n=!1,this.#r=null,(async()=>{if(this._repoSearch=``,await this.#a(e.installationId),t){let e=this._repos.find(e=>e.name===t);e&&this.#d(e)}})()};#_(){this._ownerOpen=!this._ownerOpen,this._repoOpen=!1}#v(){this._selectedOwner&&(this._repoOpen=!this._repoOpen,this._ownerOpen=!1,this._repoOpen&&queueMicrotask(()=>{this.querySelector(`.repo-picker-repo-search`)?.focus()}))}render(){return u`
2628
2628
  <div class="flex flex-col gap-6 max-w-lg">
2629
2629
  <div>
2630
2630
  <h2 class="text-lg font-medium mb-1">${this.labels.pageTitle}</h2>
@@ -2835,7 +2835,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2835
2835
  </button>
2836
2836
  <a href=${this.cancelUrl} class="btn-ghost">${this.labels.cancel}</a>
2837
2837
  </div>
2838
- `}};customElements.define(`jant-repo-picker`,mB);var hB=`/collections`;function gB(e){return e.includes(`+`)}function _B(){return hB}function vB(e){return`/${e}`}function yB(e){return gB(e)?`${hB}/${e}`:vB(e)}function bB(e){return`${hB}/${e}/edit`}var xB,SB;function CB(){return xB?Promise.resolve(xB):(SB||=pk(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(xB=e.slugify,e.slugify)),[]),SB)}async function wB(e){return(await CB())(e)}var TB=class extends _{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{e.isComposing||e.keyCode===229||(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=XT({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=YT(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=PS(await wB(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=FS(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=o(vB(this._slug.trim()||`example`)),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}#u(){let e=this.#o();return e?u`<p
2838
+ `}};customElements.define(`jant-repo-picker`,wB);var TB=`/collections`;function EB(e){return e.includes(`+`)}function DB(){return TB}function OB(e){return`/${e}`}function kB(e){return EB(e)?`${TB}/${e}`:OB(e)}function AB(e){return`${TB}/${e}/edit`}var jB,MB;function NB(){return jB?Promise.resolve(jB):(MB||=Sk(()=>import(`./chunks/url-pLre2DM_.js`).then(e=>e.i).then(e=>(jB=e.slugify,e.slugify)),[]),MB)}async function PB(e){return(await NB())(e)}var FB=class extends _{static properties={labels:{type:Object},initial:{type:Object},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},isEdit:{type:Boolean,attribute:`is-edit`},variant:{type:String},_title:{state:!0},_slug:{state:!0},_description:{state:!0},_sortOrder:{state:!0},_showSlugEditor:{state:!0},_slugEdited:{state:!0},_suggestedSlug:{state:!0},_loading:{state:!0}};#e=!1;_descEditor=null;#t=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={},this.initial={title:``,slug:``,description:``,sortOrder:`newest`},this.action=``,this.cancelHref=`/`,this.isEdit=!1,this.variant=`full`,this._title=``,this._slug=``,this._description=``,this._sortOrder=`newest`,this._showSlugEditor=!1,this._slugEdited=!1,this._suggestedSlug=``,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t=e=>{e.isComposing||e.keyCode===229||(e.metaKey||e.ctrlKey)&&e.key===`Enter`&&(e.preventDefault(),this.#f(e))},this.addEventListener(`keydown`,this.#t)}disconnectedCallback(){this.#t&&=(this.removeEventListener(`keydown`,this.#t),null),super.disconnectedCallback(),this._descEditor?.destroy(),this._descEditor=null}update(e){(!this.#e||e.has(`initial`))&&this.#n(),super.update(e)}set loading(e){this._loading=e}get loading(){return this._loading}#n(){this.initial&&(this.#e=!0,this._title=this.initial.title??``,this._slug=this.initial.slug??``,this._suggestedSlug=this.initial.slug??``,this._description=this.initial.description??``,this._sortOrder=this.initial.sortOrder??`newest`,this._slugEdited=this.isEdit||!!this._slug.trim(),this._showSlugEditor=this.variant!==`quick`,this.variant!==`quick`&&this.updateComplete.then(()=>this.#r()))}#r(){let e=this.querySelector(`[data-collection-desc-editor]`);if(!e||this._descEditor)return;this._descEditor=aE({element:e,placeholder:this.isEdit?void 0:this.labels.descriptionPlaceholder,content:this._description||void 0,onUpdate:e=>{this._description=e}}),this._description=iE(this._descEditor.getJSON());let t=e.querySelector(`.ProseMirror`);t&&(t.style.outline=`none`,t.style.minHeight=`5rem`)}async#i(e){let t=e.target;if(this._title=t.value,this.isEdit||this._slugEdited)return;let n=t.value,r=PS(await PB(n),200);this._title===n&&(this._suggestedSlug=r,this._slugEdited||(this._slug=r))}#a(e){this._slug=e.target.value.toLowerCase(),this._slugEdited=!0}#o(){let e=FS(this._slug,{maxLength:200});return e===`too_long`?this.labels.slugTooLongHelp??`Keep this link under 200 characters.`:e===`invalid`?this.labels.slugInvalidHelp:e===`reserved`?this.labels.slugReservedHelp:null}#s(){this._showSlugEditor||(this._showSlugEditor=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-slug-input]`);e?.focus(),e?.select()}))}#c(){this._suggestedSlug&&(this._slug=this._suggestedSlug,this._slugEdited=!1,this.variant===`quick`&&(this._showSlugEditor=!1))}#l(){let e=o(OB(this._slug.trim()||`example`)),t=globalThis.location?.origin&&globalThis.location.origin!==`null`?globalThis.location.origin:`http://localhost`;return new URL(e,`${t}/`).toString()}#u(){let e=this.#o();return e?u`<p
2839
2839
  class="text-xs text-destructive mt-1"
2840
2840
  data-collection-slug-error
2841
2841
  >
@@ -2892,7 +2892,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
2892
2892
  </button>
2893
2893
  </div>
2894
2894
  </div>
2895
- `}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=PS(await wB(t),200),this._slug=n,this._suggestedSlug=n),!n||this.#o()){this.variant===`quick`&&!this._showSlugEditor&&this.#s(),this.updateComplete.then(()=>{this.querySelector(`[data-collection-slug-input]`)?.focus()});return}let r={endpoint:this.action,isEdit:this.isEdit,data:{title:t,slug:n,description:this.variant===`quick`?void 0:this._description.trim()||void 0,sortOrder:this.variant===`quick`?void 0:this._sortOrder||void 0}};this.dispatchEvent(new CustomEvent(`jant:collection-submit`,{bubbles:!0,detail:r}))}render(){let e=this.variant===`quick`;return u`
2895
+ `}async#f(e){if(e.preventDefault(),this._loading)return;let t=this._title.trim(),n=this._slug.trim();if(!t){this.querySelector(`[data-collection-title-input]`)?.focus();return}if(!n&&!this._slugEdited&&(n=PS(await PB(t),200),this._slug=n,this._suggestedSlug=n),!n||this.#o()){this.variant===`quick`&&!this._showSlugEditor&&this.#s(),this.updateComplete.then(()=>{this.querySelector(`[data-collection-slug-input]`)?.focus()});return}let r={endpoint:this.action,isEdit:this.isEdit,data:{title:t,slug:n,description:this.variant===`quick`?void 0:this._description.trim()||void 0,sortOrder:this.variant===`quick`?void 0:this._sortOrder||void 0}};this.dispatchEvent(new CustomEvent(`jant:collection-submit`,{bubbles:!0,detail:r}))}render(){let e=this.variant===`quick`;return u`
2896
2896
  <form
2897
2897
  class=${e?`flex flex-col gap-4`:`collection-editor-form`}
2898
2898
  @submit=${e=>void this.#f(e)}
@@ -3007,20 +3007,20 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3007
3007
  </div>
3008
3008
  `}
3009
3009
  </form>
3010
- `}};customElements.define(`jant-collection-form`,TB);function EB(e,t){let n=e[t];if(!n||n.type!==`divider`||!n.label)return null;let r=[];for(let n=t+1;n<e.length;n+=1){let t=e[n];if(!t||t.type===`divider`)break;let i=t.collection?.slug;i&&r.push(i)}return r.length<2?null:{slugExpression:r.join(`+`),collectionCount:r.length}}function DB(e){return typeof e==`string`?e:``}function OB(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function kB(e){let n=mx(t(e.src));if(!n)return``;let r=` sandbox="${mx(e.sandbox)}"`,i=e.allow?` allow="${mx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${mx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function AB(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${mx(n.join(`;`))}"`:``;return` data-orientation="${mx(t)}"${r}`}function jB(e,n){let r=kB(e);if(!r)return``;let i=mx(t(e.url||e.src)),a=mx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=mx(e.provider),c=n?.trim()?`<figcaption>${mx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${AB(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function MB(e){let n=e??{},r=DB(n.url),i=DB(n.src),a=null;if(i){let e=t(i);e&&(a={provider:DB(n.provider)||`iframe`,providerName:DB(n.providerName)||`Embed`,src:e,url:r||e,orientation:DB(n.orientation)||`landscape`,heightPx:OB(n.heightPx)??void 0,sandbox:DB(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:DB(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=nC(r)),!a){if(!r)return``;let e=mx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return jB(a,DB(n.caption))}function NB(e,t){let n=e?.[t];return typeof n==`string`?n:``}function PB(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function FB(e){switch(e.type){case`text`:return mx(e.text??``);case`hardBreak`:return`
3011
- `;default:return(e.content??[]).map(FB).join(``)}}function IB(e,t,n){let r=PB(t.attrs,`colspan`),i=PB(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function LB(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var RB=null;function zB(e,t){let n=ax(NB(e.attrs,`label`)),r=lx(n),i=RB?.get(n),a=i?LB(t.renderChildren(i.content)):``;return`<label for="sn-${mx(r)}" class="margin-toggle sidenote-number footref"></label><input type="checkbox" id="sn-${mx(r)}" class="margin-toggle footref-toggle"/><span class="sidenote">${a}</span>`}var BB={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=mx(t(NB(n.attrs,`href`))),i=NB(n.attrs,`target`);return`<a href="${r}"${i?` target="${mx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},VB={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=ax(NB(e.attrs,`label`));t&&r.set(t,e)}RB=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{RB=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(PB(e.attrs,`level`)??1,1),6);return`<h${n}>${t.renderChildren(e.content)}</h${n}>`},text:(e,t)=>t.renderText(e.text??``,e.marks),bulletList:(e,t)=>`<ul>${t.renderChildren(e.content)}</ul>`,orderedList:(e,t)=>{let n=PB(e.attrs,`start`);return`<ol${n!==null&&n!==1?` start="${n}"`:``}>${t.renderChildren(e.content)}</ol>`},listItem:(e,t)=>`<li>${t.renderChildren(e.content)}</li>`,blockquote:(e,t)=>`<blockquote>${t.renderChildren(e.content)}</blockquote>`,codeBlock:e=>{let t=NB(e.attrs,`language`);return`<pre><code${t?` class="language-${mx(t)}"`:``}>${FB(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>IB(`td`,e,t),tableHeader:(e,t)=>IB(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>_x(e.attrs??{}),embed:e=>MB(e.attrs),htmlBlock:e=>{let t=NB(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>zB(e,t),footnoteDefinition:()=>``};function HB(e,t=[]){let n=mx(e);for(let e of t){let t=BB[e.type];t&&(n=t(n,e))}return n}function UB(e=[]){return e.map(GB).join(``)}function WB(e,t){return e.content?t.renderChildren(e.content):``}function GB(e){return(VB[e.type]??WB)(e,KB)}var KB={renderChildren:UB,renderNode:GB,renderText:HB};function qB(e){return e.type===`doc`?GB(fx(e)):``}function JB(e){return e.trim()?qB(qx(e)):``}function YB(){return Math.floor(Date.now()/1e3)}function XB(e){return new Date(e*1e3).toISOString()}function ZB(e,t=`UTC`){let n=YB()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function QB(e,t=`UTC`){let n=ZB(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var $B=class extends _{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#v();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#_();break;case`divider`:this.#x();break;case`link`:this.#S();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#d()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#d(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#f(e){return this.#r?.querySelector(e)??null}#p(){let e=this.#f(`[data-collections-action="done"]`);e&&(e.hidden=!this._reorderMode);let t=this.#f(`[data-collections-reorder-actions]`);t&&(t.hidden=!this._reorderMode);let n=this.#f(`[data-collections-toolbar]`);n&&(n.hidden=this._reorderMode);let r=this.#f(`[data-collections-hint]`);r&&(r.hidden=!this._reorderMode);let i=this.#f(`[data-collections-more-menu]`);i&&(i.hidden=!this._showMoreMenu||this._reorderMode);let a=this.#f(`[data-collections-action="toggle-menu"]`);a&&a.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#m(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#h(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#m(t)}catch{}}#g(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...FO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{zO(e,!0)},onStart:e=>{this.#n=LO(e)},onUnchoose:()=>{zO(e,!1)},onEnd:t=>{let n=IO(e,`[data-directory-item]`,`directoryItem`);RO(e,t,this.#n),this.#n=null,zO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:o}=BO(n,t.newIndex);if(!r)return;let s=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>s.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/directory-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:o??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)})}}))}#_(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#v(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#d(),this.#p(),this._reorderMode&&this.#g(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#y()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#b()}#y(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=XT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=YT(this.#i.getJSON()))}#b(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=XT({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=YT(this.#a.getJSON()))}async#x(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#h(),this._editingDividerId=t.id}catch{a(this.labels.saveFailed,`error`)}}#S(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#C(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=this._newLinkDescription.trim()||null,r=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,description:n})});if(!r.ok)throw Error(`HTTP ${r.status}`);this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,a(this.labels.linkCreated),await this.#h()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#w(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{a(this.labels.saveFailed,`error`)}}async#T(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#E(e){if(await De({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(this.labels.deleted),await this.#h()}catch{a(this.labels.saveFailed,`error`)}}}#D(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#O(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){a(this.labels.labelAndUrlRequired,`error`);return}try{let r=this._editLinkDescription.trim()||null,i=await fetch(`/api/collections/directory-items/${e.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,url:n,description:r})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();this._items=this._items.map(r=>r.id===e.id?{...r,label:o.label??t,url:o.url??n,description:o.description??null}:r),this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkSaved)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#k(e){if(await De({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{a(this.labels.saveFailed,`error`)}}}#A(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#j(e,t){let n=e.collection;if(!n)return m;let r=u`
3010
+ `}};customElements.define(`jant-collection-form`,FB);function IB(e,t){let n=e[t];if(!n||n.type!==`divider`||!n.label)return null;let r=[];for(let n=t+1;n<e.length;n+=1){let t=e[n];if(!t||t.type===`divider`)break;let i=t.collection?.slug;i&&r.push(i)}return r.length<2?null:{slugExpression:r.join(`+`),collectionCount:r.length}}function LB(e){return typeof e==`string`?e:``}function RB(e){return typeof e==`number`&&Number.isFinite(e)?e:null}function zB(e){let n=mx(t(e.src));if(!n)return``;let r=` sandbox="${mx(e.sandbox)}"`,i=e.allow?` allow="${mx(e.allow)}"`:``;return`<iframe src="${n}"${` title="${mx(e.providerName)} embed"`}${r}${i} loading="lazy" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>`}function BB(e){let t=e.orientation===`portrait`?`portrait`:e.orientation===`square`?`square`:e.orientation===`auto`?`auto`:`landscape`,n=[];e.heightPx&&e.heightPx>0&&n.push(`--tiptap-embed-height:${Math.round(e.heightPx)}px`);let r=n.length>0?` style="${mx(n.join(`;`))}"`:``;return` data-orientation="${mx(t)}"${r}`}function VB(e,n){let r=zB(e);if(!r)return``;let i=mx(t(e.url||e.src)),a=mx(e.providerName),o=i?`<a class="tiptap-embed-fallback" href="${i}" target="_blank" rel="noopener noreferrer">${a} →</a>`:``,s=mx(e.provider),c=n?.trim()?`<figcaption>${mx(n.trim())}</figcaption>`:``;return`<figure class="tiptap-embed-figure" data-provider="${s}"${BB(e)}><div class="tiptap-embed-frame">${r}</div>`+o+c+`</figure>`}function HB(e){let n=e??{},r=LB(n.url),i=LB(n.src),a=null;if(i){let e=t(i);e&&(a={provider:LB(n.provider)||`iframe`,providerName:LB(n.providerName)||`Embed`,src:e,url:r||e,orientation:LB(n.orientation)||`landscape`,heightPx:RB(n.heightPx)??void 0,sandbox:LB(n.sandbox)||`allow-scripts allow-same-origin allow-popups`,allow:LB(n.allow)||void 0,cspFrameSrc:[],cspScriptSrc:[]})}if(!a&&r&&(a=nC(r)),!a){if(!r)return``;let e=mx(t(r));return e?`<p class="tiptap-embed-fallback"><a href="${e}" target="_blank" rel="noopener noreferrer">${e}</a></p>`:``}return VB(a,LB(n.caption))}function UB(e,t){let n=e?.[t];return typeof n==`string`?n:``}function WB(e,t){let n=e?.[t];return typeof n==`number`&&Number.isFinite(n)?n:null}function GB(e){switch(e.type){case`text`:return mx(e.text??``);case`hardBreak`:return`
3011
+ `;default:return(e.content??[]).map(GB).join(``)}}function KB(e,t,n){let r=WB(t.attrs,`colspan`),i=WB(t.attrs,`rowspan`);return`<${e}${r!==null&&r!==1?` colspan="${r}"`:``}${i!==null&&i!==1?` rowspan="${i}"`:``}>${n.renderChildren(t.content)}</${e}>`}function qB(e){let t=e.trim();return t.startsWith(`<p>`)&&t.endsWith(`</p>`)&&t.indexOf(`<p>`,1)===-1?t.slice(3,-4):t}var JB=null;function YB(e,t){let n=ax(UB(e.attrs,`label`)),r=lx(n),i=JB?.get(n),a=i?qB(t.renderChildren(i.content)):``;return`<label for="sn-${mx(r)}" class="margin-toggle sidenote-number footref"></label><input type="checkbox" id="sn-${mx(r)}" class="margin-toggle footref-toggle"/><span class="sidenote">${a}</span>`}var XB={bold:e=>`<strong>${e}</strong>`,italic:e=>`<em>${e}</em>`,strike:e=>`<s>${e}</s>`,code:e=>`<code>${e}</code>`,link:(e,n)=>{let r=mx(t(UB(n.attrs,`href`))),i=UB(n.attrs,`target`);return`<a href="${r}"${i?` target="${mx(i)}"`:``}${i?` rel="noopener noreferrer"`:``}>${e}</a>`}},ZB={doc:(e,t)=>{let n=e.content??[],r=new Map;for(let e of n)if(e.type===`footnoteDefinition`){let t=ax(UB(e.attrs,`label`));t&&r.set(t,e)}JB=r.size>0?r:null;try{let e=n.filter(e=>e.type!==`footnoteDefinition`);return t.renderChildren(e)}finally{JB=null}},paragraph:(e,t)=>`<p>${t.renderChildren(e.content)}</p>`,heading:(e,t)=>{let n=Math.min(Math.max(WB(e.attrs,`level`)??1,1),6);return`<h${n}>${t.renderChildren(e.content)}</h${n}>`},text:(e,t)=>t.renderText(e.text??``,e.marks),bulletList:(e,t)=>`<ul>${t.renderChildren(e.content)}</ul>`,orderedList:(e,t)=>{let n=WB(e.attrs,`start`);return`<ol${n!==null&&n!==1?` start="${n}"`:``}>${t.renderChildren(e.content)}</ol>`},listItem:(e,t)=>`<li>${t.renderChildren(e.content)}</li>`,blockquote:(e,t)=>`<blockquote>${t.renderChildren(e.content)}</blockquote>`,codeBlock:e=>{let t=UB(e.attrs,`language`);return`<pre><code${t?` class="language-${mx(t)}"`:``}>${GB(e)}</code></pre>`},table:(e,t)=>`<table>${t.renderChildren(e.content)}</table>`,tableRow:(e,t)=>`<tr>${t.renderChildren(e.content)}</tr>`,tableCell:(e,t)=>KB(`td`,e,t),tableHeader:(e,t)=>KB(`th`,e,t),horizontalRule:()=>`<hr>`,hardBreak:()=>`<br>`,image:e=>_x(e.attrs??{}),embed:e=>HB(e.attrs),htmlBlock:e=>{let t=UB(e.attrs,`html`);return t?`<div class="tiptap-html-block">${t}</div>`:``},moreBreak:()=>`<!--more-->`,footnoteReference:(e,t)=>YB(e,t),footnoteDefinition:()=>``};function QB(e,t=[]){let n=mx(e);for(let e of t){let t=XB[e.type];t&&(n=t(n,e))}return n}function $B(e=[]){return e.map(tV).join(``)}function eV(e,t){return e.content?t.renderChildren(e.content):``}function tV(e){return(ZB[e.type]??eV)(e,nV)}var nV={renderChildren:$B,renderNode:tV,renderText:QB};function rV(e){return e.type===`doc`?tV(fx(e)):``}function iV(e){return e.trim()?rV(qx(e)):``}function aV(){return Math.floor(Date.now()/1e3)}function oV(e){return new Date(e*1e3).toISOString()}function sV(e,t=`UTC`){let n=aV()-e;if(n<60)return`1m`;let r=Math.floor(n/60);if(r<60)return`${r}m`;let i=Math.floor(n/3600);if(i<24)return`${i}h`;let a=Math.floor(n/86400);return a<=7?`${a}d`:new Date(e*1e3).toLocaleDateString(`en-US`,{month:`short`,day:`numeric`,timeZone:t})}function cV(e,t=`UTC`){let n=sV(e,t);return/^[0-9]+[mhd]$/.test(n)?`${n} ago`:n}var lV=class extends _{static properties={items:{type:Array},labels:{type:Object},_items:{state:!0},_reorderMode:{state:!0},_editingDividerId:{state:!0},_editingLinkId:{state:!0},_editLinkLabel:{state:!0},_editLinkUrl:{state:!0},_editLinkDescription:{state:!0},_showMoreMenu:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_newLinkDescription:{state:!0},_addingLink:{state:!0},_hoveringId:{state:!0},_showItemMenuId:{state:!0}};#e=null;#t=!1;#n=null;#r=null;#i=null;#a=null;#o=()=>{this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)};#s=()=>{this._showItemMenuId=null,document.removeEventListener(`click`,this.#s)};#c=e=>{let t=e.target;if(!t)return;t.closest(`[data-collections-more-menu]`)&&e.stopPropagation();let n=t.closest(`[data-collections-action]`);if(!n||!this.#r?.contains(n))return;let r=n.dataset.collectionsAction;if(r)switch(e.preventDefault(),e.stopPropagation(),r!==`toggle-menu`&&this._showMoreMenu&&(this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)),r){case`done`:this.#v();break;case`toggle-menu`:this._showMoreMenu=!this._showMoreMenu,this._showMoreMenu?setTimeout(()=>{document.addEventListener(`click`,this.#o)}):document.removeEventListener(`click`,this.#o);break;case`organize`:this.#_();break;case`divider`:this.#x();break;case`link`:this.#S();break;default:break}};createRenderRoot(){return this.innerHTML=``,this}connectedCallback(){super.connectedCallback(),this.#d()}constructor(){super(),this.items=[],this.labels={},this._items=[],this._reorderMode=!1,this._editingDividerId=null,this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this._showMoreMenu=!1,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this._addingLink=!1,this._hoveringId=null,this._showItemMenuId=null}update(e){(!this.#t||e.has(`items`))&&(this._items=[...this.items??[]],this.#t=!0),super.update(e)}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#r?.removeEventListener(`click`,this.#c),this.#r=null,this.#i?.destroy(),this.#i=null,this.#a?.destroy(),this.#a=null,document.removeEventListener(`click`,this.#o),document.removeEventListener(`click`,this.#s)}#l(){return this._items.some(e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url)}#u(e){return`${e} ${e===1?this.labels.entrySingular:this.labels.entryPlural}`}#d(){let e=this.closest(`[data-collections-manager-root]`);e!==this.#r&&(this.#r?.removeEventListener(`click`,this.#c),this.#r=e,this.#r?.addEventListener(`click`,this.#c))}#f(e){return this.#r?.querySelector(e)??null}#p(){let e=this.#f(`[data-collections-action="done"]`);e&&(e.hidden=!this._reorderMode);let t=this.#f(`[data-collections-reorder-actions]`);t&&(t.hidden=!this._reorderMode);let n=this.#f(`[data-collections-toolbar]`);n&&(n.hidden=this._reorderMode);let r=this.#f(`[data-collections-hint]`);r&&(r.hidden=!this._reorderMode);let i=this.#f(`[data-collections-more-menu]`);i&&(i.hidden=!this._showMoreMenu||this._reorderMode);let a=this.#f(`[data-collections-action="toggle-menu"]`);a&&a.setAttribute(`aria-expanded`,String(this._showMoreMenu&&!this._reorderMode))}#m(e){let t=e.collections??[],n=e.directoryItems??[],r=new Map;for(let e of t)r.set(e.id,{id:e.id,slug:e.slug,title:e.title,description:e.description,sortOrder:e.sortOrder,postCount:e.postCount??0,recentActivityAt:e.recentActivityAt});let i=new Set,a=[];for(let e of n){let t=e.collectionId==null?void 0:r.get(e.collectionId);e.type===`collection`&&!t||(t&&i.add(t.id),a.push({id:e.id,type:e.type,collectionId:e.collectionId,label:e.label,url:e.url,description:e.description,position:e.position,collection:t}))}for(let e of t)i.has(e.id)||a.push({id:`collection-${e.id}`,type:`collection`,collectionId:e.id,label:null,url:null,position:``,collection:r.get(e.id)});return a}async#h(){try{let e=await fetch(`/api/collections`);if(!e.ok)return;let t=await e.json();this._items=this.#m(t)}catch{}}#g(){let e=this.querySelector(`#collections-manager-list`);!e||this.#e||(this.#e=H.create(e,{...WO,chosenClass:`collection-directory-chosen`,dragClass:`collection-directory-drag`,ghostClass:`collection-directory-ghost`,handle:`[data-drag-handle]`,scroll:!0,onChoose:()=>{JO(e,!0)},onStart:e=>{this.#n=KO(e)},onUnchoose:()=>{JO(e,!1)},onEnd:t=>{let n=GO(e,`[data-directory-item]`,`directoryItem`);qO(e,t,this.#n),this.#n=null,JO(e,!1),this.#e?.destroy(),this.#e=null;let{movedId:r,afterId:i,beforeId:o}=YO(n,t.newIndex);if(!r)return;let s=new Map(this._items.map(e=>[e.id,e]));this._items=n.map(e=>s.get(e)).filter(e=>e!==void 0),fetch(`/api/collections/directory-items/${r}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:i??null,before:o??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)})}}))}#_(){this._reorderMode=!0,this._showLinkForm=!1,this._editingLinkId=null,this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o)}#v(){this._reorderMode=!1,this._editingDividerId=null,this.#e?.destroy(),this.#e=null}updated(e){if(this.#d(),this.#p(),this._reorderMode&&this.#g(),this._editingDividerId){let e=this.querySelector(`[data-divider-input-for="${this._editingDividerId}"]`);e&&(e.focus(),e.select(),e.scrollIntoView({block:`nearest`}),this._editingDividerId=null)}if(e.has(`_showLinkForm`)&&this._showLinkForm){let e=this.querySelector(`[data-link-form-input="label"]`);e&&this.ownerDocument.activeElement!==e&&e.focus(),this.#y()}e.has(`_editingLinkId`)&&this._editingLinkId&&this.#b()}#y(){let e=this.querySelector(`[data-new-link-desc-editor]`);!e||this.#i||(this.#i=aE({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._newLinkDescription||void 0,onUpdate:e=>{this._newLinkDescription=e}}),this._newLinkDescription=iE(this.#i.getJSON()))}#b(){let e=this.querySelector(`[data-edit-link-desc-editor]`);!e||this.#a||(this.#a=aE({element:e,placeholder:this.labels.linkDescriptionPlaceholder,content:this._editLinkDescription||void 0,onUpdate:e=>{this._editLinkDescription=e}}),this._editLinkDescription=iE(this.#a.getJSON()))}async#x(){this._showMoreMenu=!1,document.removeEventListener(`click`,this.#o);try{let e=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`divider`})});if(!e.ok)throw Error(`HTTP ${e.status}`);let t=await e.json();this._reorderMode=!0,await this.#h(),this._editingDividerId=t.id}catch{a(this.labels.saveFailed,`error`)}}#S(){this._showMoreMenu=!1,this._showLinkForm=!0,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,document.removeEventListener(`click`,this.#o)}async#C(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=this._newLinkDescription.trim()||null,r=await fetch(`/api/collections/directory-items`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,description:n})});if(!r.ok)throw Error(`HTTP ${r.status}`);this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._newLinkDescription=``,this.#i?.destroy(),this.#i=null,a(this.labels.linkCreated),await this.#h()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#w(e){try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._items=this._items.filter(t=>t.id!==e)}catch{a(this.labels.saveFailed,`error`)}}async#T(e,t){let n=t.trim();if(n!==(this._items.find(t=>t.id===e)?.label??``))try{let t=await fetch(`/api/collections/directory-items/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:n||null})});if(!t.ok)throw Error(`HTTP ${t.status}`);let r=await t.json();this._items=this._items.map(t=>t.id===e?{...t,label:r.label??null}:t)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#E(e){if(await De({message:this.labels.confirmDelete,confirmLabel:this.labels.deleteCollection,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);a(this.labels.deleted),await this.#h()}catch{a(this.labels.saveFailed,`error`)}}}#D(e){if(e.type===`link`){if(this._editingLinkId===e.id){this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null;return}this._editingLinkId=e.id,this._editLinkLabel=e.label??``,this._editLinkUrl=e.url??``,this._editLinkDescription=e.description??``,this.#a?.destroy(),this.#a=null}}async#O(e){let t=this._editLinkLabel.trim(),n=this._editLinkUrl.trim();if(!t||!n){a(this.labels.labelAndUrlRequired,`error`);return}try{let r=this._editLinkDescription.trim()||null,i=await fetch(`/api/collections/directory-items/${e.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({label:t,url:n,description:r})});if(!i.ok)throw Error(`HTTP ${i.status}`);let o=await i.json();this._items=this._items.map(r=>r.id===e.id?{...r,label:o.label??t,url:o.url??n,description:o.description??null}:r),this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkSaved)}catch{a(this.labels.saveFailed,`error`),await this.#h()}}async#k(e){if(await De({message:this.labels.confirmDeleteLink,confirmLabel:this.labels.deleteLink,cancelLabel:this.labels.cancel,tone:`danger`})){this._showItemMenuId=null,document.removeEventListener(`click`,this.#s);try{let t=await fetch(`/api/collections/directory-items/${e.id}`,{method:`DELETE`});if(!t.ok)throw Error(`HTTP ${t.status}`);this._editingLinkId=null,this._editLinkLabel=``,this._editLinkUrl=``,this._editLinkDescription=``,this.#a?.destroy(),this.#a=null,a(this.labels.linkDeleted),this._items=this._items.filter(t=>t.id!==e.id)}catch{a(this.labels.saveFailed,`error`)}}}#A(){let e=e=>e.type===`collection`&&e.collection||e.type===`link`&&e.label&&e.url,t=[],n=!1,r=0;for(let i of this._items)i.type===`divider`?(n=!0,t.push(0)):e(i)&&(n?t[t.length-1]+=1:r+=1);let i=t.length>0,a=Math.max(0,t.length-1),o=i?Math.max(1,a.toString(36).length):0,s=Math.max(2,String(Math.max(0,r-1)).length),c=[],l=-1,u=0;for(let t of this._items)if(t.type===`divider`)l+=1,u=0,c.push(``);else if(e(t)){if(i){let e=Math.max(0,l).toString(36).padStart(o,`0`),t=u.toString(36);c.push(e+t)}else c.push(String(u).padStart(s,`0`));u+=1}else c.push(``);return c}#j(e,t){let n=e.collection;if(!n)return m;let r=u`
3012
3012
  <div class="collection-directory-main">
3013
3013
  <span class="collection-directory-sequence" aria-hidden="true">
3014
3014
  ${t}
3015
3015
  </span>
3016
3016
  <div class="collection-directory-title-row">
3017
- <a href=${o(yB(n.slug))} class="collection-directory-title-link">
3017
+ <a href=${o(kB(n.slug))} class="collection-directory-title-link">
3018
3018
  <span class="collection-directory-title">${n.title}</span>
3019
3019
  </a>
3020
3020
  </div>
3021
3021
  ${n.description?u`
3022
3022
  <div class="collection-directory-description prose">
3023
- ${s(JB(n.description))}
3023
+ ${s(iV(n.description))}
3024
3024
  </div>
3025
3025
  `:m}
3026
3026
  <p class="collection-directory-summary">
@@ -3032,9 +3032,9 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3032
3032
  >
3033
3033
  <time
3034
3034
  class="collection-directory-updated"
3035
- datetime=${XB(n.recentActivityAt)}
3035
+ datetime=${oV(n.recentActivityAt)}
3036
3036
  >
3037
- ${QB(n.recentActivityAt)}
3037
+ ${cV(n.recentActivityAt)}
3038
3038
  </time>
3039
3039
  </p>
3040
3040
  </div>
@@ -3174,7 +3174,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3174
3174
  </div>
3175
3175
  ${e.description?u`
3176
3176
  <div class="collection-directory-description prose">
3177
- ${s(JB(e.description))}
3177
+ ${s(iV(e.description))}
3178
3178
  </div>
3179
3179
  `:u`
3180
3180
  <p class="collection-directory-summary">
@@ -3252,7 +3252,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3252
3252
  >
3253
3253
  ${t?u`
3254
3254
  <a
3255
- href=${o(`${bB(t.slug)}?returnTo=${encodeURIComponent(o(_B()))}`)}
3255
+ href=${o(`${AB(t.slug)}?returnTo=${encodeURIComponent(o(DB()))}`)}
3256
3256
  class="collections-page-menu-item"
3257
3257
  >
3258
3258
  ${this.labels.edit}
@@ -3344,7 +3344,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3344
3344
  </svg>
3345
3345
  </button>
3346
3346
  </div>
3347
- `;let n=!!e.label,r=EB(this._items,t);return u`
3347
+ `;let n=!!e.label,r=IB(this._items,t);return u`
3348
3348
  <div class="collection-directory-divider">
3349
3349
  <div
3350
3350
  class="collection-directory-divider-row"
@@ -3353,7 +3353,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3353
3353
  ${n?u`
3354
3354
  ${r?u`
3355
3355
  <a
3356
- href=${o(yB(r.slugExpression))}
3356
+ href=${o(kB(r.slugExpression))}
3357
3357
  class="collection-directory-divider-link collection-directory-divider-text"
3358
3358
  >
3359
3359
  ${e.label}
@@ -3431,7 +3431,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3431
3431
  ${(()=>{let e=this.#A();return this._items.map((t,n)=>t.type===`collection`?this.#j(t,e[n]):t.type===`link`?this.#N(t,e[n]):this.#F(t,n))})()}
3432
3432
  </div>
3433
3433
  `:u`<p class="text-muted-foreground">${this.labels.emptyState}</p>`}
3434
- `}};customElements.define(`jant-collections-manager`,$B);function eV(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function tV(){return document.documentElement.dataset.sitePathPrefix||``}function nV(e){let t=tV();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function rV(e,t,n){let r=e.split(`+`).filter(Boolean);if(r.length===0||r.length===1)return t;if(!n)return e;let i=!1,a=r.map(e=>e===n?(i=!0,t):e);return i?a.join(`+`):e}function iV(e,t,n){let r=t.cancelHref||o(_B());if(!e.isEdit||!n)return r;let i=eV(r);if(!i)return o(vB(n));let a=nV(i.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&a===vB(s))return i.pathname=o(vB(n)),`${i.pathname}${i.search}${i.hash}`;let c=a?.match(/^\/collections\/([^/]+)$/);return c&&(i.pathname=o(yB(rV(c[1],n,s)))),`${i.pathname}${i.search}${i.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=iV(n,r,typeof t?.slug==`string`&&t.slug.length>0?t.slug:void 0);window.location.href=a;return}catch(e){a(e instanceof Error?e.message:i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`,`error`)}finally{r.loading=!1}}});function aV(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(TS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
3434
+ `}};customElements.define(`jant-collections-manager`,lV);function uV(e){try{let t=new URL(e,window.location.origin);return t.origin===window.location.origin?t:null}catch{return null}}function dV(){return document.documentElement.dataset.sitePathPrefix||``}function fV(e){let t=dV();return t?e===t?`/`:e.startsWith(`${t}/`)?e.slice(t.length)||`/`:null:e||`/`}function pV(e,t,n){let r=e.split(`+`).filter(Boolean);if(r.length===0||r.length===1)return t;if(!n)return e;let i=!1,a=r.map(e=>e===n?(i=!0,t):e);return i?a.join(`+`):e}function mV(e,t,n){let r=t.cancelHref||o(DB());if(!e.isEdit||!n)return r;let i=uV(r);if(!i)return o(OB(n));let a=fV(i.pathname),s=t.initial?.slug?.trim()||void 0;if(s&&a===OB(s))return i.pathname=o(OB(n)),`${i.pathname}${i.search}${i.hash}`;let c=a?.match(/^\/collections\/([^/]+)$/);return c&&(i.pathname=o(kB(pV(c[1],n,s)))),`${i.pathname}${i.search}${i.hash}`}document.addEventListener(`jant:collection-submit`,async e=>{let t=e,n=t.detail,r=t.target instanceof HTMLElement?t.target:document.querySelector(`jant-collection-form`),i=r?.closest(`[data-collection-editor-page]`);if(!(!n?.endpoint||!r||!i)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:n.isEdit?`PUT`:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`);let a=mV(n,r,typeof t?.slug==`string`&&t.slug.length>0?t.slug:void 0);window.location.href=a;return}catch(e){a(e instanceof Error?e.message:i.dataset.collectionEditorSaveFailed||`Couldn't save. Try again in a moment.`,`error`)}finally{r.loading=!1}}});function hV(e){let t;if(e===`application/pdf`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="6" font-weight="700" font-family="system-ui, sans-serif">PDF</text>`;else if(e===`text/markdown`)t=`<text x="12" y="16.5" text-anchor="middle" fill="currentColor" stroke="none" font-size="10" font-weight="700" font-family="system-ui, sans-serif">#</text>`;else if(e===`text/csv`)t=`<line x1="8" y1="12" x2="16" y2="12"/><line x1="8" y1="15" x2="16" y2="15"/><line x1="8" y1="18" x2="16" y2="18"/><line x1="10.7" y1="12" x2="10.7" y2="18"/><line x1="13.3" y1="12" x2="13.3" y2="18"/>`;else if(TS(e)===`archive`)t=`<line x1="12" y1="10" x2="12" y2="11.5"/><line x1="12" y1="13" x2="12" y2="14.5"/><line x1="12" y1="16" x2="12" y2="17.5"/>`;else if(e.startsWith(`audio/`))return u`<svg
3435
3435
  width="24"
3436
3436
  height="24"
3437
3437
  viewBox="0 0 24 24"
@@ -3464,7 +3464,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3464
3464
  stroke-linejoin="round"
3465
3465
  >
3466
3466
  ${ke(`<path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/>`+t)}
3467
- </svg>`}function oV(e){return TS(e.mimeType)===`image`?u`<img
3467
+ </svg>`}function gV(e){return TS(e.mimeType)===`image`?u`<img
3468
3468
  src=${e.thumbUrl}
3469
3469
  alt=${e.alt}
3470
3470
  class="w-full h-full object-cover rounded-lg border"
@@ -3472,15 +3472,15 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3472
3472
  />`:u`<div
3473
3473
  class="w-full h-full rounded-lg border bg-muted flex flex-col items-center justify-center gap-1 p-1 text-muted-foreground"
3474
3474
  >
3475
- ${aV(e.mimeType)}
3475
+ ${hV(e.mimeType)}
3476
3476
  <span class="text-[10px] leading-tight text-center truncate w-full px-1"
3477
3477
  >${e.originalName}</span
3478
3478
  >
3479
- </div>`}function sV(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
3479
+ </div>`}function _V(e){let{media:t,labels:n,_mediaIds:r}=e;if(r.length===0)return u`<p class="text-sm text-muted-foreground">
3480
3480
  ${n.mediaEmptyLabel}
3481
3481
  </p>`;let i=new Map(t.map(e=>[e.id,e]));return u`<div class="grid grid-cols-4 sm:grid-cols-6 gap-2 mb-2">
3482
3482
  ${r.map(t=>{let r=i.get(t);return r?u`<div class="relative group aspect-square" data-media-id=${t}>
3483
- ${oV(r)}
3483
+ ${gV(r)}
3484
3484
  <button
3485
3485
  type="button"
3486
3486
  class="absolute top-1 right-1 w-5 h-5 flex items-center justify-center bg-black/60 text-white rounded-full text-xs opacity-0 group-hover:opacity-100 transition-opacity cursor-pointer"
@@ -3502,7 +3502,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3502
3502
  &times;
3503
3503
  </button>
3504
3504
  </div>`})}
3505
- </div>`}function cV(e){return e.collections.length?u`<div class="field">
3505
+ </div>`}function vV(e){return e.collections.length?u`<div class="field">
3506
3506
  <label class="label">${e.labels.collectionsLabel}</label>
3507
3507
  <div class="flex flex-col gap-1">
3508
3508
  ${e.collections.map(t=>u`<label class="flex items-center gap-2 text-sm">
@@ -3515,7 +3515,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3515
3515
  <span>${t.title}</span>
3516
3516
  </label>`)}
3517
3517
  </div>
3518
- </div>`:m}function lV(e){return u`<form
3518
+ </div>`:m}function yV(e){return u`<form
3519
3519
  class="flex flex-col gap-4 max-w-2xl"
3520
3520
  @submit=${t=>e.handleSubmit(t)}
3521
3521
  >
@@ -3590,7 +3590,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3590
3590
 
3591
3591
  <div class="field">
3592
3592
  <label class="label">${e.labels.mediaLabel}</label>
3593
- ${sV(e)}
3593
+ ${_V(e)}
3594
3594
  <button
3595
3595
  type="button"
3596
3596
  class="btn-outline text-sm"
@@ -3636,7 +3636,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3636
3636
  ${e.labels.pinnedLabel}
3637
3637
  </label>
3638
3638
 
3639
- ${cV(e)}
3639
+ ${vV(e)}
3640
3640
 
3641
3641
  <div class="flex gap-2">
3642
3642
  <button type="submit" class="btn" ?disabled=${e._loading}>
@@ -3686,7 +3686,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3686
3686
  ${e.labels.mediaDialogLoading}
3687
3687
  </p>
3688
3688
  </div>
3689
- </dialog>`}var uV={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},dV={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function fV(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var pV=class e extends _{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...dV},this.initial={...uV},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=fV(this.labels,{...dV})),typeof this.initial==`string`&&(this.initial=fV(this.initial,{...uV})),typeof this.collections==`string`&&(this.collections=fV(this.collections,[])),typeof this.media==`string`&&(this.media=fV(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??uV;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=JT({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return lV(this)}};customElements.define(`jant-post-form`,pV);function mV(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function hV(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function gV(e){let t=e,n=t.detail;if(!n)return;let r=mV(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await fe(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await fe(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let o=w(t,`status`),s=w(t,`url`);if(o===`redirect`&&s){r.clearDirty(),h(i),window.location.href=s;return}a(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await fe(e),i=w(t,`status`),o=w(t,`url`);if(i===`redirect`&&o){r.clearDirty(),h(n.messages.success),window.location.href=o;return}r.clearDirty(),a(n.messages.success)}catch(e){a(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function _V(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=mV(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&hV(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),hV(t,!1)):(r.add(n),hV(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,gV),document.addEventListener(`jant:post-load-media`,_V);var{I:vV}=i,yV=e=>e,bV=()=>document.createComment(``),xV=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new vV(r.insertBefore(bV(),i),r.insertBefore(bV(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=yV(e).nextSibling;yV(r).insertBefore(e,i),e=t}}}return n},SV=(e,t,n=e)=>(e._$AI(t,n),e),CV={},wV=(e,t=CV)=>e._$AH=t,TV=e=>e._$AH,EV=e=>{e._$AR(),e._$AA.remove()},DV=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},OV=p(class extends x{constructor(e){if(super(e),e.type!==c.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=TV(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,f=0,p=i.length-1,m=0,h=a.length-1;for(;f<=p&&m<=h;)if(i[f]===null)f++;else if(i[p]===null)p--;else if(s[f]===o[m])c[m]=SV(i[f],a[m]),f++,m++;else if(s[p]===o[h])c[h]=SV(i[p],a[h]),p--,h--;else if(s[f]===o[h])c[h]=SV(i[f],a[h]),xV(e,c[h+1],i[f]),f++,h--;else if(s[p]===o[m])c[m]=SV(i[p],a[m]),xV(e,i[f],i[p]),p--,m++;else if(l===void 0&&(l=DV(o,m,h),u=DV(s,f,p)),l.has(s[f]))if(l.has(s[p])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=xV(e,i[f]);SV(t,a[m]),c[m]=t}else c[m]=SV(n,a[m]),xV(e,i[f],n),i[t]=null;m++}else EV(i[p]),p--;else EV(i[f]),f++;for(;m<=h;){let t=xV(e,c[h+1]);SV(t,a[m]),c[m++]=t}for(;f<=p;){let e=i[f++];e!==null&&EV(e)}return this.ut=o,wV(e,c),d}}),kV=class extends _{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{if(!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore)return;let t=e;t.isComposing||t.keyCode===229||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...FO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=LO(e)},onEnd:e=>{let t=e.to,n=e.from,r=n!==t,i=t.id===`nav-items-header`?`header`:`more`,o=this.querySelector(`#nav-items-header`),s=this.querySelector(`#nav-items-more`),c=e.item?.dataset?.navId;if(!c||!o||!s){this.#r=null;return}let l=IO(o,`[data-nav-id]`,`navId`),u=IO(s,`[data-nav-id]`,`navId`);r?(e.item.parentNode?.removeChild(e.item),this.#r?n.insertBefore(e.item,this.#r):e.oldIndex!=null&&e.oldIndex<n.children.length?n.insertBefore(e.item,n.children[e.oldIndex]??null):n.appendChild(e.item)):RO(t,e,this.#r),this.#r=null,this.#c();let d=[...new Set([...l,...u])],f=new Map(this._items.map(e=>[e.id,e.id===c?{...e,placement:i}:{...e}])),p=d.map(e=>f.get(e)).filter(e=>e!==void 0),m=this._items.filter(e=>!d.includes(e.id)).map(e=>e.id===c?{...e,placement:i}:{...e});this._items=[...p,...m];let{movedId:h,afterId:g,beforeId:_}=BO(i===`header`?l:u,e.newIndex);h&&(r?fetch(`/api/nav-items/${c}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({placement:i})}).then(async e=>e.ok?(await fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})})).ok:!1).then(e=>{e?a(this.labels.placementSaved):a(this.labels.saveFailed,`error`)}):fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)}))}}}#d(e){this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url)}#f(e){let t=this._editLabel.trim();if(!t&&e.type!==`system`){a(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}async#p(e){await De({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,placement:`header`})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#h(e){if(!(!e||this._addingCollectionId)){this._addingCollectionId=e;try{let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`collection`,collectionId:e,placement:`header`})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,n],this.#a()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingCollectionId=null}}}#g(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#_(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#c(),this._items=this._items.filter(e=>e.id!==t.id)}}}catch{a(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}get#v(){return this._items.filter(e=>(e.placement??`header`)===`header`)}get#y(){return this._items.filter(e=>e.placement===`more`)}#b(){this._showPreviewMore=!1,document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#s)}#x(e){if(e.preventDefault(),e.stopPropagation(),this._showPreviewMore){this.#b();return}this._showPreviewMore=!0,document.addEventListener(`keydown`,this.#s),setTimeout(()=>{document.addEventListener(`click`,this.#o)})}#S(){let e=this.#v,t=this.#y;return u`
3689
+ </dialog>`}var bV={format:`note`,title:``,slug:``,body:``,url:``,quoteText:``,status:`published`,visibility:`public`,pinned:!1,rating:0,collectionIds:[],mediaIds:[]},xV={formatLabel:``,noteOption:``,linkOption:``,quoteOption:``,titleLabel:``,titlePlaceholder:``,slugLabel:``,slugPlaceholder:``,slugHelp:``,bodyLabel:``,bodyPlaceholder:``,urlLabel:``,urlPlaceholder:``,quoteTextLabel:``,quoteTextPlaceholder:``,mediaLabel:``,mediaAddButton:``,mediaRemoveButton:``,mediaEmptyLabel:``,statusLabel:``,statusPublished:``,statusDraft:``,visibilityLabel:``,visibilityPublic:``,visibilityHiddenFromLatest:``,pinnedLabel:``,collectionsLabel:``,submitLabel:``,cancelLabel:``,mediaDialogTitle:``,mediaDialogDone:``,mediaDialogLoading:``,submitSuccessMessage:``,submitErrorMessage:``,draftFallbackMessage:``};function SV(e,t){if(typeof e==`string`)try{return JSON.parse(e)}catch{return t}return e&&typeof e==`object`?e:t}var CV=class e extends _{static properties={labels:{type:Object},initial:{type:Object},collections:{type:Array},media:{type:Array},action:{type:String},cancelHref:{type:String,attribute:`cancel-href`},mediaPickerUrl:{type:String,attribute:`media-picker-url`},siteUrl:{type:String,attribute:`site-url`},isEdit:{type:Boolean,attribute:`is-edit`},_format:{state:!0},_title:{state:!0},_slug:{state:!0},_slugManuallyEdited:{state:!0},_body:{state:!0},_url:{state:!0},_quoteText:{state:!0},_status:{state:!0},_visibility:{state:!0},_pinned:{state:!0},_rating:{state:!0},_collectionIds:{state:!0},_mediaIds:{state:!0},_loading:{state:!0}};_editor=null;_bodyJson=null;#e=!1;#t=!1;#n=e=>{this.#t&&(e.preventDefault(),e.returnValue=``)};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.labels={...xV},this.initial={...bV},this.collections=[],this.media=[],this.action=``,this.cancelHref=`/`,this.mediaPickerUrl=``,this.siteUrl=``,this.isEdit=!1,this._format=`note`,this._title=``,this._slug=``,this._slugManuallyEdited=!1,this._body=``,this._url=``,this._quoteText=``,this._status=`published`,this._visibility=`public`,this._pinned=!1,this._rating=0,this._collectionIds=[],this._mediaIds=[],this._loading=!1}willUpdate(e){typeof this.labels==`string`&&(this.labels=SV(this.labels,{...xV})),typeof this.initial==`string`&&(this.initial=SV(this.initial,{...bV})),typeof this.collections==`string`&&(this.collections=SV(this.collections,[])),typeof this.media==`string`&&(this.media=SV(this.media,[])),(!this.#e||e.has(`initial`))&&this.#i()}set loading(e){this._loading=e}get loading(){return this._loading}set mediaIds(e){this._mediaIds=[...e]}get mediaIds(){return[...this._mediaIds]}get#r(){return this.querySelector(`#post-media-picker`)}connectedCallback(){super.connectedCallback(),window.addEventListener(`beforeunload`,this.#n)}disconnectedCallback(){super.disconnectedCallback(),window.removeEventListener(`beforeunload`,this.#n),this._editor?.destroy(),this._editor=null,this.closeMediaPicker()}#i(){let e=this.initial??bV;if(this._format=e.format??`note`,this._title=e.title??``,this._slug=e.slug??``,this._slugManuallyEdited=!!e.slug,this._body=e.body??``,this._url=e.url??``,this._quoteText=e.quoteText??``,this._status=e.status??`published`,this._visibility=e.visibility??`public`,this._pinned=!!e.pinned,this._rating=e.rating??0,this._collectionIds=[...e.collectionIds??[]],this._mediaIds=[...e.mediaIds??[]],this.#e=!0,this._body&&this._body.startsWith(`{`))try{this._bodyJson=JSON.parse(this._body)}catch{this._bodyJson=null}else this._bodyJson=null}initEditor(){if(this._editor)return;let e=this.querySelector(`.post-form-tiptap-body`);e&&(this._editor=rE({element:e,placeholder:this.labels.bodyPlaceholder??`Write something…`,content:this._bodyJson,onUpdate:e=>{this._bodyJson=e,this._body=JSON.stringify(e)},pasteMedia:{shouldInsertInline:e=>e.type.startsWith(`image/`)}}))}static#a=new Set([`_format`,`_title`,`_slug`,`_body`,`_url`,`_quoteText`,`_status`,`_visibility`,`_pinned`,`_rating`,`_collectionIds`,`_mediaIds`]);updated(t){if(super.updated(t),this._editor||this.initEditor(),this.#e&&!t.has(`initial`)){for(let n of t.keys())if(e.#a.has(n)){this.#t=!0;break}}}clearDirty(){this.#t=!1}handleInput(e,t){this[e]=t.target.value}handleTitleInput(e){let t=e.target;this._title=t.value,this._slugManuallyEdited||(this._slug=t.value.toLowerCase().replace(/[^a-z0-9]+/g,`-`).replace(/^-|-$/g,``))}handleSlugInput(e){this._slug=e.target.value,this._slugManuallyEdited=!0}toggleCollection(e){this._collectionIds=this._collectionIds.includes(e)?this._collectionIds.filter(t=>t!==e):[...this._collectionIds,e]}removeMedia(e){this._mediaIds=this._mediaIds.filter(t=>t!==e)}openMediaPicker(){let e=this.#r;e&&(e.showModal(),this.dispatchEvent(new CustomEvent(`jant:post-load-media`,{bubbles:!0,detail:{endpoint:this.mediaPickerUrl,selectedIds:[...this._mediaIds]}})))}closeMediaPicker(){this.#r?.close()}handleSubmit(e){if(e.preventDefault(),this._loading||!this.action)return;let t=this._bodyJson?JSON.stringify(this._bodyJson):this._body,n={endpoint:this.action,isEdit:this.isEdit,data:{format:this._format,title:this._title.trim(),slug:this._slug.trim()||void 0,body:t,status:this._status,visibility:this._visibility,pinned:this._pinned,url:this._url.trim(),quoteText:this._quoteText.trim(),rating:this._rating,collectionIds:[...this._collectionIds],mediaIds:[...this._mediaIds]},messages:{success:this.labels.submitSuccessMessage,error:this.labels.submitErrorMessage}};this.dispatchEvent(new CustomEvent(`jant:post-submit`,{bubbles:!0,detail:n}))}render(){return yV(this)}};customElements.define(`jant-post-form`,CV);function wV(e){return e instanceof HTMLElement&&e.tagName===`JANT-POST-FORM`?e:e instanceof HTMLElement?e.closest(`jant-post-form`):document.querySelector(`jant-post-form`)}function TV(e,t){e.classList.toggle(`ring-2`,t),e.classList.toggle(`ring-primary`,t),e.classList.toggle(`border-primary`,t)}async function EV(e){let t=e,n=t.detail;if(!n)return;let r=wV(t.target);if(!(!r||!n.endpoint)){r.loading=!0;try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(n.data)});if(!e.ok){let t=n.messages.error;try{let n=await fe(e);t=w(n,`error`)??w(n,`message`)??t}catch{}if(n.data.status===`published`&&!n.isEdit)try{let e=await fetch(n.endpoint,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({...n.data,status:`draft`})});if(e.ok){let t=await fe(e),n=r.getAttribute(`labels`),i=`Couldn't publish. Saved as draft.`;if(n)try{let e=JSON.parse(n);e.draftFallbackMessage&&(i=e.draftFallbackMessage)}catch{}let o=w(t,`status`),s=w(t,`url`);if(o===`redirect`&&s){r.clearDirty(),h(i),window.location.href=s;return}a(i),r.clearDirty();return}}catch{}throw Error(t)}let t=await fe(e),i=w(t,`status`),o=w(t,`url`);if(i===`redirect`&&o){r.clearDirty(),h(n.messages.success),window.location.href=o;return}r.clearDirty(),a(n.messages.success)}catch(e){a(e instanceof Error&&e.message?e.message:n.messages.error,`error`)}finally{r.loading=!1}}}async function DV(e){let t=e,n=t.detail;if(!n?.endpoint)return;let r=document.getElementById(`post-media-grid`),i=wV(t.target);if(!r||!i)return;try{r.innerHTML=`<p class="text-muted-foreground text-sm col-span-4">Loading...</p>`,r.innerHTML=await(await fetch(n.endpoint,{headers:{Accept:`text/html`}})).text()}catch{r.innerHTML=`<p class="text-red-500 text-sm col-span-4">Failed to load media.</p>`;return}let a=new Set(n.selectedIds);r.querySelectorAll(`[data-media-id]`).forEach(e=>{let t=e.dataset.mediaId;t&&TV(e,a.has(t))}),r.onclick=e=>{let t=e.target.closest(`[data-media-id]`);if(!t)return;let n=t.dataset.mediaId;if(!n)return;let r=new Set(i.mediaIds);r.has(n)?(r.delete(n),TV(t,!1)):(r.add(n),TV(t,!0)),i.mediaIds=[...r]}}document.addEventListener(`jant:post-submit`,EV),document.addEventListener(`jant:post-load-media`,DV);var{I:OV}=i,kV=e=>e,AV=()=>document.createComment(``),jV=(e,t,n)=>{let r=e._$AA.parentNode,i=t===void 0?e._$AB:t._$AA;if(n===void 0)n=new OV(r.insertBefore(AV(),i),r.insertBefore(AV(),i),e,e.options);else{let t=n._$AB.nextSibling,a=n._$AM,o=a!==e;if(o){let t;n._$AQ?.(e),n._$AM=e,n._$AP!==void 0&&(t=e._$AU)!==a._$AU&&n._$AP(t)}if(t!==i||o){let e=n._$AA;for(;e!==t;){let t=kV(e).nextSibling;kV(r).insertBefore(e,i),e=t}}}return n},MV=(e,t,n=e)=>(e._$AI(t,n),e),NV={},PV=(e,t=NV)=>e._$AH=t,FV=e=>e._$AH,IV=e=>{e._$AR(),e._$AA.remove()},LV=(e,t,n)=>{let r=new Map;for(let i=t;i<=n;i++)r.set(e[i],i);return r},RV=p(class extends x{constructor(e){if(super(e),e.type!==c.CHILD)throw Error(`repeat() can only be used in text expressions`)}dt(e,t,n){let r;n===void 0?n=t:t!==void 0&&(r=t);let i=[],a=[],o=0;for(let t of e)i[o]=r?r(t,o):o,a[o]=n(t,o),o++;return{values:a,keys:i}}render(e,t,n){return this.dt(e,t,n).values}update(e,[t,n,r]){let i=FV(e),{values:a,keys:o}=this.dt(t,n,r);if(!Array.isArray(i))return this.ut=o,a;let s=this.ut??=[],c=[],l,u,f=0,p=i.length-1,m=0,h=a.length-1;for(;f<=p&&m<=h;)if(i[f]===null)f++;else if(i[p]===null)p--;else if(s[f]===o[m])c[m]=MV(i[f],a[m]),f++,m++;else if(s[p]===o[h])c[h]=MV(i[p],a[h]),p--,h--;else if(s[f]===o[h])c[h]=MV(i[f],a[h]),jV(e,c[h+1],i[f]),f++,h--;else if(s[p]===o[m])c[m]=MV(i[p],a[m]),jV(e,i[f],i[p]),p--,m++;else if(l===void 0&&(l=LV(o,m,h),u=LV(s,f,p)),l.has(s[f]))if(l.has(s[p])){let t=u.get(o[m]),n=t===void 0?null:i[t];if(n===null){let t=jV(e,i[f]);MV(t,a[m]),c[m]=t}else c[m]=MV(n,a[m]),jV(e,i[f],n),i[t]=null;m++}else IV(i[p]),p--;else IV(i[f]),f++;for(;m<=h;){let t=jV(e,c[h+1]);MV(t,a[m]),c[m++]=t}for(;f<=p;){let e=i[f++];e!==null&&IV(e)}return this.ut=o,PV(e,c),d}}),zV=class extends _{static properties={items:{type:Array},labels:{type:Object},systemNavItems:{type:Array,attribute:`system-nav-items`},collections:{type:Array},siteName:{type:String,attribute:`site-name`},_items:{state:!0},_editingId:{state:!0},_editLabel:{state:!0},_editUrl:{state:!0},_togglingKeys:{state:!0},_showLinkForm:{state:!0},_newLinkLabel:{state:!0},_newLinkUrl:{state:!0},_addingLink:{state:!0},_showPreviewMore:{state:!0},_addingCollectionId:{state:!0},_showCollectionPicker:{state:!0}};#e=null;#t=null;#n=!1;#r=null;#i=()=>{this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)};#a=()=>{this._showCollectionPicker=!1,document.removeEventListener(`click`,this.#a)};#o=e=>{e.target instanceof Node&&(this.querySelector(`[data-preview-more]`)?.contains(e.target)||this.#b())};#s=e=>{if(!(`key`in e)||e.key!==`Escape`||!this._showPreviewMore)return;let t=e;t.isComposing||t.keyCode===229||(e.preventDefault(),this.#b(),this.querySelector(`[data-preview-more-trigger]`)?.focus())};createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this.items=[],this.labels={},this.systemNavItems=[],this.collections=[],this.siteName=``,this._items=[],this._editingId=null,this._editLabel=``,this._editUrl=``,this._togglingKeys=new Set,this._showLinkForm=!1,this._newLinkLabel=``,this._newLinkUrl=``,this._addingLink=!1,this._showPreviewMore=!1,this._addingCollectionId=null,this._showCollectionPicker=!1}update(e){(!this.#n||e.has(`items`))&&(this._items=[...this.items??[]],this.#n=!0),super.update(e)}updated(){this._showPreviewMore&&this.#y.length===0&&this.#b(),this.#l()}disconnectedCallback(){super.disconnectedCallback(),this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null,document.removeEventListener(`click`,this.#i),document.removeEventListener(`click`,this.#a),this.#b()}#c(){this.#e?.destroy(),this.#e=null,this.#t?.destroy(),this.#t=null}#l(){let e=this.querySelector(`#nav-items-header`),t=this.querySelector(`#nav-items-more`);e&&!this.#e&&(this.#e=H.create(e,this.#u())),t&&!this.#t&&(this.#t=H.create(t,this.#u()))}#u(){return{...WO,animation:150,handle:`[data-drag-handle]`,draggable:`[data-nav-id]`,group:`nav-items`,onStart:e=>{this.#r=KO(e)},onEnd:e=>{let t=e.to,n=e.from,r=n!==t,i=t.id===`nav-items-header`?`header`:`more`,o=this.querySelector(`#nav-items-header`),s=this.querySelector(`#nav-items-more`),c=e.item?.dataset?.navId;if(!c||!o||!s){this.#r=null;return}let l=GO(o,`[data-nav-id]`,`navId`),u=GO(s,`[data-nav-id]`,`navId`);r?(e.item.parentNode?.removeChild(e.item),this.#r?n.insertBefore(e.item,this.#r):e.oldIndex!=null&&e.oldIndex<n.children.length?n.insertBefore(e.item,n.children[e.oldIndex]??null):n.appendChild(e.item)):qO(t,e,this.#r),this.#r=null,this.#c();let d=[...new Set([...l,...u])],f=new Map(this._items.map(e=>[e.id,e.id===c?{...e,placement:i}:{...e}])),p=d.map(e=>f.get(e)).filter(e=>e!==void 0),m=this._items.filter(e=>!d.includes(e.id)).map(e=>e.id===c?{...e,placement:i}:{...e});this._items=[...p,...m];let{movedId:h,afterId:g,beforeId:_}=YO(i===`header`?l:u,e.newIndex);h&&(r?fetch(`/api/nav-items/${c}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({placement:i})}).then(async e=>e.ok?(await fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})})).ok:!1).then(e=>{e?a(this.labels.placementSaved):a(this.labels.saveFailed,`error`)}):fetch(`/api/nav-items/${h}/move`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({after:g??null,before:_??null})}).then(e=>{e.ok?a(this.labels.orderSaved):a(this.labels.saveFailed,`error`)}))}}}#d(e){this._editingId===e.id?this._editingId=null:(this._editingId=e.id,this._editLabel=e.label,this._editUrl=e.url)}#f(e){let t=this._editLabel.trim();if(!t&&e.type!==`system`){a(this.labels.labelRequired,`error`);return}let n={id:e.id,label:t,...e.type===`link`&&{url:this._editUrl.trim()}};this.dispatchEvent(new CustomEvent(`jant:nav-update`,{bubbles:!0,detail:n}))}async#p(e){await De({message:e.type===`collection`?this.labels.confirmDeleteCollection:this.labels.confirmDeleteLink,confirmLabel:e.type===`collection`?this.labels.remove:this.labels.delete,cancelLabel:this.labels.cancel,tone:`danger`})&&this.dispatchEvent(new CustomEvent(`jant:nav-delete`,{bubbles:!0,detail:{id:e.id}}))}async#m(){let e=this._newLinkLabel.trim(),t=this._newLinkUrl.trim();if(!e||!t){a(this.labels.labelAndUrlRequired,`error`);return}this._addingLink=!0;try{let n=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`link`,label:e,url:t,placement:`header`})});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json();this.#c(),this._items=[...this._items,r],this._newLinkLabel=``,this._newLinkUrl=``,this._showLinkForm=!1,document.removeEventListener(`click`,this.#i)}catch{a(this.labels.saveFailed,`error`)}finally{this._addingLink=!1}}async#h(e){if(!(!e||this._addingCollectionId)){this._addingCollectionId=e;try{let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`collection`,collectionId:e,placement:`header`})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,n],this.#a()}catch{a(this.labels.saveFailed,`error`)}finally{this._addingCollectionId=null}}}#g(e){return this._items.some(t=>t.type===`system`&&t.systemKey===e.key)}async#_(e,t){this._togglingKeys=new Set([...this._togglingKeys,e.key]);try{if(t){let t=await fetch(`/api/nav-items`,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({type:`system`,systemKey:e.key})});if(!t.ok)throw Error(`HTTP ${t.status}`);let n=await t.json();this.#c(),this._items=[...this._items,{...n,displayLabel:e.label}]}else{let t=this._items.find(t=>t.type===`system`&&t.systemKey===e.key);if(t){let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);this.#c(),this._items=this._items.filter(e=>e.id!==t.id)}}}catch{a(this.labels.saveFailed,`error`),this.requestUpdate()}finally{let t=new Set(this._togglingKeys);t.delete(e.key),this._togglingKeys=t}}get#v(){return this._items.filter(e=>(e.placement??`header`)===`header`)}get#y(){return this._items.filter(e=>e.placement===`more`)}#b(){this._showPreviewMore=!1,document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#s)}#x(e){if(e.preventDefault(),e.stopPropagation(),this._showPreviewMore){this.#b();return}this._showPreviewMore=!0,document.addEventListener(`keydown`,this.#s),setTimeout(()=>{document.addEventListener(`click`,this.#o)})}#S(){let e=this.#v,t=this.#y;return u`
3690
3690
  <div class="nav-preview">
3691
3691
  <div class="nav-preview-chrome">
3692
3692
  <div class="nav-preview-dots">
@@ -3698,7 +3698,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3698
3698
  <div class="site-header-top">
3699
3699
  <a href=${o(`/`)} class="site-logo">${this.siteName}</a>
3700
3700
  <nav class="site-header-nav">
3701
- ${OV(e,e=>e.id,(e,t)=>u`<a
3701
+ ${RV(e,e=>e.id,(e,t)=>u`<a
3702
3702
  class=${t===0?`site-header-link site-header-link-active`:`site-header-link`}
3703
3703
  >
3704
3704
  ${e.displayLabel??e.label}
@@ -3734,7 +3734,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
3734
3734
  aria-hidden=${this._showPreviewMore?`false`:`true`}
3735
3735
  @click=${e=>e.stopPropagation()}
3736
3736
  >
3737
- ${OV(t,e=>e.id,e=>u`
3737
+ ${RV(t,e=>e.id,e=>u`
3738
3738
  <span class="site-header-more-link">
3739
3739
  ${e.displayLabel??e.label}
3740
3740
  </span>
@@ -4112,14 +4112,14 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4112
4112
  ${this.labels.emptyState}
4113
4113
  </p>`:m}
4114
4114
  <div id="nav-items-header" class="nav-items-list">
4115
- ${OV(this.#v,e=>e.id,e=>this.#T(e))}
4115
+ ${RV(this.#v,e=>e.id,e=>this.#T(e))}
4116
4116
  </div>
4117
4117
  </section>
4118
4118
 
4119
4119
  <section class="mt-8">
4120
4120
  <h2 class="text-lg font-semibold mb-3">${this.labels.moreSection}</h2>
4121
4121
  <div id="nav-items-more" class="nav-items-list nav-items-list-drop">
4122
- ${this.#y.length>0?OV(this.#y,e=>e.id,e=>this.#T(e)):u`<p class="nav-items-empty-hint">
4122
+ ${this.#y.length>0?RV(this.#y,e=>e.id,e=>this.#T(e)):u`<p class="nav-items-empty-hint">
4123
4123
  ${this.labels.moreEmptyHint}
4124
4124
  </p>`}
4125
4125
  </div>
@@ -4127,7 +4127,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4127
4127
 
4128
4128
  ${this.#E()} ${this.#D()}
4129
4129
  ${this.#O()}
4130
- `}};customElements.define(`jant-nav-manager`,kV),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to delete. Please try again.`,`error`)}});var AV=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,jV=`M4 4 20 20`,MV=360,NV=12;function PV(e){let t=window.innerHeight-e.bottom-NV,n=e.top-NV;return t<MV&&n>t}function FV(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var IV=class extends _{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=PV(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{let t=e;if(!(t.isComposing||t.keyCode===229)&&t.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},a({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),a(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},a(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),a(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},a(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),a(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},a(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),a(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await De({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),FV(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),FV(n)}a(`Post deleted.`)}catch{a(`Could not delete post. Try again.`,`error`),e?.focus()}}async#S(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}}),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();let r=(await t.json()).collections??[],i=this._postCollectionIds;n.ok&&(i=(await n.json()).collectionIds??[]),this.#t=$x(r,i),this._collections=r,this._postCollectionIds=i}catch{this._collections=this._collections??[],a(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}#C(e){if(!this._data)return;let t=this._data.id,n=this._postCollectionIds.includes(e);n?this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e):this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,a(n?`Removed from collection.`:`Added to collection.`),n?fetch(`/api/collections/${e}/posts/${t}`,{method:`DELETE`}).then(e=>{if(!e.ok)throw Error();return this.#k()}).catch(()=>{this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]),a(`Could not remove from collection. Try again.`,`error`)}):fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:t})}).then(e=>{if(!e.ok){if(e.status===409)return this.#k();throw Error()}return this.#k()}).catch(()=>{this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),a(`Could not add to collection. Try again.`,`error`)})}#w(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#T(){this._addCollectionPanelOpen=!1,this.#r(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#E(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),await this.#k(),this.#e=!0,this.#T(),a(this.#D()?.createdLabel??`Collection created.`)}catch(e){a(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#D(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#O(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}async#k(){await document.querySelector(`jant-compose-dialog`)?.refreshCollections?.()}#A(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#j(){return u`<svg
4130
+ `}};customElements.define(`jant-nav-manager`,zV),document.addEventListener(`jant:nav-update`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`PUT`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify({label:t.label,...t.url!==void 0&&{url:t.url}})});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to save. Please try again.`,`error`)}}),document.addEventListener(`jant:nav-delete`,async e=>{let{detail:t}=e;if(t?.id)try{let e=await fetch(`/api/nav-items/${t.id}`,{method:`DELETE`,headers:{Accept:`application/json`}});if(!e.ok)throw Error(`HTTP ${e.status}`);window.location.reload()}catch{a(`Failed to delete. Please try again.`,`error`)}});var BV=`M12 3 10.1 10.1 3 12l7.1 1.9L12 21l1.9-7.1L21 12l-7.1-1.9Z`,VV=`M4 4 20 20`,HV=360,UV=12;function WV(e){let t=window.innerHeight-e.bottom-UV,n=e.top-UV;return t<HV&&n>t}function GV(e){let t=Array.from(e?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-item`));Array.from(t?.children??[]).find(e=>e instanceof HTMLElement&&e.classList.contains(`feed-divider`))?.remove()}var KV=class extends _{static properties={_open:{state:!0},_data:{state:!0},_x:{state:!0},_y:{state:!0},_openAbove:{state:!0},_view:{state:!0},_collections:{state:!0},_collectionsLoading:{state:!0},_collectionSearch:{state:!0},_postCollectionIds:{state:!0},_addCollectionPanelOpen:{state:!0}};#e=!1;#t=[];#n=!0;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._data=null,this._x=0,this._y=0,this._openAbove=!0,this._view=`menu`,this._collections=null,this._collectionsLoading=!1,this._collectionSearch=``,this._postCollectionIds=[],this._addCollectionPanelOpen=!1,this._triggerEl=null}connectedCallback(){super.connectedCallback(),document.addEventListener(`click`,this.#o),document.addEventListener(`keydown`,this.#a),window.addEventListener(`resize`,this.#i)}disconnectedCallback(){super.disconnectedCallback(),document.removeEventListener(`click`,this.#o),document.removeEventListener(`keydown`,this.#a),window.removeEventListener(`resize`,this.#i)}#r(){let e=this._triggerEl;if(!e?.isConnected){this._open&&this.#h({restoreFocus:!1});return}let t=e.getBoundingClientRect();this._openAbove=WV(t),this._x=window.scrollX+t.right,this._y=window.scrollY+(this._openAbove?t.top-6:t.bottom+6)}#i=()=>{!this._open||this._addCollectionPanelOpen||this.#r()};#a=e=>{let t=e;if(!(t.isComposing||t.keyCode===229)&&t.key===`Escape`){if(this._addCollectionPanelOpen){this.#T();return}let e=document.querySelector(`[data-collection-popover].open`);if(e){e.classList.remove(`open`);return}if(this._open){if(this._view!==`menu`){this.#p();return}this.#h()}}};#o=e=>{let t=e.target,n=t.closest(`[data-collection-popover-trigger]`);if(n){e.preventDefault(),e.stopPropagation();let t=n.parentElement?.querySelector(`[data-collection-popover]`);t&&t.classList.toggle(`open`);return}if(t.closest(`[data-collection-popover]`)||t.closest(`[data-collection-quick-dialog]`)||t.classList.contains(`collection-quick-dialog-backdrop`))return;let r=document.querySelector(`[data-collection-popover].open`);r&&r.classList.remove(`open`);let i=t.closest(`[data-post-menu-trigger]`);if(i){e.preventDefault(),e.stopPropagation();let t=i.closest(`article[data-post]`);if(!t)return;let n=t.dataset.postId;if(!n)return;if(this._open&&this._data?.id===n){this.#h();return}this._data={id:n,pinned:t.hasAttribute(`data-post-pinned`),pinnedInCollection:t.hasAttribute(`data-post-pinned-in-collection`),featured:t.hasAttribute(`data-post-featured`),visibility:t.dataset.postVisibility??`public`,isReply:t.hasAttribute(`data-post-reply`)},this._triggerEl=i,this.#n=!0,this.#r(),i.setAttribute(`aria-expanded`,`true`),this._view=`menu`,this._open=!0,this.#s(`[data-post-menu-item-primary]`);return}this._open&&t.closest?.(`[role='menu'], [data-collection-picker], [data-visibility-panel]`)||this._open&&this.#h({restoreFocus:!1})};#s(e){this.updateComplete.then(()=>{this.querySelector(e)?.focus()})}#c(){return Array.from(this.querySelectorAll(`.post-menu-picker-option`))}#l=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;if(e.key===`Enter`){e.preventDefault(),this.#h();return}if(e.key!==`ArrowDown`)return;let[t]=this.#c(),n=this.querySelector(`[data-post-menu-add-collection]`),r=t??n;r&&(e.preventDefault(),r.focus())};#u=(e,t)=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey)return;let n=this.#c(),r=e.currentTarget,i=r?n.indexOf(r):-1;if(e.key===`ArrowDown`){let t=this.querySelector(`[data-post-menu-add-collection]`),r=i>=0?n[i+1]??t:n[0];if(!r)return;e.preventDefault(),r.focus();return}if(e.key===`ArrowUp`){let t=this.querySelector(`.post-menu-picker-search input`),r=i>0?n[i-1]:t;if(!r)return;e.preventDefault(),r.focus();return}if(e.key===` `||e.key===`Spacebar`){e.preventDefault(),this.#C(t);return}e.key===`Enter`&&(e.preventDefault(),this.#h())};#d=(e,t)=>{e.detail!==0&&this.#C(t)};#f=e=>{if(e.defaultPrevented||e.isComposing||e.altKey||e.ctrlKey||e.metaKey||e.key!==`ArrowUp`)return;let t=this.#c(),n=this.querySelector(`.post-menu-picker-search input`),r=t.at(-1)??n;r&&(e.preventDefault(),r.focus())};#p(e=`[data-post-menu-item-primary]`){this._view=`menu`,this.#s(e)}#m(){this._data?.isReply||(this._view=`visibility`,this.#s(`[data-post-menu-visibility-current='true'], [data-post-menu-visibility-option]`))}#h(e={}){let t=e.restoreFocus??this.#n,n=this._triggerEl;if(n?.setAttribute(`aria-expanded`,`false`),this._triggerEl=null,this.#n=!0,this._open=!1,this._view=`menu`,this._addCollectionPanelOpen=!1,this._collectionSearch=``,this.#e){this.#e=!1,window.location.reload();return}t&&n?.focus()}openCollectionsForPost(e){let t=e.dataset.postId;if(!t)return;this._data={id:t,pinned:e.hasAttribute(`data-post-pinned`),pinnedInCollection:e.hasAttribute(`data-post-pinned-in-collection`),featured:e.hasAttribute(`data-post-featured`),visibility:e.dataset.postVisibility??`public`,isReply:e.hasAttribute(`data-post-reply`)};let n=e.querySelector(`[data-post-menu-trigger]`);n&&(this._triggerEl=n,this.#n=!1,this.#r(),n.setAttribute(`aria-expanded`,`true`)),this._open=!0,this.#S()}async#g(){if(!this._data)return;let e=this._data.id;this.#h({restoreFocus:!1});let t=document.getElementById(`compose-dialog`)?.querySelector(`jant-compose-dialog`);t&&await t.openEdit(e)}#_(e){if(!this._data)return;let t=this._data.id,n=this._data.visibility,r=document.querySelector(`article[data-post-id="${t}"]`);r&&(r.dataset.postVisibility=e),this._data={...this._data,visibility:e},a({public:`Post made public.`,latest_hidden:`Hidden from Latest.`,private:`Post made private.`}[e]??`Visibility updated.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({visibility:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let e=document.querySelector(`article[data-post-id="${t}"]`);e&&(e.dataset.postVisibility=n),a(`Could not update visibility. Try again.`,`error`)})}#v(e){if(!this._data)return;let t=this._data.id,n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.setAttribute(`data-post-featured`,``):n.removeAttribute(`data-post-featured`)),this._data={...this._data,featured:e},a(e?`Added to Featured.`:`Removed from Featured.`),this.#h(),fetch(`/api/posts/${t}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({featured:e})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${t}"]`);n&&(e?n.removeAttribute(`data-post-featured`):n.setAttribute(`data-post-featured`,``)),a(`Could not update post. Try again.`,`error`)})}#y(){if(!this._data)return;let e=this._data.id,t=!this._data.pinned,n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.setAttribute(`data-post-pinned`,``):n.removeAttribute(`data-post-pinned`)),this._data={...this._data,pinned:t},a(t?`Post pinned.`:`Post unpinned.`),this.#h(),fetch(`/api/posts/${e}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify({pinned:t})}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let n=document.querySelector(`article[data-post-id="${e}"]`);n&&(t?n.removeAttribute(`data-post-pinned`):n.setAttribute(`data-post-pinned`,``)),a(`Could not update post. Try again.`,`error`)})}#b(){if(!this._data)return;let e=this._data.id,t=document.querySelector(`[data-collection-id]`)?.dataset.collectionId;if(!t)return;let n=!this._data.pinnedInCollection,r=document.querySelector(`article[data-post-id="${e}"]`);r&&(n?r.setAttribute(`data-post-pinned-in-collection`,``):r.removeAttribute(`data-post-pinned-in-collection`)),this._data={...this._data,pinnedInCollection:n},a(n?`Pinned in collection.`:`Unpinned from collection.`),this.#h();let i=n?`PUT`:`DELETE`;fetch(`/api/collections/${t}/posts/${e}/pin`,{method:i}).then(e=>{if(!e.ok)throw Error()}).catch(()=>{let t=document.querySelector(`article[data-post-id="${e}"]`);t&&(n?t.removeAttribute(`data-post-pinned-in-collection`):t.setAttribute(`data-post-pinned-in-collection`,``)),a(`Could not update pin. Try again.`,`error`)})}async#x(){if(!this._data)return;let e=this._triggerEl;if(this.#h({restoreFocus:!1}),!await De({message:`Delete this post permanently? This can't be undone.`,confirmLabel:`Delete`,cancelLabel:`Cancel`,tone:`danger`})){e?.focus();return}try{if(!(await fetch(`/api/posts/${this._data.id}`,{method:`DELETE`})).ok)throw Error();let e=document.querySelector(`article[data-post-id="${this._data.id}"]`),t=e?.closest(`.thread-item`),n=t?.closest(`.thread-group`);if(t&&n){if(t.remove(),n.querySelectorAll(`.thread-item:not(.thread-item-gap)`).length===0){let e=n.closest(`.feed-item`),t=e?.parentElement??null;(e??n).remove(),GV(t)}}else{let t=e?.closest(`.feed-item`),n=t?.parentElement??null;(t??e)?.remove(),GV(n)}a(`Post deleted.`)}catch{a(`Could not delete post. Try again.`,`error`),e?.focus()}}async#S(){if(!this._data)return;let e=this._data.id;this._view=`collections`,this._collectionSearch=``,this._collectionsLoading=!0,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`);try{let[t,n]=await Promise.all([fetch(`/api/collections?view=compose`,{cache:`no-store`,headers:{Accept:`application/json`}}),fetch(`/api/posts/${e}`)]);if(!t.ok)throw Error();let r=(await t.json()).collections??[],i=this._postCollectionIds;n.ok&&(i=(await n.json()).collectionIds??[]),this.#t=$x(r,i),this._collections=r,this._postCollectionIds=i}catch{this._collections=this._collections??[],a(`Could not load collections.`,`error`)}this._collectionsLoading=!1,this.#s(`.post-menu-picker-search input, .post-menu-picker-option, [data-post-menu-add-collection]`)}#C(e){if(!this._data)return;let t=this._data.id,n=this._postCollectionIds.includes(e);n?this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e):this._postCollectionIds=[...this._postCollectionIds,e],this.#e=!0,a(n?`Removed from collection.`:`Added to collection.`),n?fetch(`/api/collections/${e}/posts/${t}`,{method:`DELETE`}).then(e=>{if(!e.ok)throw Error();return this.#k()}).catch(()=>{this._postCollectionIds.includes(e)||(this._postCollectionIds=[...this._postCollectionIds,e]),a(`Could not remove from collection. Try again.`,`error`)}):fetch(`/api/collections/${e}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:t})}).then(e=>{if(!e.ok){if(e.status===409)return this.#k();throw Error()}return this.#k()}).catch(()=>{this._postCollectionIds=this._postCollectionIds.filter(t=>t!==e),a(`Could not add to collection. Try again.`,`error`)})}#w(){this._addCollectionPanelOpen=!0,this.updateComplete.then(()=>{let e=this.querySelector(`[data-collection-quick-dialog] [data-collection-title-input]`);e?.focus(),e?.select()})}#T(){this._addCollectionPanelOpen=!1,this.#r(),this.updateComplete.then(()=>{(this.querySelector(`[data-post-menu-add-collection]`)??this._triggerEl)?.focus()})}async#E(e){let t=e;t.stopPropagation();let n=t.detail;if(!n)return;let r=this.querySelector(`jant-collection-form`);r&&(r.loading=!0);try{let e=await fetch(`/api/collections`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(n.data)}),t=await e.json().catch(()=>null);if(!e.ok)throw Error(t?.error||`Could not create collection. Try again.`);if(!t?.id||!t.title||!t.slug)throw Error(`Could not create collection. Try again.`);let r={id:t.id,title:t.title,slug:t.slug};this._collections=[...this._collections??[],r],this._data&&(await fetch(`/api/collections/${t.id}/posts`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({postId:this._data.id})}),this._postCollectionIds=[...this._postCollectionIds,t.id]),await this.#k(),this.#e=!0,this.#T(),a(this.#D()?.createdLabel??`Collection created.`)}catch(e){a(e instanceof Error?e.message:`Could not create collection. Try again.`,`error`)}finally{r&&(r.loading=!1)}}#D(){return document.querySelector(`jant-compose-dialog`)?.labels?.collectionFormLabels??null}#O(){return document.querySelector(`jant-compose-dialog`)?.labels?.addCollection??`Add Collection`}async#k(){await document.querySelector(`jant-compose-dialog`)?.refreshCollections?.()}#A(e){switch(e){case`private`:return`Private`;case`latest_hidden`:return`Hidden from Latest`;default:return`Public`}}#j(){return u`<svg
4131
4131
  xmlns="http://www.w3.org/2000/svg"
4132
4132
  viewBox="0 0 24 24"
4133
4133
  fill="none"
@@ -4147,7 +4147,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4147
4147
  stroke-linecap="round"
4148
4148
  stroke-linejoin="round"
4149
4149
  >
4150
- <path d=${AV} />
4150
+ <path d=${BV} />
4151
4151
  </svg>`}#N(){return u`<svg
4152
4152
  xmlns="http://www.w3.org/2000/svg"
4153
4153
  viewBox="0 0 24 24"
@@ -4158,8 +4158,8 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4158
4158
  stroke-linecap="round"
4159
4159
  stroke-linejoin="round"
4160
4160
  >
4161
- <path d=${AV} />
4162
- <path d=${jV} />
4161
+ <path d=${BV} />
4162
+ <path d=${VV} />
4163
4163
  </svg>`}#P(){return u`<svg
4164
4164
  xmlns="http://www.w3.org/2000/svg"
4165
4165
  viewBox="0 0 24 24"
@@ -4604,7 +4604,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4604
4604
  </div>
4605
4605
  `}
4606
4606
  ${this._addCollectionPanelOpen?this.#H():m}
4607
- `}};customElements.define(`jant-post-menu`,IV);var LV=e=>{if(!e)return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``};try{return JSON.parse(e)}catch{return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``}}};document.querySelectorAll(`[data-collection-page-actions]`).forEach(e=>{if(e.dataset.collectionPageActionsInitialized===`true`)return;let t=LV(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||_B(),i=e.querySelector(`[data-collection-page-action='toggle-menu']`),o=e.querySelector(`[data-collection-page-menu]`);if(!n||!i||!o)return;let s=(e=!1)=>{o.hidden||(o.hidden=!0,i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},c=(e=!1)=>{o.hidden=!1,i.setAttribute(`aria-expanded`,`true`),e&&o.querySelector(`[role='menuitem']`)?.focus()},l=async()=>{if(s(!1),await De({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);a(t.deleted),window.location.href=r}catch{a(t.saveFailed,`error`)}};i.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),o.hidden){c(!1);return}s(!1)}),i.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`)&&(e.preventDefault(),o.hidden?c(!0):s(!1)),e.key===`Escape`&&(e.preventDefault(),s(!0))}),o.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),s(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let r=n.closest(`[data-collection-page-action]`);!r||!e.contains(r)||r.dataset.collectionPageAction===`delete`&&(t.preventDefault(),l())}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||s(!1))}),e.dataset.collectionPageActionsInitialized=`true`});function RV(e=document){e.querySelectorAll(`[data-custom-url-actions]`).forEach(e=>{if(e.dataset.customUrlActionsInitialized===`true`)return;let t=e.querySelector(`[data-custom-url-action='toggle-menu']`),n=e.querySelector(`[data-custom-url-menu]`);if(!(t instanceof HTMLButtonElement)||!n)return;let r=(e=!1)=>{n.hidden||(n.hidden=!0,t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},i=(r=!1)=>{document.dispatchEvent(new CustomEvent(`jant:custom-url-menu`,{detail:{source:e}})),n.hidden=!1,t.setAttribute(`aria-expanded`,`true`),r&&n.querySelector(`[role='menuitem']`)?.focus()};t.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),n.hidden){i(!1);return}r(!1)}),t.addEventListener(`keydown`,e=>{if(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`){e.preventDefault(),n.hidden?i(!0):r(!1);return}e.key===`Escape`&&(e.preventDefault(),r(!0))}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),r(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let i=n.closest(`[data-custom-url-action]`);!i||!e.contains(i)||i.dataset.customUrlAction===`delete`&&r(!1)}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||r(!1))}),document.addEventListener(`jant:custom-url-menu`,t=>{t.detail?.source!==e&&r(!1)}),e.dataset.customUrlActionsInitialized=`true`})}RV();var zV=`xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"`,BV={post:`<svg ${zV}><path d="M8 2v4"/><path d="M12 2v4"/><path d="M16 2v4"/><rect width="16" height="18" x="4" y="4" rx="2"/><path d="M8 10h6"/><path d="M8 14h8"/><path d="M8 18h5"/></svg>`,collection:`<svg ${zV} viewBox="0 0 16 16" stroke-width="1.35"><rect x="3" y="5.05" width="10" height="8.15" rx="2.2"/><path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85"/></svg>`,system:`<svg ${zV}><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>`,command:`<svg ${zV}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,search:`<svg ${zV}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`},VV=5;function HV(e){try{let t=globalThis.localStorage.getItem(e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e):[]}catch{return[]}}function UV(e,t){let n=HV(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,VV)))}var WV=`jant:nav-history`,GV=`jant:search-history`,KV=[{title:`Home`,path:`/`,type:`system`},{title:`Featured`,path:`/featured`,type:`system`},{title:`Latest`,path:`/latest`,type:`system`},{title:`Archive`,path:`/archive`,type:`system`},{title:`Collections`,path:`/collections`,type:`system`},{title:`Settings`,path:`/settings`,type:`system`},{title:`General`,path:`/settings/general`,type:`system`},{title:`Navigation`,path:`/settings/navigation`,type:`system`},{title:`Appearance`,path:`/settings/appearance/color-theme`,type:`system`},{title:`Custom URLs`,path:`/settings/custom-urls`,type:`system`},{title:`API Tokens`,path:`/settings/api-tokens`,type:`system`},{title:`Sessions`,path:`/settings/sessions`,type:`system`},{title:`Account`,path:`/settings/account`,type:`system`}],qV=[{label:`New Post`,icon:BV.command,action:()=>void QR()}],JV=class extends _{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:`navigate`}get#r(){let e=Zx(this._query),t=[...this.#e??[],...KV];if(!e){let e=HV(WV);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Xx([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Zx(this._query.slice(1));return qV.filter(t=>!e||t.label.toLowerCase().includes(e))}get#a(){let e=this.#n;if(e===`command`)return this.#i.map(e=>({label:e.label,icon:e.icon}));if(e===`search`){let e=this._query.slice(1).trim();return e?[{label:`Search for "${e}"`,icon:BV.search,searchQuery:e}]:HV(GV).map(e=>({label:e,icon:BV.search,searchQuery:e}))}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:BV[e.type]})),n=Zx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:BV.search,searchQuery:this._query.trim()}),t}#o(e){let t=this.#n;if(t===`command`){let t=this.#i[e];t&&(this.close(),t.action());return}if(t===`search`){let t=this.#a[e]?.searchQuery;t&&(UV(GV,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;UV(GV,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&(UV(WV,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{if(e.isComposing||e.keyCode===229)return;let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return m;let e=this.#a;return u`
4607
+ `}};customElements.define(`jant-post-menu`,KV);var qV=e=>{if(!e)return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``};try{return JSON.parse(e)}catch{return{edit:``,moreActions:``,deleteCollection:``,confirmDelete:``,cancel:``,saveFailed:``,deleted:``}}};document.querySelectorAll(`[data-collection-page-actions]`).forEach(e=>{if(e.dataset.collectionPageActionsInitialized===`true`)return;let t=qV(e.dataset.collectionPageLabels),n=e.dataset.collectionId,r=e.dataset.collectionPageRedirectUrl||DB(),i=e.querySelector(`[data-collection-page-action='toggle-menu']`),o=e.querySelector(`[data-collection-page-menu]`);if(!n||!i||!o)return;let s=(e=!1)=>{o.hidden||(o.hidden=!0,i.setAttribute(`aria-expanded`,`false`),e&&i.focus())},c=(e=!1)=>{o.hidden=!1,i.setAttribute(`aria-expanded`,`true`),e&&o.querySelector(`[role='menuitem']`)?.focus()},l=async()=>{if(s(!1),await De({message:t.confirmDelete,confirmLabel:t.deleteCollection,cancelLabel:t.cancel,tone:`danger`}))try{let e=await fetch(`/api/collections/${n}`,{method:`DELETE`});if(!e.ok)throw Error(`HTTP ${e.status}`);a(t.deleted),window.location.href=r}catch{a(t.saveFailed,`error`)}};i.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),o.hidden){c(!1);return}s(!1)}),i.addEventListener(`keydown`,e=>{(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`)&&(e.preventDefault(),o.hidden?c(!0):s(!1)),e.key===`Escape`&&(e.preventDefault(),s(!0))}),o.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),s(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let r=n.closest(`[data-collection-page-action]`);!r||!e.contains(r)||r.dataset.collectionPageAction===`delete`&&(t.preventDefault(),l())}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||s(!1))}),e.dataset.collectionPageActionsInitialized=`true`});function JV(e=document){e.querySelectorAll(`[data-custom-url-actions]`).forEach(e=>{if(e.dataset.customUrlActionsInitialized===`true`)return;let t=e.querySelector(`[data-custom-url-action='toggle-menu']`),n=e.querySelector(`[data-custom-url-menu]`);if(!(t instanceof HTMLButtonElement)||!n)return;let r=(e=!1)=>{n.hidden||(n.hidden=!0,t.setAttribute(`aria-expanded`,`false`),e&&t.focus())},i=(r=!1)=>{document.dispatchEvent(new CustomEvent(`jant:custom-url-menu`,{detail:{source:e}})),n.hidden=!1,t.setAttribute(`aria-expanded`,`true`),r&&n.querySelector(`[role='menuitem']`)?.focus()};t.addEventListener(`click`,e=>{if(e.preventDefault(),e.stopPropagation(),n.hidden){i(!1);return}r(!1)}),t.addEventListener(`keydown`,e=>{if(e.key===`Enter`||e.key===` `||e.key===`ArrowDown`){e.preventDefault(),n.hidden?i(!0):r(!1);return}e.key===`Escape`&&(e.preventDefault(),r(!0))}),n.addEventListener(`keydown`,e=>{e.key===`Escape`&&(e.preventDefault(),r(!0))}),e.addEventListener(`click`,t=>{let n=t.target;if(!n)return;let i=n.closest(`[data-custom-url-action]`);!i||!e.contains(i)||i.dataset.customUrlAction===`delete`&&r(!1)}),document.addEventListener(`click`,t=>{t.target instanceof Node&&(e.contains(t.target)||r(!1))}),document.addEventListener(`jant:custom-url-menu`,t=>{t.detail?.source!==e&&r(!1)}),e.dataset.customUrlActionsInitialized=`true`})}JV();var YV=`xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"`,XV={post:`<svg ${YV}><path d="M8 2v4"/><path d="M12 2v4"/><path d="M16 2v4"/><rect width="16" height="18" x="4" y="4" rx="2"/><path d="M8 10h6"/><path d="M8 14h8"/><path d="M8 18h5"/></svg>`,collection:`<svg ${YV} viewBox="0 0 16 16" stroke-width="1.35"><rect x="3" y="5.05" width="10" height="8.15" rx="2.2"/><path d="M5.1 5.05V4.2a1.1 1.1 0 0 1 1.1-1.1h3.6a1.1 1.1 0 0 1 1.1 1.1v.85"/></svg>`,system:`<svg ${YV}><path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/><circle cx="12" cy="12" r="3"/></svg>`,command:`<svg ${YV}><path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/></svg>`,search:`<svg ${YV}><circle cx="11" cy="11" r="8"/><path d="m21 21-4.3-4.3"/></svg>`},ZV=5;function QV(e){try{let t=globalThis.localStorage.getItem(e);if(!t)return[];let n=JSON.parse(t);return Array.isArray(n)?n.filter(e=>typeof e==`string`&&e):[]}catch{return[]}}function $V(e,t){let n=QV(e).filter(e=>e!==t);n.unshift(t),globalThis.localStorage.setItem(e,JSON.stringify(n.slice(0,ZV)))}var eH=`jant:nav-history`,tH=`jant:search-history`,nH=[{title:`Home`,path:`/`,type:`system`},{title:`Featured`,path:`/featured`,type:`system`},{title:`Latest`,path:`/latest`,type:`system`},{title:`Archive`,path:`/archive`,type:`system`},{title:`Collections`,path:`/collections`,type:`system`},{title:`Settings`,path:`/settings`,type:`system`},{title:`General`,path:`/settings/general`,type:`system`},{title:`Navigation`,path:`/settings/navigation`,type:`system`},{title:`Appearance`,path:`/settings/appearance/color-theme`,type:`system`},{title:`Custom URLs`,path:`/settings/custom-urls`,type:`system`},{title:`API Tokens`,path:`/settings/api-tokens`,type:`system`},{title:`Sessions`,path:`/settings/sessions`,type:`system`},{title:`Account`,path:`/settings/account`,type:`system`}],rH=[{label:`New Post`,icon:XV.command,action:()=>void sz()}],iH=class extends _{static properties={_open:{state:!0},_query:{state:!0},_selectedIndex:{state:!0},_loading:{state:!0}};#e=null;createRenderRoot(){return this.innerHTML=``,this}constructor(){super(),this._open=!1,this._query=``,this._selectedIndex=0,this._loading=!1}connectedCallback(){super.connectedCallback(),this.#t()}async#t(){if(!this.#e)try{let e=await fetch(`/api/palette`);e.ok?this.#e=(await e.json()).items:this.#e=[]}catch{this.#e=[]}}async open(){if(this._open)return;this.#e||(this._loading=!0,await this.#t(),this._loading=!1),this._open=!0,this._query=``,this._selectedIndex=0,await this.updateComplete;let e=this.querySelector(`.command-palette`);e&&!e.open&&e.showModal(),this.querySelector(`.command-palette-input`)?.focus()}close(){let e=this.querySelector(`.command-palette`);e?.open&&e.close(),this._open=!1,this._query=``,this._selectedIndex=0}get#n(){let e=this._query.charAt(0);return e===`>`||e===`>`?`command`:e===`?`||e===`?`?`search`:`navigate`}get#r(){let e=Zx(this._query),t=[...this.#e??[],...nH];if(!e){let e=QV(eH);if(e.length===0)return t;let n=new Set(e),r=[],i=[];for(let e of t)n.has(e.path)?r.push(e):i.push(e);return r.sort((t,n)=>e.indexOf(t.path)-e.indexOf(n.path)),[...r,...i]}return t.map((t,n)=>({item:t,index:n,rank:Xx([t.title,t.path],e)})).filter(e=>e.rank!==null).sort((e,t)=>e.rank-t.rank||e.index-t.index).map(e=>e.item)}get#i(){let e=Zx(this._query.slice(1));return rH.filter(t=>!e||t.label.toLowerCase().includes(e))}get#a(){let e=this.#n;if(e===`command`)return this.#i.map(e=>({label:e.label,icon:e.icon}));if(e===`search`){let e=this._query.slice(1).trim();return e?[{label:`Search for "${e}"`,icon:XV.search,searchQuery:e}]:QV(tH).map(e=>({label:e,icon:XV.search,searchQuery:e}))}let t=this.#r.map(e=>({label:e.title,secondary:(e.type,e.path),icon:XV[e.type]})),n=Zx(this._query);return t.length===0&&n&&t.push({label:`Search for "${this._query.trim()}"`,icon:XV.search,searchQuery:this._query.trim()}),t}#o(e){let t=this.#n;if(t===`command`){let t=this.#i[e];t&&(this.close(),t.action());return}if(t===`search`){let t=this.#a[e]?.searchQuery;t&&($V(tH,t),this.close(),window.location.href=`/search?q=${encodeURIComponent(t)}`);return}let n=this.#a[e];if(n?.searchQuery){let e=n.searchQuery;$V(tH,e),this.close(),window.location.href=`/search?q=${encodeURIComponent(e)}`;return}let r=this.#r[e];r&&($V(eH,r.path),this.close(),r.type===`system`?window.location.href=r.path:r.type===`collection`?window.location.href=`/collections/${r.path}`:window.location.href=`/${r.path}`)}#s=e=>{this._query=e.target.value,this._selectedIndex=0};#c=e=>{if(e.isComposing||e.keyCode===229)return;let t=this.#a;if(e.key===`ArrowDown`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex+1)%t.length:0,this.#f();return}if(e.key===`ArrowUp`){e.preventDefault(),this._selectedIndex=t.length>0?(this._selectedIndex-1+t.length)%t.length:0,this.#f();return}if(e.key===`Enter`){e.preventDefault(),this.#o(this._selectedIndex);return}if(e.key===`Tab`){e.preventDefault();return}if(e.key===`Escape`){e.preventDefault(),this.close();return}};#l=e=>{e.preventDefault(),this.close()};#u=e=>{e.target===e.currentTarget&&this.close()};#d(e){return()=>this.#o(e)}#f(){requestAnimationFrame(()=>{this.querySelector(`.command-palette-result-selected`)?.scrollIntoView({block:`nearest`})})}render(){if(!this._open)return m;let e=this.#a;return u`
4608
4608
  <dialog
4609
4609
  class="command-palette"
4610
4610
  @cancel=${this.#l}
@@ -4617,7 +4617,7 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4617
4617
  >
4618
4618
  <div class="command-palette-input-wrapper">
4619
4619
  <span class="command-palette-search-icon"
4620
- >${ke(BV.search)}</span
4620
+ >${ke(XV.search)}</span
4621
4621
  >
4622
4622
  <input
4623
4623
  type="text"
@@ -4666,4 +4666,4 @@ Check the discardedTracks field for more info.`)}return e}async execute(){if(!th
4666
4666
  `:this._query.trim()&&!this._loading?u`<div class="command-palette-empty">No results</div>`:m}
4667
4667
  </div>
4668
4668
  </dialog>
4669
- `}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,JV),document.addEventListener(`keydown`,e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.defaultPrevented||e.isComposing)return;e.preventDefault();let t=document.querySelector(`jant-command-palette`);if(t){if(t.querySelector(`dialog[open]`)){t.close();return}document.querySelector(`dialog[open]`)||t.open()}}),document.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof globalThis.Element)||!t.closest(`.site-header-search-link`)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0||e.defaultPrevented)return;let n=document.querySelector(`jant-command-palette`);n&&(document.querySelector(`dialog[open]`)||(e.preventDefault(),n.open()))}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),Ee(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));
4669
+ `}};customElements.get(`jant-command-palette`)||customElements.define(`jant-command-palette`,iH),document.addEventListener(`keydown`,e=>{if(e.key.toLowerCase()!==`k`||!(e.metaKey||e.ctrlKey)||e.altKey||e.shiftKey||e.defaultPrevented||e.isComposing)return;e.preventDefault();let t=document.querySelector(`jant-command-palette`);if(t){if(t.querySelector(`dialog[open]`)){t.close();return}document.querySelector(`dialog[open]`)||t.open()}}),document.addEventListener(`click`,e=>{let t=e.target;if(!(t instanceof globalThis.Element)||!t.closest(`.site-header-search-link`)||e.metaKey||e.ctrlKey||e.shiftKey||e.altKey||e.button!==0||e.defaultPrevented)return;let n=document.querySelector(`jant-command-palette`);n&&(document.querySelector(`dialog[open]`)||(e.preventDefault(),n.open()))}),document.querySelector(`jant-compose-fullscreen`)||document.body.appendChild(document.createElement(`jant-compose-fullscreen`)),Ee(),document.querySelector(`jant-command-palette`)||document.body.appendChild(document.createElement(`jant-command-palette`));