(globalThis.TURBOPACK||(globalThis.TURBOPACK=[])).push(["object"==typeof document?document.currentScript:void 0,86860,e=>{"use strict";var t,r,n,a="https://huggingface.co";async function s(e,t){let r=new o(e.url,e.status,e.headers.get("X-Request-Id")??t?.requestId);r.message=`Api error with status ${r.statusCode}${t?.message?`. ${t.message}`:""}`;let n=[`URL: ${r.url}`,r.requestId?`Request ID: ${r.requestId}`:void 0].filter(Boolean).join(". ");if(e.headers.get("Content-Type")?.startsWith("application/json")){let t=await e.json();r.message=t.error||t.message||r.message,t.error_description&&(r.message=r.message?r.message+`: ${t.error_description}`:t.error_description),r.data=t}else r.data={message:await e.text()};throw r.message+=`. ${n}`,r}var o=class extends Error{statusCode;url;requestId;data;constructor(e,t,r,n){super(n),this.statusCode=t,this.requestId=r,this.url=e}},i=class extends Error{};function l(e){if(!e.startsWith("hf_"))throw TypeError("Your access token must start with 'hf_'")}function h(e){return e.accessToken?(l(e.accessToken),e.accessToken):e.credentials?.accessToken?(l(e.credentials.accessToken),e.credentials.accessToken):void 0}function c(e){if("string"!=typeof e)return e;if(e.startsWith("model/")||e.startsWith("models/"))throw TypeError("A repo designation for a model should not start with 'models/', directly specify the model namespace / name");if(e.startsWith("space/"))throw TypeError("Spaces should start with 'spaces/', plural, not 'space/'");if(e.startsWith("dataset/"))throw TypeError("Datasets should start with 'datasets/', plural, not 'dataset/'");if(e.startsWith("bucket/"))throw TypeError("Buckets should start with 'buckets/', plural, not 'bucket/'");let t=e.split("/").length-1;if(e.startsWith("spaces/")){if(2!==t)throw TypeError("Space Id must include namespace and name of the space");return{type:"space",name:e.slice(7)}}if(e.startsWith("datasets/")){if(t>2)throw TypeError("Too many slashes in repo designation: "+e);return{type:"dataset",name:e.slice(9)}}if(e.startsWith("buckets/")){if(2!==t)throw TypeError("Bucket Id must include namespace and name of the bucket");return{type:"bucket",name:e.slice(8)}}if(t>1)throw TypeError("Too many slashes in repo designation: "+e);return{type:"model",name:e}}function f(e,t){if(isNaN(t)||t<1)throw RangeError("Invalid chunk size: "+t);return e.length?e.length<=t?[e]:Array(Math.ceil(e.length/t)).fill(0).map((e,t)=>t).map(r=>e.slice(r*t,(r+1)*t)):[]}async function d(e,t){let r=[],n=new Set,a=0;for(let s of e){let e=a++,o=s().then(t=>{r[e]=t,n.delete(o)});n.add(o),n.size>=t&&await Promise.race(n)}return await Promise.all(n),r}async function u(e,t){let r=[];for await(let n of e){let e=n().then(()=>{r.splice(r.indexOf(e),1)});r.push(e),r.length>=t&&await Promise.race(r)}await Promise.all(r)}async function*p(e){let t=[];function r(){let e,r,n=new Promise((t,n)=>{e=t,r=n});t.push({p:n,resolve:e,reject:r})}r();let n=Promise.resolve().then(()=>e(e=>{r(),t.at(-2)?.resolve({done:!1,value:e})},e=>{r(),t.at(-2)?.resolve({done:!0,value:e})},e=>t.shift()?.reject(e))).catch(e=>t.shift()?.reject(e));for(;;){let e=t[0];if(!e)throw Error("Logic error in eventGenerator, promises should never be empty");let r=await e.p;if(t.shift(),r.done)return await n,r.value;yield r.value}throw Error("Unreachable")}var g="u">typeof window&&void 0!==window.document,b="object"==typeof self&&self.constructor&&"DedicatedWorkerGlobalScope"===self.constructor.name,w=!(!g&&!b);async function m(){let t=await e.A(25667);return URL.createObjectURL(new Blob([t.createSHA256WorkerCode()]))}var y=[],x=new Set,k=new Promise(e=>{t=e});async function v(e){{let e=y.pop();if(e)return x.add(e),e}if(!e){let e=new Worker(await m());return x.add(e),e}if(e<=0)throw TypeError("Invalid webworker pool size: "+e);for(;x.size>=e;)await k;let t=new Worker(await m());return x.add(t),t}async function I(e,r){if(!r)return U(e);x.delete(e),y.push(e);let n=t;k=new Promise(e=>{t=e}),n()}function U(e){x.delete(e),e.terminate();let r=t;k=new Promise(e=>{t=e}),r()}async function*T(t,a){yield 0;let s="object"==typeof a?.useWebWorker&&a?.useWebWorker.minSize!==void 0?a.useWebWorker.minSize:1e7;if(t.size{t.push(e.toString(16).padStart(2,"0"))}),t.join("")}}(new Uint8Array(await globalThis.crypto.subtle.digest("SHA-256",t instanceof Blob?await t.arrayBuffer():t)));return yield 1,e}if(w){if(a?.useWebWorker)try{let e,r,n="object"==typeof a?.useWebWorker?a.useWebWorker.poolSize:void 0,s=await v(n),o=()=>{s.removeEventListener("message",e),s.removeEventListener("error",r)};return yield*p((i,l,h)=>{if(e=e=>{if(e.data.sha256)o(),I(s,n),l(e.data.sha256);else if(e.data.progress){i(e.data.progress);try{a.abortSignal?.throwIfAborted()}catch(e){o(),U(s),h(e)}}else o(),U(s),h(e)},r=e=>{o(),U(s),h(e.error)},a?.abortSignal){try{a.abortSignal?.throwIfAborted()}catch(e){o(),U(s),h(a.abortSignal.reason??new DOMException("Aborted","AbortError"));return}let e=()=>{o(),U(s),h(a.abortSignal?.reason??new DOMException("Aborted","AbortError")),a.abortSignal?.removeEventListener("abort",e)};a.abortSignal.addEventListener("abort",e)}s.addEventListener("message",e),s.addEventListener("error",r),s.postMessage({file:t})})}catch(e){console.warn("Failed to use web worker for sha256",e)}n||(n=await e.A(25667));let r=await n.createSHA256();r.init();let s=t.stream().getReader(),o=t.size,i=0;for(;;){let{done:e,value:t}=await s.read();if(e)break;r.update(t),i+=t.length,yield i/o,a?.abortSignal?.throwIfAborted()}return r.digest("hex")}return r||(r=await e.A(22519)),yield*r.sha256Node(t,{abortSignal:a?.abortSignal})}var S=class extends Blob{static async create(e,t){let r=t?.fetch??fetch,n=await r(e,{method:"HEAD",...t?.accessToken&&{headers:{Authorization:`Bearer ${t.accessToken}`}}}),a=Number(n.headers.get("content-length")),s=n.headers.get("content-type")||"";return"bytes"!==n.headers.get("accept-ranges")||a<(t?.cacheBelow??1e6)?await (await r(e)).blob():new S(e,0,a,s,!0,r,t?.accessToken)}url;start;end;contentType;full;fetch;accessToken;constructor(e,t,r,n,a,s,o){super([]),this.url=e,this.start=t,this.end=r,this.contentType=n,this.full=a,this.fetch=s,this.accessToken=o}get size(){return this.end-this.start}get type(){return this.contentType}slice(e=0,t=this.size){return(e<0||t<0)&&TypeError("Unsupported negative start/end on WebBlob.slice"),new S(this.url,this.start+e,Math.min(this.start+t,this.end),this.contentType,0===e&&t===this.size&&this.full,this.fetch,this.accessToken)}async arrayBuffer(){return(await this.fetchRange()).arrayBuffer()}async text(){return(await this.fetchRange()).text()}stream(){let e=new TransformStream;return this.fetchRange().then(t=>t.body?.pipeThrough(e)).catch(t=>e.writable.abort(t.message)),e.readable}fetchRange(){let e=this.fetch;return this.full?e(this.url,{...this.accessToken&&{headers:{Authorization:`Bearer ${this.accessToken}`}}}).then(e=>e.ok?e:s(e)):e(this.url,{headers:{Range:`bytes=${this.start}-${this.end-1}`,...this.accessToken&&{Authorization:`Bearer ${this.accessToken}`}}}).then(e=>e.ok?e:s(e))}};function B(e){if(globalThis.Buffer)return globalThis.Buffer.from(e).toString("base64");{let t=[];return e.forEach(e=>{t.push(String.fromCharCode(e))}),globalThis.btoa(t.join(""))}}async function A(t,r,n){if("http:"===t.protocol||"https:"===t.protocol)return[{path:r,blob:await S.create(t,{fetch:n?.fetch,accessToken:n?.accessToken})}];if(w)throw TypeError(`Unsupported URL protocol "${t.protocol}"`);if("file:"===t.protocol){let{FileBlob:a}=await e.A(40100),{subPaths:s}=await e.A(89771),o=await s(t,n?.maxFolderDepth);return 1===o.length&&"."===o[0].relativePath?[{path:r,blob:await a.create(t)}]:Promise.all(o.map(async e=>({path:`${r}/${e.relativePath}`.replace(/\/[.]$/,"").replaceAll("//","/").replace(/^[.]?\//,""),blob:await a.create(new URL(e.path))})))}throw TypeError(`Unsupported URL protocol "${t.protocol}"`)}function $(e,t){return e[t++]|e[t++]<<8|e[t++]<<16|e[t++]<<24}function E(e,t,r){e[t++]=255&r,e[t++]=r>>8&255,e[t++]=r>>16&255,e[t++]=r>>24&255}function P(e,t){let r=65535&e,n=65535&t;return r*n+((e>>>16)*n+r*(t>>>16)<<16)|0}function z(e,t){return(e|=0)>>>32-(t|=0)|e<>>32-(t|=0)|e<>>(t|=0)^e}function R(e,t,r,n,a){return C(P(t,r)+e,n,a)}var _=function(e,t,r,n){let a,s=n;if(n>=16){for(a=[e+0x9e3779b1+0x85ebca77,e+0x85ebca77,e,e-0x9e3779b1];n>=16;){var o,i;o=a,i=r,a=[R(o[0],$(t,i+0),0x85ebca77,13,0x9e3779b1),R(o[1],$(t,i+4),0x85ebca77,13,0x9e3779b1),R(o[2],$(t,i+8),0x85ebca77,13,0x9e3779b1),R(o[3],$(t,i+12),0x85ebca77,13,0x9e3779b1)],r+=16,n-=16}a=z(a[0],1)+z(a[1],7)+z(a[2],12)+z(a[3],18)+s}else a=e+0x165667b1+n>>>0;for(;n>=4;)a=R(a,$(t,r),0xc2b2ae3d,17,0x27d4eb2f),r+=4,n-=4;for(;n>0;)a=C(a+P(t[r],0x165667b1),11,0x9e3779b1),r++,n--;return(a=L(P(L(P(L(a,15),0x85ebca77),13),0xc2b2ae3d),16))>>>0},O=M(5242880),D=function(){try{return new Uint32Array(65536)}catch(t){let e=Array(65536);for(let t=0;t<65536;t++)e[t]=0;return e}}(),j={4:65536,5:262144,6:1048576,7:4194304};function M(e){return new Uint8Array(e)}function W(e,t){let r,n;return void 0===t&&(t=function(e){let t=0;if(0x184d2204!==$(e,0))throw Error("invalid magic number");t+=4;let r=e[t++];if((192&r)!=64)throw Error("incompatible descriptor version "+(192&r));let n=(16&r)!=0,a=e[t++]>>4&7;if(void 0===j[a])throw Error("invalid block size "+a);let s=j[a];if((8&r)!=0){var o;return o=t,e[o++]|e[o++]<<8|e[o++]<<16|e[o++]<<24|e[o++]<<32|e[o++]<<40|e[o++]<<48|e[o++]<<56}t++;let i=0;for(;;){let r=$(e,t);if(t+=4,0x80000000&r?(r&=0x7fffffff,i+=r):r>0&&(i+=s),0===r)return i;n&&(t+=4),t+=r}}(e)),(n=function(e,t){let r,n,a=0,s=0;if(0x184d2204!==$(e,0))throw Error("invalid magic number");if(a+=4,(192&(n=e[a++]))!=64)throw Error("incompatible descriptor version");if(r=(16&n)!=0,void 0===j[e[a++]>>4&7])throw Error("invalid block size");for((8&n)!=0&&(a+=8),a++;;){var o;if(o=$(e,a),a+=4,0===o)break;if(r&&(a+=4),(0x80000000&o)!=0){o&=0x7fffffff;for(let r=0;r>4;if(f>0){if(15===f)for(;f+=e[r],255===e[r++];);for(l=r+f;r=i)break;if(s=15&n,o=e[r++]|e[r++]<<8,15===s)for(;s+=e[r],255===e[r++];);if(s+=4,c&&1===o)t.fill(0|t[a-1],a,a+s),a+=s;else if(c&&o>s&&s>31)t.copyWithin(a,a-o,a-o+s),a+=s;else for(l=(h=a-o)+s;h>8,r++;let n=j[7],a=e.length,s=0;for(let e=0;e<65536;e++)D[e]=0;for(;a>0;){let o=0,i=a>n?n:a;if((o=function(e,t,r,n,a){let s,o,i,l,h,c,f,d;c=0,f=n+r,o=r;let u=67;for(;r<=f-12;){var p;let n=$(e,r),g=(-0x4aa5b0f7^(p=(p=(p=(p=-0x389e3dc4^(p=(p=0|n)+0x7ed55d16+(p<<12)|0)^p>>>19)+0x165667b1+(p<<5)|0)+-0x2c5d9b94^p<<9)+-0x28fb93b+(p<<3)|0)^p>>>16)>>>0;if(s=a[g=(g>>16^g)>>>0&65535]-1,a[g]=r+1,s<0||r-s>>>16>0||$(e,s)!==n){r+=u++>>6;continue}for(u=67,h=r-o,l=r-s,r+=4,s+=4,i=r;r=15){for(t[c++]=240+b,d=h-15;d>=255;d-=255)t[c++]=255;t[c++]=d}else t[c++]=(h<<4)+b;for(let r=0;r>8,i>=15){for(d=i-15;d>=255;d-=255)t[c++]=255;t[c++]=d}o=r}if(0===o)return 0;if((h=f-o)>=15){for(t[c++]=240,d=h-15;d>=255;d-=255)t[c++]=255;t[c++]=d}else t[c++]=h<<4;for(r=o;ri||0===o){E(t,r,0x80000000|i),r+=4;for(let n=s+i;sa.start&&r.push({index:n,range:a}),null!==a.data)throw Error("Overlapping range already has data")}if(0===r.length){this.ranges.push({start:e,end:t,refCount:1,data:null}),this.ranges.sort((e,t)=>e.start-t.start);return}let n=[],a=e;for(let e=0;et&&n.push({start:t,end:s.end,refCount:s.refCount,data:null}),a=Math.max(a,s.end)}ae.start-t.start)}remove(e,t){if(t<=e)throw TypeError("End must be greater than start");let r=[];for(let n=0;na.start&&r.push({index:n,range:a})}if(0===r.length)throw Error("No ranges found to remove");if(e!==r[0].range.start||t!==r[r.length-1].range.end)throw Error("Range boundaries must match existing boundaries");for(let e=0;ee.refCount>0)}getRanges(e,t){if(t<=e)throw TypeError("End must be greater than start");return this.ranges.filter(r=>er.start)}getAllRanges(){return[...this.ranges]}},X={0:"None",1:"LZ4",2:"ByteGroupingLZ4"},N=class extends Blob{fetch;accessToken;refreshUrl;reconstructionUrl;hash;start=0;end=0;internalLogging=!1;reconstructionInfo;listener;constructor(e){if(super([]),this.fetch=e.fetch??fetch.bind(globalThis),this.accessToken=h(e),this.refreshUrl=e.refreshUrl,this.end=e.size,this.reconstructionUrl=e.reconstructionUrl,this.hash=e.hash,this.listener=e.listener,this.internalLogging=e.internalLogging??!1,e.readToken){const t=K({refreshUrl:this.refreshUrl,initialAccessToken:this.accessToken});J.set(t,{accessToken:e.readToken.accessToken,expiresAt:new Date(1e3*e.readToken.exp),casUrl:e.readToken.casUrl})}}get size(){return this.end-this.start}#e(){let e=new N({fetch:this.fetch,hash:this.hash,refreshUrl:this.refreshUrl,reconstructionUrl:this.reconstructionUrl,size:this.size});return e.accessToken=this.accessToken,e.start=this.start,e.end=this.end,e.reconstructionInfo=this.reconstructionInfo,e.listener=this.listener,e.internalLogging=this.internalLogging,e}slice(e=0,t=this.size){(e<0||t<0)&&TypeError("Unsupported negative start/end on XetBlob.slice");let r=this.#e();return r.start=this.start+e,r.end=Math.min(this.start+t,this.end),(r.start!==this.start||r.end!==this.end)&&(r.reconstructionInfo=void 0),r}#t;#r(){return this.#t||(this.#t=(async()=>{let e=await V(this.accessToken,this.fetch,this.refreshUrl),t=await this.fetch(this.reconstructionUrl??`${e.casUrl}/v1/reconstructions/${this.hash}`,{headers:{Authorization:`Bearer ${e.accessToken}`,Range:`bytes=${this.start}-${this.end-1}`}});if(!t.ok)throw await s(t);return this.reconstructionInfo=await t.json(),this.reconstructionInfo})().finally(()=>this.#t=void 0)),this.#t}async #n(){if(0===this.size)return new ReadableStream({start(e){e.close()}});this.reconstructionInfo||await this.#r();let e=new Map;if(!this.reconstructionInfo)throw Error("Failed to load reconstruction info");for(let t of this.reconstructionInfo.terms){let r=e.get(t.hash);r||(r=new q,e.set(t.hash,r)),r.add(t.range.start,t.range.end)}let t=this.listener,r=this.internalLogging?(...e)=>console.log(...e):()=>{},n=async function*(n,a,o,i){let l=0,h=n.offset_into_first_range;for(let c of n.terms){let f;if(l>=o)break;let d=e.get(c.hash);if(!d)throw Error(`Failed to find range list for term ${c.hash}`);{let e=d.getRanges(c.range.start,c.range.end);if(e.every(e=>e.data)){r("all data available for term",c.hash,h);e:for(let r of e)for(let e of r.data){if(h){let t=Math.min(h,e.byteLength);if(e=e.slice(t),h-=t,!e.byteLength)continue}if(e.byteLength>o-l&&(e=e.slice(0,o-l)),l+=e.byteLength,yield r.refCount>1?e.slice():e,t?.({event:"progress",progress:{read:l,total:o}}),l>=o)break e}d.remove(c.range.start,c.range.end);continue}}let u=n.fetch_info[c.hash].find(e=>e.range.start<=c.range.start&&e.range.end>=c.range.end);if(!u)throw Error(`Failed to find fetch info for term ${c.hash} and range ${c.range.start}-${c.range.end}`);r("term",c),r("fetchinfo",u),r("readBytesToSkip",h);let p=await a(u.url,{headers:{Range:`bytes=${u.url_range.start}-${u.url_range.end}`}});if(403===p.status&&(n=await i(),p=await a(u.url,{headers:{Range:`bytes=${u.url_range.start}-${u.url_range.end}`}})),!p.ok)throw await s(p);r("expected content length",p.headers.get("content-length"),"range",u.url_range,p.headers.get("content-range"));let g=p.body?.getReader();if(!g)throw Error("Failed to get reader from response body");let b=!1,w=u.range.start,m=d.getRanges(u.range.start,u.range.end),y=0;t:for(;!b&&l=1),a=n+t+ +(r>=2),s=a+t+ +(3==r),o=new Uint8Array(e.byteLength);for(let t=0,r=0;tw>=e.start&&w=c.range.start&&w=u&&(i.data??=[],i.data.push(s),p=!0),d){if(h){let e=Math.min(h,s.byteLength);s=s.slice(h),h-=e}s.byteLength>o-l&&(s=s.slice(0,o-l)),s.byteLength&&(r("yield",s.byteLength,"bytes",e.value.byteLength,"total read",l,p),l+=s.byteLength,yield p?s.slice():s,t?.({event:"progress",progress:{read:l,total:o}}))}w++,e.value=e.value.slice(a.compressed_length)}}if(b&&lt.pipeThrough(e)).catch(t=>e.writable.abort(t.message)),e.readable}},H=new Map,J=new Map;function K(e){return JSON.stringify([e.refreshUrl,e.initialAccessToken])}async function V(e,t,r){let n=K({refreshUrl:r,initialAccessToken:e}),a=J.get(n);if(a&&a.expiresAt>new Date(Date.now()+6e4))return{accessToken:a.accessToken,casUrl:a.casUrl};let s=H.get(n);if(s)return s;let o=(async()=>{let a=await t(r,{headers:{...e?{Authorization:`Bearer ${e}`}:{}}});if(!a.ok)throw Error(`Failed to get JWT token: ${a.status} ${await a.text()}`);let s=await a.json(),o={accessToken:s.accessToken,expiresAt:new Date(1e3*s.exp),casUrl:s.casUrl};for(let[e,t]of(H.delete(n),J.entries()))if(t.expiresAt=1e3){let e=J.keys().next().value;e&&J.delete(e)}return J.set(n,o),{accessToken:s.accessToken,casUrl:s.casUrl}})();return H.set(n,o),o}var G=class{index=0;xorbIndices;chunkIndices;map=new Map;hmacs=new Set;maxSize;constructor(e=1e6){if(e<1)throw Error("maxSize must be at least 1");this.maxSize=e,this.xorbIndices=new Int32Array(Math.min(1e4,e)),this.chunkIndices=new Uint16Array(Math.min(1e4,e))}addChunkToCache(e,t,r,n){if(!this.map.has(e)){if(this.map.values().next().value===this.index&&this.map.delete(this.map.keys().next().value),this.map.set(e,this.index),null!==n&&this.hmacs.add(n),this.index>=this.xorbIndices.length){let e=this.xorbIndices,t=this.chunkIndices;this.xorbIndices=new Int32Array(Math.min(1.5*this.xorbIndices.length,this.maxSize)),this.chunkIndices=new Uint16Array(Math.min(1.5*this.chunkIndices.length,this.maxSize)),this.xorbIndices.set(e),this.chunkIndices.set(t)}this.xorbIndices[this.index]=t,this.chunkIndices[this.index]=r,this.index=(this.index+1)%this.maxSize}}getChunk(e,t){let r=this.map.get(e);if(void 0===r&&null!==t){for(let n of this.hmacs)if(void 0!==(r=this.map.get(t(e,n))))break}if(void 0!==r)return{xorbIndex:this.xorbIndices[r],chunkIndex:this.chunkIndices[r]}}updateChunkIndex(e,t){let r=this.map.get(e);if(void 0===r)throw Error(`Chunk not found in cache: ${e}`);this.chunkIndices[r]=t}removeChunkFromCache(e){this.map.delete(e)}},Z=new Map,Y=new Map;async function Q(e){if(e.xetParams.expiresAt&&e.xetParams.casUrl&&e.xetParams.accessToken&&e.xetParams.expiresAt>new Date(Date.now()+6e4))return{accessToken:e.xetParams.accessToken,casUrl:e.xetParams.casUrl};let t=e.xetParams.refreshWriteTokenUrl,r=Y.get(t);if(r&&r.expiresAt>new Date(Date.now()+6e4))return{accessToken:r.accessToken,casUrl:r.casUrl};let n=Z.get(t);if(n)return n;let a=(async()=>{let r=await (e.fetch??fetch)(e.xetParams.refreshWriteTokenUrl,{headers:{...e.accessToken?{Authorization:`Bearer ${e.accessToken}`}:{},...e.xetParams.sessionId?{"X-Xet-Session-Id":e.xetParams.sessionId}:{}}});if(!r.ok)throw await s(r);let n=await r.json(),a={accessToken:n.accessToken,expiresAt:new Date(1e3*n.exp),casUrl:n.casUrl};for(let[e,r]of(Z.delete(t),Y.entries()))if(r.expiresAt=1e3){let e=Y.keys().next().value;e&&Y.delete(e)}return Y.set(t,a),{accessToken:n.accessToken,casUrl:n.casUrl}})();return Z.set(t,a),a}var ee="ff".repeat(32);function et(e,t){let r="";for(let n=0;n<32;n+=8)r+=`${e[t+n+7].toString(16).padStart(2,"0")}${e[t+n+6].toString(16).padStart(2,"0")}${e[t+n+5].toString(16).padStart(2,"0")}${e[t+n+4].toString(16).padStart(2,"0")}${e[t+n+3].toString(16).padStart(2,"0")}${e[t+n+2].toString(16).padStart(2,"0")}${e[t+n+1].toString(16).padStart(2,"0")}${e[t+n].toString(16).padStart(2,"0")}`;return r}async function er(e){let t=new Uint8Array(await e.arrayBuffer()),r=new DataView(t.buffer);if(!t.slice(0,eu.length).every((e,t)=>e===eu[t]))throw Error("Invalid shard magic tag");let n=r.getBigUint64(eu.length,!0);if(n!==ef)throw Error(`Invalid shard version: ${n}`);let a=Number(r.getBigUint64(eu.length+8,!0)),s=t.length-a,o=r.getBigUint64(s,!0);if(o!==ed)throw Error(`Invalid shard footer version: ${o}`);let i=Number(r.getBigUint64(s+16,!0)),l=Number(r.getBigUint64(s+24,!0)),h=et(t,s+72),c=[],f=i;for(;fe+t,0)}var ea=class extends Blob{originalBlob;spliceOperations;constructor(e,t){super(),this.originalBlob=e,this.spliceOperations=t}static create(e,t){for(let r of t)if(r.start<0||r.end<0||r.start>e.size||r.end>e.size||r.start>r.end)throw Error("Invalid start/end positions for SplicedBlob");let r=[...t].sort((e,t)=>e.start-t.start);for(let e=0;er[e+1].start)throw Error("Overlapping splice operations are not supported");return new ea(e,r)}get size(){let e=0,t=0;for(let r of this.spliceOperations)e+=r.end-r.start,t+=r.insert.size;return this.originalBlob.size-e+t}get type(){return this.originalBlob.type}slice(e=0,t=this.size){if(e<0||t<0)throw TypeError("Unsupported negative start/end on SplicedBlob.slice");if(e=Math.min(e,this.size),t=Math.min(t,this.size),e>=t)return new Blob([]);let r=this.segments,n=[0],a=0;for(let e of r)a+=e.size,n.push(a);let s=[];for(let a=0;a=t)break;let i=Math.max(0,e-o),l=Math.min(r[a].size,t-o);ie.arrayBuffer())),r=new Uint8Array(en(t.map(e=>e.byteLength))),n=0;for(let e of t)r.set(new Uint8Array(e),n),n+=e.byteLength;return r.buffer}async text(){let e=await this.arrayBuffer();return new TextDecoder().decode(e)}stream(){return new ReadableStream({start:async e=>{try{for(let t of this.segments){let r=t.stream().getReader();try{for(;;){let{done:t,value:n}=await r.read();if(t)break;e.enqueue(n)}}finally{r.releaseLock()}}e.close()}catch(t){e.error(t)}}})}get segments(){let e=[],t=0;for(let r of[...this.spliceOperations].sort((e,t)=>e.start-t.start))t0&&e.push(r.insert),t=r.end;return t({hash:e.hash,length:e.length}));return{event:"xorb",xorb:this.data.subarray(0,this.offset),hash:e(t),chunks:t,id:this.id,files:Object.entries(this.fileProcessedBytes).map(([e,t])=>({path:e,progress:t/this.fileSize[e],lastSentProgress:((this.fileUploadedBytes[e]??0)+(t-(this.fileUploadedBytes[e]??0))*.1)/this.fileSize[e]}))}}};async function*eo(t,r){let n=new Set,a=await e.A(82958),s=0;await a.init();let o=new G,i=new es,l=e=>{let t=i.event(a.compute_xorb_hash.bind(a));return s++,(i=new es).id=s,i.fileUploadedBytes={[e.path]:e.uploadedBytes},i.fileSize[e.path]=e.size,t},h=[],c=[""];for await(let e of t){if(r.yieldCallback?.({event:"fileProgress",path:e.path,progress:0}),e.sha256&&n.has(e.sha256)){r.yieldCallback?.({event:"fileProgress",path:e.path,progress:1});continue}e.sha256&&n.add(e.sha256);let t=new a.Chunker(65536);try{i.fileSize[e.path]=e.content.size,e.content instanceof ea&&e.content.firstSpliceIndex<131072&&await ec(e.content.originalBlob.slice(0,131072),c,r,o,a,{maxChunks:1,isAtBeginning:!0});let n=1/0,f=0,d=!0,u=[],p=e.content.stream().getReader(),g=0,b=0,w=[],m=[],y=async function*(t){for(let p of t){d&&(p.dedup=!0,d=!1);let t=i.chunks.length,y=s,x=ei(u,p.length),k=o.getChunk(p.hash,a.compute_hmac);if(void 0===k&&p.dedup&&n>=4e6){let t=await Q(r);n=0;let s=await (r.fetch??fetch)(t.casUrl+"/v1/chunks/default/"+p.hash,{headers:{Authorization:`Bearer ${t.accessToken}`}});if(s.ok){let t=await s.blob(),r=await er(t);for(let e of r.xorbs){let t=-c.length;c.push(e.hash);let n=0;for(let a of e.chunks)o.addChunkToCache(a.hash,t,n++,r.hmacKey)}k=o.getChunk(p.hash,a.compute_hmac);let n=b;(b=function(e,t,r,n,a,s){let o=new Map;for(let a=e.immutableData?.chunkIndex??0;a0&&d.set(t,f.length-1))}for(let t of(e.chunks=f,e.offset=c,a))if(t.xorbId===e.id){let r=d.get(t.chunkIndex);if(void 0!==r){let a=n.getChunk(e.chunks[r].hash,null);void 0!==a&&a.xorbIndex===t.xorbId&&a.chunkIndex===t.chunkIndex&&n.updateChunkIndex(e.chunks[r].hash,r),t.chunkIndex=r}}return s}(i,a.compute_hmac.bind(a),r,o,m,b))>n&&(i.fileUploadedBytes[e.path]??=0,i.fileUploadedBytes[e.path]+=b-n)}}if(void 0===k){if(!el(i,x,p.hash)){for(let r of(yield l({path:e.path,uploadedBytes:g,size:e.content.size}),t=0,y=s,h))r.representation=r.representation.map(e=>({...e,xorbId:e.xorbId>=0?e.xorbId:c[-e.xorbId]})),yield r;if(h.length=0,!el(i,x,p.hash))throw Error("Failed to write chunk into xorb")}o.addChunkToCache(p.hash,s,t,null)}else y=k.xorbIndex,t=k.chunkIndex,b+=p.length,i.fileUploadedBytes[e.path]??=0,i.fileUploadedBytes[e.path]+=p.length;if(n+=p.length,f+=p.length,w.push({hash:p.hash,length:p.length}),m.push({xorbId:y,chunkIndex:t,length:p.length}),i.fileProcessedBytes[e.path]=g,f>=1e6&&(f=0,r.yieldCallback?.({event:"fileProgress",path:e.path,progress:((i.fileUploadedBytes[e.path]??0)+(i.fileProcessedBytes[e.path]-(i.fileUploadedBytes[e.path]??0))*.1)/e.content.size})),i.chunks.length>=8192){for(let t of(yield l({path:e.path,uploadedBytes:g,size:e.content.size}),h))t.representation=t.representation.map(e=>({...e,xorbId:e.xorbId>=0?e.xorbId:c[-e.xorbId]})),yield t;h.length=0}}};for(;;){let{done:e,value:r}=await p.read();if(e){yield*y(t.finish());break}g+=r.length,u.push(r),yield*y(t.add_data(r))}let x=eh(m,w,a.compute_verification_hash.bind(a));i.immutableData={chunkIndex:i.chunks.length,offset:i.offset};let k=e.content.size>0?b/e.content.size:0;h.push({event:"file",path:e.path,hash:a.compute_file_hash(w),sha256:e.sha256,dedupRatio:k,representation:x})}finally{t.free()}}for(let e of(i.offset>0&&(yield i.event(a.compute_xorb_hash.bind(a))),h))e.representation=e.representation.map(e=>({...e,xorbId:e.xorbId>=0?e.xorbId:c[-e.xorbId]})),yield e}function ei(e,t){if(t===e[0].length){let t=e[0];return e.shift(),t}if(t=1),s=a+r+ +(n>=2),o=s+r+ +(3==n);for(let r=0,n=0;r0x4000000)&&(e.data[e.offset]=0,e.data[e.offset+1]=255&o.length,e.data[e.offset+2]=o.length>>8&255,e.data[e.offset+3]=o.length>>16&255,e.data[e.offset+4]=o.length>8&255,e.data[e.offset+7]=t.length>>16&255,e.data.set(o,e.offset+8),e.chunks.push({hash:r,length:t.length,offset:e.offset}),e.offset+=8+o.length,!0)}var eh=(e,t,r)=>{if(0===e.length)return[];let n=[],a={xorbId:e[0].xorbId,indexStart:e[0].chunkIndex,indexEnd:e[0].chunkIndex+1,length:e[0].length,chunkHashStart:0};for(let s=1;se.hash));n.push({xorbId:a.xorbId,indexStart:a.indexStart,indexEnd:a.indexEnd,length:a.length,rangeHash:e}),a={xorbId:o.xorbId,indexStart:o.chunkIndex,indexEnd:o.chunkIndex+1,length:o.length,chunkHashStart:s}}}let s=r(t.slice(a.chunkHashStart).map(e=>e.hash));return n.push({xorbId:a.xorbId,indexStart:a.indexStart,indexEnd:a.indexEnd,length:a.length,rangeHash:s}),n};async function ec(e,t,r,n,a,s){let o=new a.Chunker(65536),i=0,l=0,h=0,c=1/0,f=[];try{let d=e.stream().getReader(),u=async e=>{for(let o of e){l++,s?.isAtBeginning&&1===l&&(o.dedup=!0),h+=o.length,ei(f,o.length);let e=n.getChunk(o.hash,a.compute_hmac);if(void 0!==e){i+=o.length,c+=o.length;continue}if(o.dedup&&c>=4e6){let s=await Q(r);c=0;let i=await (r.fetch??fetch)(s.casUrl+"/v1/chunks/default/"+o.hash,{headers:{Authorization:`Bearer ${s.accessToken}`}});if(i.ok){let r=await i.blob(),s=await er(r);for(let e of s.xorbs){let r=-t.length;t.push(e.hash);let a=0;for(let t of e.chunks)n.addChunkToCache(t.hash,r,a++,s.hmacKey)}e=n.getChunk(o.hash,a.compute_hmac)}}void 0!==e&&(i+=o.length),c+=o.length}};for(;(s?.end===void 0||!(h>=s.end))&&(s?.maxChunks===void 0||!(l>=s.maxChunks));){let{done:e,value:t}=await d.read();if(e){await u(o.finish());break}f.push(t),await u(o.add_data(t))}}finally{o.free()}}var ef=2n,ed=1n,eu=new Uint8Array([72,70,82,101,112,111,77,101,116,97,68,97,116,97,0,85,105,103,69,106,123,129,87,131,165,189,217,92,205,209,74,169]);async function*ep(e,t){let r=[],n=new Uint8Array(.25*Math.floor(0x3ffff08)),a=new Uint8Array(.75*Math.floor(0x3ffff08)),s=new DataView(a.buffer),o=0,i=new DataView(n.buffer),l=0,h=0n,c=0n,f=0n;for await(let c of eo(e,t))switch(c.event){case"xorb":{r.push(c.hash);let e=48+48*c.chunks.length;o+e>a.length&&(o>0||l>0)&&await ew(d(),t),eg(c.hash,a,o),o+=32,s.setUint32(o,0,!0),o+=4,s.setUint32(o,c.chunks.length,!0),o+=4;let n=en(c.chunks.map(e=>e.length));s.setUint32(o,n,!0),f+=BigInt(n),h+=BigInt(c.xorb.byteLength),o+=4,s.setUint32(o,c.xorb.byteLength,!0),o+=4;let i=0;for(let e of c.chunks)eg(e.hash,a,o),o+=32,s.setUint32(o,i,!0),o+=4,s.setUint32(o,e.length,!0),o+=4,s.setBigUint64(o,0n,!0),o+=8,i+=e.length;for(let e of c.files)yield{event:"fileProgress",path:e.path,progress:e.lastSentProgress};for(let e of(await eb(c,t),c.files))yield{event:"fileProgress",path:e.path,progress:e.progress};break}case"file":{yield{event:"file",path:c.path,xetHash:c.hash,sha256:c.sha256,dedupRatio:c.dedupRatio};let e=48*c.representation.length,a=48*c.representation.length,s=c.sha256,h=void 0!==s;for(let s of(l+(48+e+a+48*!!h)>n.length&&(o>0||l>0)&&await ew(d(),t),eg(c.hash,n,l),l+=32,i.setUint32(l,0x80000000+0x40000000*!!h,!0),l+=4,i.setUint32(l,c.representation.length,!0),l+=4,i.setBigUint64(l,0n,!0),l+=8,c.representation))eg("number"==typeof s.xorbId?r[s.xorbId]:s.xorbId,n,l),l+=32,i.setUint32(l,0,!0),l+=4,i.setUint32(l,s.length,!0),l+=4,i.setUint32(l,s.indexStart,!0),l+=4,i.setUint32(l,s.indexEnd,!0),l+=4;for(let e of c.representation){eg(e.rangeHash,n,l),l+=32;for(let e=0;e<16;e++)n[l+e]=0;l+=16}if(h){eg(s,n,l),l+=32;for(let e=0;e<16;e++)n[l+e]=0;l+=16}}}function d(){let e=new Uint8Array(248+o+48+l+48),t=new DataView(e.buffer),r=0;e.set(eu,r),r+=eu.length,t.setBigUint64(r,ef,!0),r+=8,t.setBigUint64(r,BigInt(200),!0),r+=8,e.set(n.slice(0,l),r),r+=l;for(let t=0;t<32;t++)e[r+t]=255;r+=32;for(let t=0;t<16;t++)e[r+t]=0;let s=r+=16;e.set(a.slice(0,o),r),r+=o;for(let t=0;t<32;t++)e[r+t]=255;r+=32;for(let t=0;t<16;t++)e[r+t]=0;let i=r+=16;t.setBigUint64(r,ed,!0),r+=8,t.setBigUint64(r,BigInt(48),!0),r+=8,t.setBigUint64(r,BigInt(s),!0),r+=8;for(let e=0;e<48;e++)t.setUint8(r+e,0);r+=48;for(let e=0;e<32;e++)t.setUint8(r+e,0);r+=32,t.setBigUint64(r,BigInt(Math.floor(Date.now()/1e3)),!0),r+=8,t.setBigUint64(r,0n,!0),r+=8;for(let e=0;e<48;e++)t.setUint8(r+e,0);return r+=48,t.setBigUint64(r,h,!0),r+=8,t.setBigUint64(r,c,!0),r+=8,t.setBigUint64(r,f,!0),r+=8,t.setBigUint64(r,BigInt(i),!0),o=0,l=0,h=0n,f=0n,c=0n,e}(o||l)&&await ew(d(),t)}function eg(e,t,r){for(let n=0;n{for(let n of e.files)t.yieldCallback?.({event:"fileProgress",path:n.path,progress:n.lastSentProgress+(n.progress-n.lastSentProgress)*r})}}}});if(!n.ok)throw await s(n)}async function ew(e,t){let r=await Q(t),n=await (t.fetch??fetch)(`${r.casUrl}/v1/shards`,{method:"POST",body:e,headers:{Authorization:`Bearer ${r.accessToken}`,...t.xetParams.sessionId?{"X-Xet-Session-Id":t.xetParams.sessionId}:{}}});if(!n.ok)throw await s(n)}function em(e,t){if(t<=0)return[];let r=e=>new Promise(t=>setTimeout(t,e)),n=null,a=[],s=t;for(let o=0;o{for(;null!==n;)await r(1);return n=o,e.next().then(e=>(n=null,e))},return:async()=>0==--s?e.return(void 0):{done:!0,value:void 0},throw:async t=>e.throw(t),[Symbol.asyncIterator]:()=>a[o]});return a}function ey(e){let t="addOrUpdate"===e.operation;if(t&&!(e.content instanceof Blob))throw TypeError("Precondition failed: op.content should be a Blob");return t}async function*ex(e){let t=h(e),r=c(e.repo);if("bucket"===r.type)return yield*ek(e);yield{event:"phase",phase:"preuploading"};let n=e.useXet??!0,l=new Map,g=new AbortController,b=g.signal;b.throwIfAborted||(b.throwIfAborted=()=>{if(b.aborted)throw new DOMException("Aborted","AbortError")}),e.abortSignal&&e.abortSignal.addEventListener("abort",()=>g.abort());try{let h=(await Promise.all(e.operations.map(async t=>{if("edit"===t.operation){let e=ea.create(t.originalContent,t.edits.map(e=>({insert:e.content,start:e.start,end:e.end})));return{operation:"addOrUpdate",path:t.path,content:e}}if("addOrUpdate"!==t.operation)return t;if(!(t.content instanceof URL))return{...t,content:t.content};let r=await A(t.content,t.path,{fetch:e.fetch,maxFolderDepth:e.maxFolderDepth});return b?.throwIfAborted(),r.map(e=>({...t,content:e.blob,path:e.path}))}))).flat(1),c=h.filter(ey).find(e=>".gitattributes"===e.path)?.content;for(let n of f(h.filter(ey),100)){let o={gitAttributes:c&&await c.text(),files:await Promise.all(n.map(async e=>({path:e.path,size:e.content.size,sample:B(new Uint8Array(await e.content.slice(0,512).arrayBuffer()))})))};b?.throwIfAborted();let i=await (e.fetch??fetch)(`${e.hubUrl??a}/api/${r.type}s/${r.name}/preupload/${encodeURIComponent(e.branch??"main")}`+(e.isPullRequest?"?create_pr=1":""),{method:"POST",headers:{...t&&{Authorization:`Bearer ${t}`},"Content-Type":"application/json"},body:JSON.stringify(o),signal:b});if(!i.ok)throw await s(i);for(let e of(await i.json()).files)"lfs"===e.uploadMode&&l.set(e.path,null)}for(let c of(yield{event:"phase",phase:"uploadingLargeFiles"},f(h.filter(ey).filter(e=>l.has(e.path)),100))){let h=yield*p((t,r,n)=>d(c.map(r=>async()=>{let n,a=T(r.content,{useWebWorker:e.useWebWorkers,abortSignal:b});do(n=await a.next()).done||t({event:"fileProgress",path:r.path,progress:n.value,state:"hashing"});while(!n.done)let s=n.value;return l.set(r.path,n.value),s}),5).then(r,n));b?.throwIfAborted();let f={operation:"upload",transfers:["basic","multipart",...n?["xet"]:[]],hash_algo:"sha_256",...!e.isPullRequest&&{ref:{name:e.branch??"main"}},objects:c.map((e,t)=>({oid:h[t],size:e.content.size}))},g=await (e.fetch??fetch)(`${e.hubUrl??a}/${"model"===r.type?"":r.type+"s/"}${r.name}.git/info/lfs/objects/batch`,{method:"POST",headers:{...t&&{Authorization:`Bearer ${t}`},Accept:"application/vnd.git-lfs+json","Content-Type":"application/vnd.git-lfs+json"},body:JSON.stringify(f),signal:b});if(!g.ok)throw await s(g);let m=await g.json(),y=g.headers.get("X-Request-Id")||void 0,x=new Map(c.map((e,t)=>[h[t],e]));n&&"xet"!==m.transfer&&(n=!1);let k=null;if(n){for(let e of m.objects){let t=x.get(e.oid);if(!t)throw new i("Unrequested object ID in response");if(e.error){let t=`Error while doing LFS batch call for ${c[h.indexOf(e.oid)].path}: ${e.error.message}${y?` - Request ID: ${y}`:""}`;throw new o(g.url,e.error.code,y,t)}if(e.actions?.upload){let t=new Headers(e.actions.upload.header);k={sessionId:t.get("X-Xet-Session-Id")??void 0,casUrl:t.get("X-Xet-Cas-Url")??void 0,accessToken:t.get("X-Xet-Access-Token")??void 0,expiresAt:t.get("X-Xet-Token-Expiration")?new Date(1e3*parseInt(t.get("X-Xet-Token-Expiration")??"0")):void 0,refreshWriteTokenUrl:e.actions.upload.href}}else yield{event:"fileProgress",path:t.path,progress:1,state:"uploading"}}let n=async function*(){for(let e of m.objects){let t=x.get(e.oid);t&&e.actions?.upload&&(b?.throwIfAborted(),yield{content:t.content,path:t.path,sha256:e.oid})}}();if(k){let s=k,o=em(n,5);yield*p((n,i,l)=>Promise.all(o.map(async function(o){for await(let i of ep(o,{fetch:e.fetch,accessToken:t,hubUrl:e.hubUrl??a,repo:r,xetParams:s,rev:e.branch??"main",isPullRequest:e.isPullRequest,yieldCallback:e=>n({...e,state:"uploading"})}))"file"===i.event?n({event:"fileProgress",path:i.path,progress:1,state:"uploading"}):"fileProgress"===i.event&&n({event:"fileProgress",path:i.path,progress:i.progress,state:"uploading"})})).then(()=>i(void 0),l))}}else yield*p((t,r,n)=>u(m.objects.map(r=>async()=>{let n=x.get(r.oid);if(!n)throw new i("Unrequested object ID in response");if(b?.throwIfAborted(),r.error){let e=`Error while doing LFS batch call for ${c[h.indexOf(r.oid)].path}: ${r.error.message}${y?` - Request ID: ${y}`:""}`;throw new o(g.url,r.error.code,y,e)}if(!r.actions?.upload)return void t({event:"fileProgress",path:n.path,progress:1,state:"uploading"});t({event:"fileProgress",path:n.path,progress:0,state:"uploading"});let a=n.content,l=r.actions.upload.header;if(l?.chunk_size){let o=parseInt(l.chunk_size),i=r.actions.upload.href,f=Object.keys(l).filter(e=>/^[0-9]+$/.test(e));if(f.length!==Math.ceil(a.size/o))throw Error("Invalid server response to upload large LFS file, wrong number of parts");let d={oid:r.oid,parts:f.map(e=>({partNumber:+e,etag:""}))},p=e=>t({event:"fileProgress",path:n.path,progress:e,state:"uploading"});await u(f.map(t=>async()=>{b?.throwIfAborted();let i=parseInt(t)-1,u=a.slice(i*o,(i+1)*o),g=await (e.fetch??fetch)(l[t],{method:"PUT",body:u instanceof S&&w?await u.arrayBuffer():u,signal:b,...{progressHint:{path:n.path,part:i,numParts:f.length,progressCallback:p}}});if(!g.ok)throw await s(g,{requestId:y,message:`Error while uploading part ${t} of ${c[h.indexOf(r.oid)].path} to LFS storage`});let m=g.headers.get("ETag");if(!m)throw Error("Cannot get ETag of part during multipart upload");d.parts[Number(t)-1].etag=m}),5),b?.throwIfAborted();let g=await (e.fetch??fetch)(i,{method:"POST",body:JSON.stringify(d),headers:{Accept:"application/vnd.git-lfs+json","Content-Type":"application/vnd.git-lfs+json"},signal:b});if(!g.ok)throw await s(g,{requestId:y,message:`Error completing multipart upload of ${c[h.indexOf(r.oid)].path} to LFS storage`});t({event:"fileProgress",path:n.path,progress:1,state:"uploading"})}else{let o=await (e.fetch??fetch)(r.actions.upload.href,{method:"PUT",headers:{...y?{"X-Request-Id":y}:void 0},body:a instanceof S&&w?await a.arrayBuffer():a,signal:b,...{progressHint:{path:n.path,progressCallback:e=>t({event:"fileProgress",path:n.path,progress:e,state:"uploading"})}}});if(!o.ok)throw await s(o,{requestId:y,message:`Error while uploading ${c[h.indexOf(r.oid)].path} to LFS storage`});t({event:"fileProgress",path:n.path,progress:1,state:"uploading"})}}),5).then(r,n))}return b?.throwIfAborted(),yield{event:"phase",phase:"committing"},yield*p(async(n,o,i)=>(e.fetch??fetch)(`${e.hubUrl??a}/api/${r.type}s/${r.name}/commit/${encodeURIComponent(e.branch??"main")}`+(e.isPullRequest?"?create_pr=1":""),{method:"POST",headers:{...t&&{Authorization:`Bearer ${t}`},"Content-Type":"application/x-ndjson"},body:[{key:"header",value:{summary:e.title,description:e.description,parentCommit:e.parentCommit}},...await Promise.all(h.map(e=>{if(ey(e)){let t=l.get(e.path);if(t)return{key:"lfsFile",value:{path:e.path,algo:"sha256",size:e.content.size,oid:t}}}return eI(e)}))].map(e=>JSON.stringify(e)).join("\n"),signal:b,...{progressHint:{progressCallback:e=>{for(let t of h)ey(t)&&!l.has(t.path)&&n({event:"fileProgress",path:t.path,progress:e,state:"uploading"})}}}}).then(async e=>{if(!e.ok)throw await s(e);let t=await e.json();o({pullRequestUrl:t.pullRequestUrl,commit:{oid:t.commitOid,url:t.commitUrl},hookOutput:t.hookOutput})}).catch(i))}catch(e){throw g.abort(),e}}async function*ek(e){let t=h(e),r=c(e.repo);if(!1===e.useXet)throw Error("useXet must be true or undefined for buckets");let n=new AbortController,o=n.signal;o.throwIfAborted||(o.throwIfAborted=()=>{if(o.aborted)throw new DOMException("Aborted","AbortError")}),e.abortSignal&&e.abortSignal.addEventListener("abort",()=>n.abort());try{let n=(await Promise.all(e.operations.map(async t=>{if("edit"===t.operation){let e=ea.create(t.originalContent,t.edits.map(e=>({insert:e.content,start:e.start,end:e.end})));return{operation:"addOrUpdate",path:t.path,content:e}}if("addOrUpdate"!==t.operation)return t;if(!(t.content instanceof URL))return{...t,content:t.content};let r=await A(t.content,t.path,{fetch:e.fetch,maxFolderDepth:e.maxFolderDepth});return o?.throwIfAborted(),r.map(e=>({...t,content:e.blob,path:e.path}))}))).flat(1);for(let i of(yield{event:"phase",phase:"uploadingLargeFiles"},f(n.filter(ey),100))){let n=new Map;o?.throwIfAborted();let l=async function*(){for(let e of i)o?.throwIfAborted(),yield{content:e.content,path:e.path}}(),h={sessionId:crypto.randomUUID(),refreshWriteTokenUrl:`${e.hubUrl??a}/api/${r.type}s/${r.name}/xet-write-token`},c=em(l,5);yield*p((s,o,i)=>Promise.all(c.map(async function(o){for await(let i of ep(o,{fetch:e.fetch,accessToken:t,hubUrl:e.hubUrl??a,repo:r,xetParams:h,rev:e.branch??"main",yieldCallback:e=>s({...e,state:"uploading"})}))"file"===i.event?(s({event:"fileProgress",path:i.path,progress:1,state:"uploading"}),n.set(i.path,i.xetHash)):"fileProgress"===i.event&&s({event:"fileProgress",path:i.path,progress:i.progress,state:"uploading"})})).then(()=>o(void 0),i));let f=await (e.fetch??fetch)(`${e.hubUrl??a}/api/${r.type}s/${r.name}/batch`,{method:"POST",headers:{...t&&{Authorization:`Bearer ${t}`},"Content-Type":"application/x-ndjson"},body:[...n.entries()].map(([e,t])=>JSON.stringify({type:"addFile",path:e,xetHash:t})).join("\n"),signal:o});if(!f.ok&&422!==f.status)throw await s(f);for(let e of(await f.json()).failed)yield{event:"fileProgress",path:e.path,progress:0,state:"error"}}o?.throwIfAborted();let i=n.filter(e=>"delete"===e.operation);if(i.length>0){let n=await (e.fetch??fetch)(`${e.hubUrl??a}/api/${r.type}s/${r.name}/batch`,{method:"POST",headers:{...t&&{Authorization:`Bearer ${t}`},"Content-Type":"application/x-ndjson"},body:i.map(e=>JSON.stringify({type:"deleteFile",path:e.path})).join("\n"),signal:o});if(!n.ok)throw await s(n);let l=await n.json();if(l.failed.length>0){let e=l.failed.slice(0,5).map(e=>e.path);throw Error(`Failed to delete ${l.failed.length} file(s): ${e.join(", ")}${l.failed.length>5?"...":""}, request ID: ${n.headers.get("X-Request-Id")}`)}}o?.throwIfAborted()}catch(e){throw n.abort(),e}}async function ev(e){let t=ex(e),r=[],n=0,a=await t.next();for(;!a.done;)"fileProgress"===a.value.event&&"error"===a.value.state&&(n++,r.length<5&&r.push(a.value.path)),a=await t.next();if(n>0)throw Error(`Failed to upload ${n} file(s): ${r.join(", ")}${n>5?"...":""}`);return a.value}async function eI(e){switch(e.operation){case"addOrUpdate":return{key:"file",value:{content:B(new Uint8Array(await e.content.arrayBuffer())),path:e.path,encoding:"base64"}};case"delete":return{key:"deletedFile",value:{path:e.path}};case"edit":throw Error("Edit operations should be converted to addOrUpdate operations before reaching convertOperationToNdJson");default:throw TypeError("Unknown operation: "+e.operation)}}e.s(["commit",0,ev])}]);