var A="2023-11-03",m=null,i=null,w=0,P=3,C=3,_=500,E=null,o=null,S=!1,k=!1,g=!1,f=0,d=[],p={},u=0,c=0;function a(t,e,r){postMessage({type:"DEBUG",fileId:i,level:t,msg:e,payload:r})}function $(){let t=Math.min(99,Math.round(u/c*100));postMessage({type:"PROGRESS",fileId:i,percent:t})}function B(){postMessage({type:"PROGRESS",fileId:i,percent:100}),postMessage({type:"DONE",fileId:i})}function U(t){postMessage({type:"ERROR",fileId:i,error:t})}function M(t){return new Promise(e=>setTimeout(e,t))}function x(t=2e3){if(!o)return!0;try{let r=new URLSearchParams(o).get("se");return r?Date.parse(r)-Date.now()<t:!0}catch{return!0}}async function I(){if(!i)throw new Error("fileId missing");g=!1,o=null,postMessage({type:"REFRESH_SAS",fileId:i});let t=0;for(;!o&&!g;){if(k)throw new Error("Canceled during SAS refresh");if(await M(60),t+=60,t>12e4)throw new Error("SAS refresh timeout")}if(g)throw new Error("SAS refresh failed")}function D(t){return btoa(t.toString().padStart(10,"0"))}onmessage=t=>{let e=t.data;switch(e.type){case"START":S=!1,k=!1,g=!1,m=e.file,i=e.fileId,w=e.chunkSize,P=e.concurrency,C=e.maxChunkRetries??3,_=e.retryDelayMs??500,E=e.initialUrl.split("?")[0],o=e.initialUrl.split("?")[1],v().catch(r=>U(String(r)));break;case"PAUSE":S=!0;break;case"RESUME":S=!1;break;case"CANCEL":k=!0;break;case"REFRESH_SAS_DONE":e.fileId===i&&(o=e.url.split("?")[1]??e.url);break;case"REFRESH_SAS_FAILED":e.fileId===i&&(g=!0);break}};async function v(){if(!m)throw new Error("No file");if(c=m.size,f=Math.ceil(c/w),d=Array.from({length:f},(t,e)=>D(e)),p={},d.forEach(t=>p[t]=0),u=0,a("info","upload-start",{size:c,chunks:f,newBlockIdExample:d[0]}),f===1)return z();if(await H(),u<c){let t=c-u;throw a("error",`Commit failed due to progress mismatch. Missing ${t} bytes.`,{bytesUploaded:u,totalBytes:c}),new Error("Commit failed: worker tracking mismatch. Not all blocks registered successfully.")}await F(),B()}async function z(){(!o||x())&&await I();let t=`${E}?${o}`;await new Promise((e,r)=>{let n=new XMLHttpRequest;n.open("PUT",t,!0),n.setRequestHeader("x-ms-blob-type","BlockBlob"),n.setRequestHeader("Content-Type",m.type||"application/octet-stream"),n.upload.onprogress=l=>{l.lengthComputable&&postMessage({type:"PROGRESS",fileId:i,percent:Math.round(l.loaded/l.total*100)})},n.onload=()=>n.status>=200&&n.status<300?e():r(n.responseText),n.onerror=()=>r("Network error"),n.send(m)}),B()}async function H(){let t=0,e=0;return new Promise((r,n)=>{let l=()=>{if(k)return n("Canceled");for(;!S&&e<P&&t<f;){let b=t++;e++,L(b).then(()=>{e--,t>=f&&e===0?r():l()}).catch(n)}};l()})}async function L(t){let e=0,r=d[t];for(;;){(!o||x())&&await I();try{await N(t,r);return}catch(n){if(e++,a("warn",`putBlock failed for chunk ${t}. Retrying (try ${e}/${C}).`,String(n)),e>C)throw new Error(`Chunk ${t} failed after max retries: ${String(n)}`);await M(_)}}}function N(t,e){return new Promise((r,n)=>{let l=t*w,b=Math.min(l+w,c),y=m.slice(l,b),s=new XMLHttpRequest;s.open("PUT",`${E}?${o}&comp=block&blockid=${encodeURIComponent(e)}`,!0),s.setRequestHeader("x-ms-version",A),s.upload.onprogress=h=>{if(!h.lengthComputable)return;let R=p[e],T=h.loaded-R;p[e]=h.loaded,u+=T,$()},s.onload=()=>{if(s.status>=200&&s.status<300){let h=p[e]||0,R=y.size-h;p[e]=y.size,u+=R,$(),a("info",`Chunk ${t} (${e}) successful. Size: ${y.size} bytes.`),r()}else a("error",`putBlock HTTP Error for chunk ${t} (${e})`,{status:s.status,response:s.responseText}),n(s.responseText||s.statusText)},s.onerror=()=>{a("error",`putBlock Network Error for chunk ${t} (${e})`),n("Network error")},s.send(y)})}async function F(){(!o||x())&&await I(),a("info","Waiting 3 seconds before commit for Azure state finalization..."),await M(3e3);let t=`<?xml version="1.0" encoding="utf-8"?>
<BlockList>
`+d.map(r=>`  <Latest>${r}</Latest>`).join(`
`)+`
</BlockList>`;a("info","Committing block list...",{totalBlocks:d.length});let e=await fetch(`${E}?${o}&comp=blocklist`,{method:"PUT",headers:{"Content-Type":"application/xml","x-ms-version":A},body:t});if(!e.ok){let r=await e.text();throw a("error","Commit failed!",{status:e.status,response:r}),new Error(r)}a("info","Commit successful!")}
