UNPKG

@imgly/plugin-ai-video-generation-web

Version:

AI video generation plugin for the CE.SDK editor

5 lines 195 kB
var Uo=Object.create;var Ui=Object.defineProperty;var Lo=Object.getOwnPropertyDescriptor;var $o=Object.getOwnPropertyNames;var No=Object.getPrototypeOf,zo=Object.prototype.hasOwnProperty;var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Bo=(t,e,i,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of $o(e))!zo.call(t,n)&&n!==i&&Ui(t,n,{get:()=>e[n],enumerable:!(r=Lo(e,n))||r.enumerable});return t};var Ko=(t,e,i)=>(i=t!=null?Uo(No(t)):{},Bo(e||!t||!t.__esModule?Ui(i,"default",{value:t,enumerable:!0}):i,t));var Kt=_(N=>{"use strict";var su=N&&N.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})};Object.defineProperty(N,"__esModule",{value:!0});N.TARGET_URL_HEADER=void 0;N.withMiddleware=au;N.withProxy=lu;function au(...t){let e=i=>typeof i=="function";return i=>su(this,void 0,void 0,function*(){let r=Object.assign({},i);for(let n of t.filter(e))r=yield n(r);return r})}N.TARGET_URL_HEADER="x-fal-target-url";function lu(t){let e=i=>Promise.resolve(i);return typeof window>"u"?e:i=>i.headers&&N.TARGET_URL_HEADER in i?e(i):Promise.resolve(Object.assign(Object.assign({},i),{url:t.targetUrl,headers:Object.assign(Object.assign({},i.headers||{}),{[N.TARGET_URL_HEADER]:i.url})}))}});var lt=_(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.RUNNER_HINT_HEADER=q.QUEUE_PRIORITY_HEADER=q.REQUEST_TIMEOUT_TYPE_HEADER=q.REQUEST_TIMEOUT_HEADER=q.MIN_REQUEST_TIMEOUT_SECONDS=void 0;q.validateTimeoutHeader=dr;q.buildTimeoutHeaders=uu;q.MIN_REQUEST_TIMEOUT_SECONDS=1;q.REQUEST_TIMEOUT_HEADER="x-fal-request-timeout";q.REQUEST_TIMEOUT_TYPE_HEADER="x-fal-request-timeout-type";q.QUEUE_PRIORITY_HEADER="x-fal-queue-priority";q.RUNNER_HINT_HEADER="x-fal-runner-hint";function dr(t){if(typeof t!="number"||isNaN(t))throw new Error(`Timeout must be a number, got ${t}`);if(t<=q.MIN_REQUEST_TIMEOUT_SECONDS)throw new Error(`Timeout must be greater than ${q.MIN_REQUEST_TIMEOUT_SECONDS} seconds`);return t.toString()}function uu(t){return t===void 0?{}:{[q.REQUEST_TIMEOUT_HEADER]:dr(t)}}});var ee=_(z=>{"use strict";var cr=z&&z.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})};Object.defineProperty(z,"__esModule",{value:!0});z.ValidationError=z.ApiError=void 0;z.defaultResponseHandler=mr;z.resultResponseHandler=cu;var du=lt(),pr="x-fal-request-id",Ie=class extends Error{constructor({message:e,status:i,body:r,requestId:n,timeoutType:o}){super(e),this.name="ApiError",this.status=i,this.body=r,this.requestId=n||"",this.timeoutType=o}get isUserTimeout(){return this.status===504&&this.timeoutType==="user"}};z.ApiError=Ie;var ut=class extends Ie{constructor(e){super(e),this.name="ValidationError"}get fieldErrors(){return typeof this.body.detail=="string"?[{loc:["body"],msg:this.body.detail,type:"value_error"}]:this.body.detail||[]}getFieldErrors(e){return this.fieldErrors.filter(i=>i.loc[i.loc.length-1]===e)}};z.ValidationError=ut;function mr(t){return cr(this,void 0,void 0,function*(){var e;let{status:i,statusText:r}=t,n=(e=t.headers.get("Content-Type"))!==null&&e!==void 0?e:"",o=t.headers.get(pr)||void 0,s=t.headers.get(du.REQUEST_TIMEOUT_TYPE_HEADER)||void 0;if(!t.ok){if(n.includes("application/json")){let l=yield t.json(),u=i===422?ut:Ie;throw new u({message:l.message||r,status:i,body:l,requestId:o,timeoutType:s})}throw new Ie({message:`HTTP ${i}: ${r}`,status:i,requestId:o,timeoutType:s})}return n.includes("application/json")?t.json():n.includes("text/html")?t.text():n.includes("application/octet-stream")?t.arrayBuffer():t.text()})}function cu(t){return cr(this,void 0,void 0,function*(){return{data:yield mr(t),requestId:t.headers.get(pr)||""}})}});var te=_(U=>{"use strict";var pu=U&&U.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})};Object.defineProperty(U,"__esModule",{value:!0});U.ensureEndpointIdFormat=fr;U.parseEndpointId=fu;U.isValidUrl=gu;U.throttle=hu;U.isReact=yu;U.isPlainObject=bu;U.sleep=vu;function fr(t){if(t.split("/").length>1)return t;let[,i,r]=/^([0-9]+)-([a-zA-Z0-9-]+)$/.exec(t)||[];if(i&&r)return`${i}/${r}`;throw new Error(`Invalid app id: ${t}. Must be in the format <appOwner>/<appId>`)}var mu=["workflows","comfy"];function fu(t){let i=fr(t).split("/");return mu.includes(i[0])?{owner:i[1],alias:i[2],path:i.slice(3).join("/")||void 0,namespace:i[0]}:{owner:i[0],alias:i[1],path:i.slice(2).join("/")||void 0}}function gu(t){try{let{host:e}=new URL(t);return/(fal\.(ai|run))$/.test(e)}catch{return!1}}function hu(t,e,i=!1){let r,n;return(...o)=>{!n&&i?(t(...o),n=Date.now()):(r&&clearTimeout(r),r=setTimeout(()=>{Date.now()-n>=e&&(t(...o),n=Date.now())},e-(Date.now()-n)))}}var Ht;function yu(){if(Ht===void 0){let t=new Error().stack;Ht=!!t&&(t.includes("node_modules/react-dom/")||t.includes("node_modules/next/"))}return Ht}function bu(t){return!!t&&Object.getPrototypeOf(t)===Object.prototype}function vu(t){return pu(this,void 0,void 0,function*(){return new Promise(e=>setTimeout(e,t))})}});var Ne=_(j=>{"use strict";var wu=j&&j.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})};Object.defineProperty(j,"__esModule",{value:!0});j.DEFAULT_RETRY_OPTIONS=j.DEFAULT_RETRYABLE_STATUS_CODES=void 0;j.isRetryableError=gr;j.calculateBackoffDelay=hr;j.executeWithRetry=Tu;var _u=ee(),xu=te();j.DEFAULT_RETRYABLE_STATUS_CODES=[429,502,503,504];j.DEFAULT_RETRY_OPTIONS={maxRetries:3,baseDelay:1e3,maxDelay:3e4,backoffMultiplier:2,retryableStatusCodes:j.DEFAULT_RETRYABLE_STATUS_CODES,enableJitter:!0};function gr(t,e){return!(t instanceof _u.ApiError)||t.isUserTimeout?!1:e.includes(t.status)}function hr(t,e,i,r,n){let o=Math.min(e*Math.pow(r,t),i);if(n){let s=.25*o*(Math.random()*2-1);return Math.max(0,o+s)}return o}function Tu(t,e,i){return wu(this,void 0,void 0,function*(){let r={totalAttempts:0,totalDelay:0},n;for(let o=0;o<=e.maxRetries;o++){r.totalAttempts++;try{return{result:yield t(),metrics:r}}catch(s){if(n=s,r.lastError=s,o===e.maxRetries||!gr(s,e.retryableStatusCodes))throw s;let l=hr(o,e.baseDelay,e.maxDelay,e.backoffMultiplier,e.enableJitter);r.totalDelay+=l,i&&i(o+1,s,l),yield(0,xu.sleep)(l)}}throw n})}});var yr=_((Qg,Iu)=>{Iu.exports={name:"@fal-ai/client",description:"The fal.ai client for JavaScript and TypeScript",version:"1.9.0",license:"MIT",repository:{type:"git",url:"https://github.com/fal-ai/fal-js.git",directory:"libs/client"},keywords:["fal","client","ai","ml","typescript"],exports:{".":"./src/index.js","./endpoints":"./src/types/endpoints.js"},typesVersions:{"*":{endpoints:["src/types/endpoints.d.ts"]}},main:"./src/index.js",types:"./src/index.d.ts",dependencies:{"@msgpack/msgpack":"^3.0.0-beta2","eventsource-parser":"^1.1.2",robot3:"^0.4.1"},engines:{node:">=18.0.0"},type:"commonjs"}});var pt=_(ct=>{"use strict";Object.defineProperty(ct,"__esModule",{value:!0});ct.isBrowser=Su;ct.getUserAgent=Eu;function Su(){return typeof window<"u"&&typeof window.document<"u"}var dt=null;function Eu(){if(dt!==null)return dt;let t=yr();return dt=`${t.name}/${t.version}`,dt}});var mt=_(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.credentialsFromEnv=void 0;ie.resolveDefaultFetch=wr;ie.createConfig=Vu;ie.getRestApiUrl=Mu;var br=Kt(),Au=ee(),vr=Ne(),Cu=pt();function wr(){if(typeof fetch>"u")throw new Error("Your environment does not support fetch. Please provide your own fetch implementation.");return fetch}function ku(){return typeof process<"u"&&process.env&&(typeof process.env.FAL_KEY<"u"||typeof process.env.FAL_KEY_ID<"u"&&typeof process.env.FAL_KEY_SECRET<"u")}var Pu=()=>{if(ku())return typeof process.env.FAL_KEY<"u"?process.env.FAL_KEY:process.env.FAL_KEY_ID?`${process.env.FAL_KEY_ID}:${process.env.FAL_KEY_SECRET}`:void 0};ie.credentialsFromEnv=Pu;var qu={credentials:ie.credentialsFromEnv,suppressLocalCredentialsWarning:!1,requestMiddleware:t=>Promise.resolve(t),responseHandler:Au.defaultResponseHandler,retry:vr.DEFAULT_RETRY_OPTIONS};function Vu(t){var e;let i=Object.assign(Object.assign(Object.assign({},qu),t),{fetch:(e=t.fetch)!==null&&e!==void 0?e:wr(),retry:Object.assign(Object.assign({},vr.DEFAULT_RETRY_OPTIONS),t.retry||{})});t.proxyUrl&&(i=Object.assign(Object.assign({},i),{requestMiddleware:(0,br.withMiddleware)(i.requestMiddleware,(0,br.withProxy)({targetUrl:t.proxyUrl}))}));let{credentials:r,suppressLocalCredentialsWarning:n}=i,o=typeof r=="function"?r():r;return(0,Cu.isBrowser)()&&o&&!n&&console.warn("The fal credentials are exposed in the browser's environment. That's not recommended for production use cases."),i}function Mu(){return"https://rest.alpha.fal.ai"}});var Se=_(re=>{"use strict";var _r=re&&re.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})},Du=re&&re.__rest||function(t,e){var i={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(i[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(t);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(i[r[n]]=t[r[n]]);return i};Object.defineProperty(re,"__esModule",{value:!0});re.dispatchRequest=Ou;re.buildUrl=Fu;var xr=Ne(),Tr=pt(),Gt=te(),ju=typeof navigator<"u"&&navigator?.userAgent==="Cloudflare-Workers";function Ou(t){return _r(this,void 0,void 0,function*(){var e;let{targetUrl:i,input:r,config:n,options:o={}}=t,{credentials:s,requestMiddleware:l,responseHandler:u,fetch:d}=n,a=Object.assign(Object.assign({},n.retry),o.retry||{}),c=()=>_r(this,void 0,void 0,function*(){var p,g,h;let b=(0,Tr.isBrowser)()?{}:{"User-Agent":(0,Tr.getUserAgent)()},f=typeof s=="function"?s():s,{method:v,url:C,headers:T}=yield l({method:((g=(p=t.method)!==null&&p!==void 0?p:o.method)!==null&&g!==void 0?g:"post").toUpperCase(),url:i,headers:t.headers}),M=f?{Authorization:`Key ${f}`}:{},$=Object.assign(Object.assign(Object.assign(Object.assign({},M),{Accept:"application/json","Content-Type":"application/json"}),b),T??{}),{responseHandler:le,retry:nt}=o,ge=Du(o,["responseHandler","retry"]),H=yield d(C,Object.assign(Object.assign(Object.assign(Object.assign({},ge),{method:v,headers:Object.assign(Object.assign({},$),(h=ge.headers)!==null&&h!==void 0?h:{})}),!ju&&{mode:"cors"}),{signal:o.signal,body:v.toLowerCase()!=="get"&&r?JSON.stringify(r):void 0}));return yield(le??u)(H)}),m;for(let p=0;p<=a.maxRetries;p++)try{return yield c()}catch(g){if(m=g,p===a.maxRetries||!(0,xr.isRetryableError)(g,a.retryableStatusCodes)||((e=o.signal)===null||e===void 0?void 0:e.aborted))throw g;let b=(0,xr.calculateBackoffDelay)(p,a.baseDelay,a.maxDelay,a.backoffMultiplier,a.enableJitter);yield(0,Gt.sleep)(b)}throw m})}function Fu(t,e={}){var i,r;let n=((i=e.method)!==null&&i!==void 0?i:"post").toLowerCase(),o=((r=e.path)!==null&&r!==void 0?r:"").replace(/^\//,"").replace(/\/{2,}/,"/"),s=e.input,l=Object.assign(Object.assign({},e.query||{}),n==="get"?s:{}),u=Object.keys(l).length>0?`?${new URLSearchParams(l).toString()}`:"";if((0,Gt.isValidUrl)(t))return`${t.endsWith("/")?t:`${t}/`}${o}${u}`;let d=(0,Gt.ensureEndpointIdFormat)(t);return`${`https://${e.subdomain?`${e.subdomain}.`:""}fal.run/${d}/${o}`.replace(/\/$/,"")}${u}`}});var Wt=_(B=>{"use strict";var de=B&&B.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})};Object.defineProperty(B,"__esModule",{value:!0});B.OBJECT_LIFECYCYLE_PREFERENCE_HEADER=void 0;B.getExpirationDurationSeconds=Qt;B.buildObjectLifecycleHeaders=Lu;B.createStorageClient=Bu;var Ir=mt(),Sr=Se(),Ru=te();B.OBJECT_LIFECYCYLE_PREFERENCE_HEADER="x-fal-object-lifecycle-preference";var Uu={never:31536e5,immediate:void 0,"1h":3600,"1d":86400,"7d":604800,"30d":2592e3,"1y":31536e3};function Qt(t){let{expiresIn:e}=t;return typeof e=="number"?e:Uu[e]}function Lu(t){if(!t)return{};let e=Qt(t);return e===void 0?{}:{[B.OBJECT_LIFECYCYLE_PREFERENCE_HEADER]:JSON.stringify({expiration_duration_seconds:e})}}function Er(t){var e;let[,i]=t.split("/");return(e=i.split(/[-;]/)[0])!==null&&e!==void 0?e:"bin"}function $u(t,e,i,r){return de(this,void 0,void 0,function*(){let n=t.name||`${Date.now()}.${Er(i)}`,o={};if(r){let s={expiration_duration_seconds:Qt(r),allow_io_storage:r.expiresIn!=="immediate"};o["X-Fal-Object-Lifecycle"]=JSON.stringify(s)}return yield(0,Sr.dispatchRequest)({method:"POST",targetUrl:`${(0,Ir.getRestApiUrl)()}/storage/upload/initiate?storage_type=fal-cdn-v3`,input:{content_type:i,file_name:n},config:e,headers:o})})}function Nu(t,e,i,r){return de(this,void 0,void 0,function*(){let n=t.name||`${Date.now()}.${Er(i)}`,o={};return r&&(o["X-Fal-Object-Lifecycle"]=JSON.stringify(r)),yield(0,Sr.dispatchRequest)({method:"POST",targetUrl:`${(0,Ir.getRestApiUrl)()}/storage/upload/initiate-multipart?storage_type=fal-cdn-v3`,input:{content_type:i,file_name:n},config:e,headers:o})})}function Ar(t,e,i){return de(this,arguments,void 0,function*(r,n,o,s=3){if(s===0)throw new Error("Part upload failed, retries exhausted");let{fetch:l,responseHandler:u}=o;try{let d=yield l(r,{method:"PUT",body:n});return yield u(d)}catch{return yield Ar(r,n,o,s-1)}})}function zu(t,e,i){return de(this,void 0,void 0,function*(){let{fetch:r,responseHandler:n}=e,o=t.type||"application/octet-stream",{upload_url:s,file_url:l}=yield Nu(t,e,o,i),u=10*1024*1024,d=Math.ceil(t.size/u),a=new URL(s),c=[];for(let g=0;g<d;g++){let h=g*u,b=Math.min(h+u,t.size),f=t.slice(h,b),v=g+1,C=`${a.origin}${a.pathname}/${v}${a.search}`;c.push(yield Ar(C,f,e))}let m=`${a.origin}${a.pathname}/complete${a.search}`,p=yield r(m,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({parts:c.map(g=>({partNumber:g.partNumber,etag:g.etag}))})});return yield n(p),l})}function Bu({config:t}){let e={upload:(i,r)=>de(this,void 0,void 0,function*(){let n=r?.lifecycle;if(i.size>94371840)return yield zu(i,t,n);let o=i.type||"application/octet-stream",{fetch:s,responseHandler:l}=t,{upload_url:u,file_url:d}=yield $u(i,t,o,n),a=yield s(u,{method:"PUT",body:i,headers:{"Content-Type":i.type||"application/octet-stream"}});return yield l(a),d}),transformInput:i=>de(this,void 0,void 0,function*(){if(Array.isArray(i))return Promise.all(i.map(r=>e.transformInput(r)));if(i instanceof Blob)return yield e.upload(i);if((0,Ru.isPlainObject)(i)){let n=Object.entries(i).map(s=>de(this,[s],void 0,function*([l,u]){return[l,yield e.transformInput(u)]})),o=yield Promise.all(n);return Object.fromEntries(o)}return i})};return e}});var kr=_(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});function Ku(t){let e,i,r,n,o,s,l;return u(),{feed:d,reset:u};function u(){e=!0,i="",r=0,n=-1,o=void 0,s=void 0,l=""}function d(c){i=i?i+c:c,e&&Hu(i)&&(i=i.slice(Cr.length)),e=!1;let m=i.length,p=0,g=!1;for(;p<m;){g&&(i[p]===` `&&++p,g=!1);let h=-1,b=n,f;for(let v=r;h<0&&v<m;++v)f=i[v],f===":"&&b<0?b=v-p:f==="\r"?(g=!0,h=v-p):f===` `&&(h=v-p);if(h<0){r=m-p,n=b;break}else r=0,n=-1;a(i,p,b,h),p+=h+1}p===m?i="":p>0&&(i=i.slice(p))}function a(c,m,p,g){if(g===0){l.length>0&&(t({type:"event",id:o,event:s||void 0,data:l.slice(0,-1)}),l="",o=void 0),s=void 0;return}let h=p<0,b=c.slice(m,m+(h?g:p)),f=0;h?f=g:c[m+p+1]===" "?f=p+2:f=p+1;let v=m+f,C=g-f,T=c.slice(v,v+C).toString();if(b==="data")l+=T?"".concat(T,` `):` `;else if(b==="event")s=T;else if(b==="id"&&!T.includes("\0"))o=T;else if(b==="retry"){let M=parseInt(T,10);Number.isNaN(M)||t({type:"reconnect-interval",value:M})}}}var Cr=[239,187,191];function Hu(t){return Cr.every((e,i)=>t.charCodeAt(i)===e)}Yt.createParser=Ku});var Zt=_(ne=>{"use strict";var Gu=ne&&ne.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})};Object.defineProperty(ne,"__esModule",{value:!0});ne.TOKEN_EXPIRATION_SECONDS=void 0;ne.getTemporaryAuthToken=Zu;var Qu=mt(),Wu=Se(),Yu=te();ne.TOKEN_EXPIRATION_SECONDS=120;function Zu(t,e){return Gu(this,void 0,void 0,function*(){let i=(0,Yu.parseEndpointId)(t),r=yield(0,Wu.dispatchRequest)({method:"POST",targetUrl:`${(0,Qu.getRestApiUrl)()}/tokens/`,config:e,input:{allowed_apps:[i.alias],token_expiration:ne.TOKEN_EXPIRATION_SECONDS}});return typeof r!="string"&&r.detail?r.detail:r})}});var Xt=_(L=>{"use strict";var Ae=L&&L.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})},ze=L&&L.__await||function(t){return this instanceof ze?(this.v=t,this):new ze(t)},Ju=L&&L.__asyncGenerator||function(t,e,i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=i.apply(t,e||[]),n,o=[];return n={},l("next"),l("throw"),l("return",s),n[Symbol.asyncIterator]=function(){return this},n;function s(p){return function(g){return Promise.resolve(g).then(p,c)}}function l(p,g){r[p]&&(n[p]=function(h){return new Promise(function(b,f){o.push([p,h,b,f])>1||u(p,h)})},g&&(n[p]=g(n[p])))}function u(p,g){try{d(r[p](g))}catch(h){m(o[0][3],h)}}function d(p){p.value instanceof ze?Promise.resolve(p.value.v).then(a,c):m(o[0][2],p)}function a(p){u("next",p)}function c(p){u("throw",p)}function m(p,g){p(g),o.shift(),o.length&&u(o[0][0],o[0][1])}};Object.defineProperty(L,"__esModule",{value:!0});L.FalStream=void 0;L.createStreamingClient=id;var Xu=kr(),ed=Zt(),Pr=Se(),Ee=ee(),Jt="text/event-stream",td=15*1e3,ft=class{constructor(e,i,r){var n;this.listeners=new Map,this.buffer=[],this.currentData=void 0,this.lastEventTimestamp=0,this.streamClosed=!1,this._requestId=null,this.abortController=new AbortController,this.start=()=>Ae(this,void 0,void 0,function*(){var o,s;let{endpointId:l,options:u}=this,{input:d,method:a="post",connectionMode:c="server",tokenProvider:m}=u;try{if(c==="client"){let g=yield(m?()=>m(l):()=>(console.warn('[fal.stream] Using the default token provider is deprecated. Please provide a `tokenProvider` function when using `connectionMode: "client"`. See https://docs.fal.ai/fal-client/authentication for more information.'),(0,ed.getTemporaryAuthToken)(l,this.config)))(),{fetch:h}=this.config,b=new URL(this.url);b.searchParams.set("fal_jwt_token",g);let f=yield h(b.toString(),{method:a.toUpperCase(),headers:{accept:(o=u.accept)!==null&&o!==void 0?o:Jt,"content-type":"application/json"},body:d&&a!=="get"?JSON.stringify(d):void 0,signal:this.abortController.signal});return this._requestId=f.headers.get("x-fal-request-id"),yield this.handleResponse(f)}return yield(0,Pr.dispatchRequest)({method:a.toUpperCase(),targetUrl:this.url,input:d,config:this.config,options:{headers:{accept:(s=u.accept)!==null&&s!==void 0?s:Jt},responseHandler:p=>Ae(this,void 0,void 0,function*(){return this._requestId=p.headers.get("x-fal-request-id"),yield this.handleResponse(p)}),signal:this.abortController.signal}})}catch(p){this.handleError(p)}}),this.handleResponse=o=>Ae(this,void 0,void 0,function*(){var s,l;if(!o.ok){try{yield(0,Ee.defaultResponseHandler)(o)}catch(h){this.emit("error",h)}return}let u=o.body;if(!u){this.emit("error",new Ee.ApiError({message:"Response body is empty.",status:400,body:void 0,requestId:this._requestId||void 0}));return}if(!((s=o.headers.get("content-type"))!==null&&s!==void 0?s:"").startsWith(Jt)){let h=u.getReader(),b=()=>{h.read().then(({done:f,value:v})=>{if(f){this.emit("done",this.currentData);return}this.buffer.push(v),this.currentData=v,this.emit("data",v),b()})};b();return}let a=new TextDecoder("utf-8"),c=o.body.getReader(),m=(0,Xu.createParser)(h=>{if(h.type==="event"){let b=h.data;try{let f=JSON.parse(b);this.buffer.push(f),this.currentData=f,this.emit("data",f),this.emit("message",f)}catch(f){this.emit("error",f)}}}),p=(l=this.options.timeout)!==null&&l!==void 0?l:td,g=()=>Ae(this,void 0,void 0,function*(){let{value:h,done:b}=yield c.read();this.lastEventTimestamp=Date.now(),m.feed(a.decode(h)),Date.now()-this.lastEventTimestamp>p&&this.emit("error",new Ee.ApiError({message:`Event stream timed out after ${(p/1e3).toFixed(0)} seconds with no messages.`,status:408,requestId:this._requestId||void 0})),b?this.emit("done",this.currentData):g().catch(this.handleError)});g().catch(this.handleError)}),this.handleError=o=>{var s;if(o.name==="AbortError"||this.signal.aborted)return;let l=o instanceof Ee.ApiError?o:new Ee.ApiError({message:(s=o.message)!==null&&s!==void 0?s:"An unknown error occurred",status:500,requestId:this._requestId||void 0});this.emit("error",l)},this.on=(o,s)=>{var l;this.listeners.has(o)||this.listeners.set(o,[]),(l=this.listeners.get(o))===null||l===void 0||l.push(s)},this.emit=(o,s)=>{let l=this.listeners.get(o)||[];for(let u of l)u(s)},this.done=()=>Ae(this,void 0,void 0,function*(){return this.donePromise}),this.abort=o=>{this.streamClosed||this.abortController.abort(o)},this.endpointId=e,this.config=i,this.url=(n=r.url)!==null&&n!==void 0?n:(0,Pr.buildUrl)(e,{path:"/stream",query:r.queryParams}),this.options=r,this.donePromise=new Promise((o,s)=>{this.streamClosed&&s(new Ee.ApiError({message:"Streaming connection is already closed.",status:400,body:void 0,requestId:this._requestId||void 0})),this.signal.addEventListener("abort",()=>{var l;o((l=this.currentData)!==null&&l!==void 0?l:{})}),this.on("done",l=>{this.streamClosed=!0,o(l)}),this.on("error",l=>{this.streamClosed=!0,s(l)})}),r.signal&&r.signal.addEventListener("abort",()=>{this.abortController.abort()}),this.start().catch(this.handleError)}[Symbol.asyncIterator](){return Ju(this,arguments,function*(){let i=!0,r=()=>i=!1;for(this.on("error",r),this.on("done",r);i||this.buffer.length>0;){let n=this.buffer.shift();n&&(yield yield ze(n)),yield ze(new Promise(o=>setTimeout(o,16)))}})}get signal(){return this.abortController.signal}get requestId(){return this._requestId}};L.FalStream=ft;function id({config:t,storage:e}){return{stream(i,r){return Ae(this,void 0,void 0,function*(){let n=r.input?yield e.transformInput(r.input):void 0;return new ft(i,t,Object.assign(Object.assign({},r),{input:n}))})}}}});var Dr=_(oe=>{"use strict";var ce=oe&&oe.__awaiter||function(t,e,i,r){function n(o){return o instanceof i?o:new i(function(s){s(o)})}return new(i||(i=Promise))(function(o,s){function l(a){try{d(r.next(a))}catch(c){s(c)}}function u(a){try{d(r.throw(a))}catch(c){s(c)}}function d(a){a.done?o(a.value):n(a.value).then(l,u)}d((r=r.apply(t,e||[])).next())})},rd=oe&&oe.__rest||function(t,e){var i={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(i[r]=t[r]);if(t!=null&&typeof Object.getOwnPropertySymbols=="function")for(var n=0,r=Object.getOwnPropertySymbols(t);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(i[r[n]]=t[r[n]]);return i};Object.defineProperty(oe,"__esModule",{value:!0});oe.createQueueClient=void 0;var ei=lt(),Q=Se(),nd=ee(),Mr=Ne(),od=Wt(),sd=Xt(),gt=te(),qr=500,Vr={maxRetries:3,baseDelay:1e3,maxDelay:6e4,retryableStatusCodes:Mr.DEFAULT_RETRYABLE_STATUS_CODES},ad={maxRetries:5,baseDelay:1e3,maxDelay:3e4,retryableStatusCodes:[...Mr.DEFAULT_RETRYABLE_STATUS_CODES,500]},ld=({config:t,storage:e})=>{let i={submit(r,n){return ce(this,void 0,void 0,function*(){let{webhookUrl:o,priority:s,hint:l,startTimeout:u,headers:d,storageSettings:a}=n,c=rd(n,["webhookUrl","priority","hint","startTimeout","headers","storageSettings"]),m=n.input?yield e.transformInput(n.input):void 0,p=Object.fromEntries(Object.entries(d??{}).map(([g,h])=>[g.toLowerCase(),h]));return(0,Q.dispatchRequest)({method:n.method,targetUrl:(0,Q.buildUrl)(r,Object.assign(Object.assign({},c),{subdomain:"queue",query:o?{fal_webhook:o}:void 0})),headers:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},p),(0,od.buildObjectLifecycleHeaders)(a)),{[ei.QUEUE_PRIORITY_HEADER]:s??"normal"}),l&&{[ei.RUNNER_HINT_HEADER]:l}),(0,ei.buildTimeoutHeaders)(u)),input:m,config:t,options:{signal:n.abortSignal,retry:Vr}})})},status(r,n){return ce(this,arguments,void 0,function*(o,{requestId:s,logs:l=!1,abortSignal:u}){let d=(0,gt.parseEndpointId)(o),a=d.namespace?`${d.namespace}/`:"";return(0,Q.dispatchRequest)({method:"get",targetUrl:(0,Q.buildUrl)(`${a}${d.owner}/${d.alias}`,{subdomain:"queue",query:{logs:l?"1":"0"},path:`/requests/${s}/status`}),config:t,options:{signal:u,retry:ad}})})},streamStatus(r,n){return ce(this,arguments,void 0,function*(o,{requestId:s,logs:l=!1,connectionMode:u}){let d=(0,gt.parseEndpointId)(o),a=d.namespace?`${d.namespace}/`:"",c={logs:l?"1":"0"},m=(0,Q.buildUrl)(`${a}${d.owner}/${d.alias}`,{subdomain:"queue",path:`/requests/${s}/status/stream`,query:c});return new sd.FalStream(o,t,{url:m,method:"get",connectionMode:u,queryParams:c})})},subscribeToStatus(r,n){return ce(this,void 0,void 0,function*(){let o=n.requestId,s=n.timeout,l,u=()=>{};if(n.mode==="streaming"){let d=yield i.streamStatus(r,{requestId:o,logs:n.logs,connectionMode:"connectionMode"in n?n.connectionMode:void 0}),a=[];s&&(l=setTimeout(()=>{throw d.abort(),i.cancel(r,{requestId:o}).catch(u),new Error(`Client timed out waiting for the request to complete after ${s}ms`)},s)),d.on("data",m=>{n.onQueueUpdate&&("logs"in m&&Array.isArray(m.logs)&&m.logs.length>0&&a.push(...m.logs),n.onQueueUpdate("logs"in m?Object.assign(Object.assign({},m),{logs:a}):m))});let c=yield d.done();return l&&clearTimeout(l),c}return new Promise((d,a)=>{var c;let m,p="pollInterval"in n&&typeof n.pollInterval=="number"&&(c=n.pollInterval)!==null&&c!==void 0?c:qr,g=()=>{l&&clearTimeout(l),m&&clearTimeout(m)};s&&(l=setTimeout(()=>{g(),i.cancel(r,{requestId:o}).catch(u),a(new Error(`Client timed out waiting for the request to complete after ${s}ms`))},s));let h=()=>ce(this,void 0,void 0,function*(){var b;try{let f=yield i.status(r,{requestId:o,logs:(b=n.logs)!==null&&b!==void 0?b:!1,abortSignal:n.abortSignal});if(n.onQueueUpdate&&n.onQueueUpdate(f),f.status==="COMPLETED"){g(),d(f);return}m=setTimeout(h,p)}catch(f){g(),a(f)}});h().catch(a)})})},result(r,n){return ce(this,arguments,void 0,function*(o,{requestId:s,abortSignal:l}){let u=(0,gt.parseEndpointId)(o),d=u.namespace?`${u.namespace}/`:"";return(0,Q.dispatchRequest)({method:"get",targetUrl:(0,Q.buildUrl)(`${d}${u.owner}/${u.alias}`,{subdomain:"queue",path:`/requests/${s}`}),config:Object.assign(Object.assign({},t),{responseHandler:nd.resultResponseHandler}),options:{signal:l,retry:Vr}})})},cancel(r,n){return ce(this,arguments,void 0,function*(o,{requestId:s,abortSignal:l}){let u=(0,gt.parseEndpointId)(o),d=u.namespace?`${u.namespace}/`:"";yield(0,Q.dispatchRequest)({method:"put",targetUrl:(0,Q.buildUrl)(`${d}${u.owner}/${u.alias}`,{subdomain:"queue",path:`/requests/${s}/cancel`}),config:t,options:{signal:l}})})}};return i};oe.createQueueClient=ld});var ht=_(W=>{"use strict";Object.defineProperty(W,"__esModule",{value:!0});W.utf8Count=ud;W.utf8EncodeJs=jr;W.utf8EncodeTE=Or;W.utf8Encode=pd;W.utf8DecodeJs=Fr;W.utf8DecodeTD=Rr;W.utf8Decode=hd;function ud(t){let e=t.length,i=0,r=0;for(;r<e;){let n=t.charCodeAt(r++);if(n&4294967168)if(!(n&4294965248))i+=2;else{if(n>=55296&&n<=56319&&r<e){let o=t.charCodeAt(r);(o&64512)===56320&&(++r,n=((n&1023)<<10)+(o&1023)+65536)}n&4294901760?i+=4:i+=3}else{i++;continue}}return i}function jr(t,e,i){let r=t.length,n=i,o=0;for(;o<r;){let s=t.charCodeAt(o++);if(s&4294967168)if(!(s&4294965248))e[n++]=s>>6&31|192;else{if(s>=55296&&s<=56319&&o<r){let l=t.charCodeAt(o);(l&64512)===56320&&(++o,s=((s&1023)<<10)+(l&1023)+65536)}s&4294901760?(e[n++]=s>>18&7|240,e[n++]=s>>12&63|128,e[n++]=s>>6&63|128):(e[n++]=s>>12&15|224,e[n++]=s>>6&63|128)}else{e[n++]=s;continue}e[n++]=s&63|128}}var dd=new TextEncoder,cd=50;function Or(t,e,i){dd.encodeInto(t,e.subarray(i))}function pd(t,e,i){t.length>cd?Or(t,e,i):jr(t,e,i)}var md=4096;function Fr(t,e,i){let r=e,n=r+i,o=[],s="";for(;r<n;){let l=t[r++];if(!(l&128))o.push(l);else if((l&224)===192){let u=t[r++]&63;o.push((l&31)<<6|u)}else if((l&240)===224){let u=t[r++]&63,d=t[r++]&63;o.push((l&31)<<12|u<<6|d)}else if((l&248)===240){let u=t[r++]&63,d=t[r++]&63,a=t[r++]&63,c=(l&7)<<18|u<<12|d<<6|a;c>65535&&(c-=65536,o.push(c>>>10&1023|55296),c=56320|c&1023),o.push(c)}else o.push(l);o.length>=md&&(s+=String.fromCharCode(...o),o.length=0)}return o.length>0&&(s+=String.fromCharCode(...o)),s}var fd=new TextDecoder,gd=200;function Rr(t,e,i){let r=t.subarray(e,e+i);return fd.decode(r)}function hd(t,e,i){return i>gd?Rr(t,e,i):Fr(t,e,i)}});var ii=_(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.ExtData=void 0;var ti=class{type;data;constructor(e,i){this.type=e,this.data=i}};yt.ExtData=ti});var vt=_(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.DecodeError=void 0;var ri=class t extends Error{constructor(e){super(e);let i=Object.create(t.prototype);Object.setPrototypeOf(this,i),Object.defineProperty(this,"name",{configurable:!0,enumerable:!1,value:t.name})}};bt.DecodeError=ri});var wt=_(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.UINT32_MAX=void 0;se.setUint64=yd;se.setInt64=bd;se.getInt64=vd;se.getUint64=wd;se.UINT32_MAX=4294967295;function yd(t,e,i){let r=i/4294967296,n=i;t.setUint32(e,r),t.setUint32(e+4,n)}function bd(t,e,i){let r=Math.floor(i/4294967296),n=i;t.setUint32(e,r),t.setUint32(e+4,n)}function vd(t,e){let i=t.getInt32(e),r=t.getUint32(e+4);return i*4294967296+r}function wd(t,e){let i=t.getUint32(e),r=t.getUint32(e+4);return i*4294967296+r}});var ni=_(O=>{"use strict";Object.defineProperty(O,"__esModule",{value:!0});O.timestampExtension=O.EXT_TIMESTAMP=void 0;O.encodeTimeSpecToTimestamp=Lr;O.encodeDateToTimeSpec=$r;O.encodeTimestampExtension=Nr;O.decodeTimestampToTimeSpec=zr;O.decodeTimestampExtension=Br;var _d=vt(),Ur=wt();O.EXT_TIMESTAMP=-1;var xd=4294967296-1,Td=17179869184-1;function Lr({sec:t,nsec:e}){if(t>=0&&e>=0&&t<=Td)if(e===0&&t<=xd){let i=new Uint8Array(4);return new DataView(i.buffer).setUint32(0,t),i}else{let i=t/4294967296,r=t&4294967295,n=new Uint8Array(8),o=new DataView(n.buffer);return o.setUint32(0,e<<2|i&3),o.setUint32(4,r),n}else{let i=new Uint8Array(12),r=new DataView(i.buffer);return r.setUint32(0,e),(0,Ur.setInt64)(r,4,t),i}}function $r(t){let e=t.getTime(),i=Math.floor(e/1e3),r=(e-i*1e3)*1e6,n=Math.floor(r/1e9);return{sec:i+n,nsec:r-n*1e9}}function Nr(t){if(t instanceof Date){let e=$r(t);return Lr(e)}else return null}function zr(t){let e=new DataView(t.buffer,t.byteOffset,t.byteLength);switch(t.byteLength){case 4:return{sec:e.getUint32(0),nsec:0};case 8:{let i=e.getUint32(0),r=e.getUint32(4),n=(i&3)*4294967296+r,o=i>>>2;return{sec:n,nsec:o}}case 12:{let i=(0,Ur.getInt64)(e,4),r=e.getUint32(0);return{sec:i,nsec:r}}default:throw new _d.DecodeError(`Unrecognized data size for timestamp (expected 4, 8, or 12): ${t.length}`)}}function Br(t){let e=zr(t);return new Date(e.sec*1e3+e.nsec/1e6)}O.timestampExtension={type:O.EXT_TIMESTAMP,encode:Nr,decode:Br}});var Tt=_(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.ExtensionCodec=void 0;var _t=ii(),Id=ni(),oi=class t{static defaultCodec=new t;__brand;builtInEncoders=[];builtInDecoders=[];encoders=[];decoders=[];constructor(){this.register(Id.timestampExtension)}register({type:e,encode:i,decode:r}){if(e>=0)this.encoders[e]=i,this.decoders[e]=r;else{let n=-1-e;this.builtInEncoders[n]=i,this.builtInDecoders[n]=r}}tryToEncode(e,i){for(let r=0;r<this.builtInEncoders.length;r++){let n=this.builtInEncoders[r];if(n!=null){let o=n(e,i);if(o!=null){let s=-1-r;return new _t.ExtData(s,o)}}}for(let r=0;r<this.encoders.length;r++){let n=this.encoders[r];if(n!=null){let o=n(e,i);if(o!=null){let s=r;return new _t.ExtData(s,o)}}}return e instanceof _t.ExtData?e:null}decode(e,i,r){let n=i<0?this.builtInDecoders[-1-i]:this.decoders[i];return n?n(e,i,r):new _t.ExtData(i,e)}};xt.ExtensionCodec=oi});var ai=_(si=>{"use strict";Object.defineProperty(si,"__esModule",{value:!0});si.ensureUint8Array=Ed;function Sd(t){return t instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&t instanceof SharedArrayBuffer}function Ed(t){return t instanceof Uint8Array?t:ArrayBuffer.isView(t)?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Sd(t)?new Uint8Array(t):Uint8Array.from(t)}});var ui=_(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.Encoder=K.DEFAULT_INITIAL_BUFFER_SIZE=K.DEFAULT_MAX_DEPTH=void 0;var Kr=ht(),Ad=Tt(),Hr=wt(),Cd=ai();K.DEFAULT_MAX_DEPTH=100;K.DEFAULT_INITIAL_BUFFER_SIZE=2048;var li=class t{extensionCodec;context;useBigInt64;maxDepth;initialBufferSize;sortKeys;forceFloat32;ignoreUndefined;forceIntegerToFloat;pos;view;bytes;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??Ad.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.maxDepth=e?.maxDepth??K.DEFAULT_MAX_DEPTH,this.initialBufferSize=e?.initialBufferSize??K.DEFAULT_INITIAL_BUFFER_SIZE,this.sortKeys=e?.sortKeys??!1,this.forceFloat32=e?.forceFloat32??!1,this.ignoreUndefined=e?.ignoreUndefined??!1,this.forceIntegerToFloat=e?.forceIntegerToFloat??!1,this.pos=0,this.view=new DataView(new ArrayBuffer(this.initialBufferSize)),this.bytes=new Uint8Array(this.view.buffer)}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,maxDepth:this.maxDepth,initialBufferSize:this.initialBufferSize,sortKeys:this.sortKeys,forceFloat32:this.forceFloat32,ignoreUndefined:this.ignoreUndefined,forceIntegerToFloat:this.forceIntegerToFloat})}reinitializeState(){this.pos=0}encodeSharedRef(e){if(this.entered)return this.clone().encodeSharedRef(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.subarray(0,this.pos)}finally{this.entered=!1}}encode(e){if(this.entered)return this.clone().encode(e);try{return this.entered=!0,this.reinitializeState(),this.doEncode(e,1),this.bytes.slice(0,this.pos)}finally{this.entered=!1}}doEncode(e,i){if(i>this.maxDepth)throw new Error(`Too deep objects in depth ${i}`);e==null?this.encodeNil():typeof e=="boolean"?this.encodeBoolean(e):typeof e=="number"?this.forceIntegerToFloat?this.encodeNumberAsFloat(e):this.encodeNumber(e):typeof e=="string"?this.encodeString(e):this.useBigInt64&&typeof e=="bigint"?this.encodeBigInt64(e):this.encodeObject(e,i)}ensureBufferSizeToWrite(e){let i=this.pos+e;this.view.byteLength<i&&this.resizeBuffer(i*2)}resizeBuffer(e){let i=new ArrayBuffer(e),r=new Uint8Array(i),n=new DataView(i);r.set(this.bytes),this.view=n,this.bytes=r}encodeNil(){this.writeU8(192)}encodeBoolean(e){e===!1?this.writeU8(194):this.writeU8(195)}encodeNumber(e){!this.forceIntegerToFloat&&Number.isSafeInteger(e)?e>=0?e<128?this.writeU8(e):e<256?(this.writeU8(204),this.writeU8(e)):e<65536?(this.writeU8(205),this.writeU16(e)):e<4294967296?(this.writeU8(206),this.writeU32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(207),this.writeU64(e)):e>=-32?this.writeU8(224|e+32):e>=-128?(this.writeU8(208),this.writeI8(e)):e>=-32768?(this.writeU8(209),this.writeI16(e)):e>=-2147483648?(this.writeU8(210),this.writeI32(e)):this.useBigInt64?this.encodeNumberAsFloat(e):(this.writeU8(211),this.writeI64(e)):this.encodeNumberAsFloat(e)}encodeNumberAsFloat(e){this.forceFloat32?(this.writeU8(202),this.writeF32(e)):(this.writeU8(203),this.writeF64(e))}encodeBigInt64(e){e>=BigInt(0)?(this.writeU8(207),this.writeBigUint64(e)):(this.writeU8(211),this.writeBigInt64(e))}writeStringHeader(e){if(e<32)this.writeU8(160+e);else if(e<256)this.writeU8(217),this.writeU8(e);else if(e<65536)this.writeU8(218),this.writeU16(e);else if(e<4294967296)this.writeU8(219),this.writeU32(e);else throw new Error(`Too long string: ${e} bytes in UTF-8`)}encodeString(e){let r=(0,Kr.utf8Count)(e);this.ensureBufferSizeToWrite(5+r),this.writeStringHeader(r),(0,Kr.utf8Encode)(e,this.bytes,this.pos),this.pos+=r}encodeObject(e,i){let r=this.extensionCodec.tryToEncode(e,this.context);if(r!=null)this.encodeExtension(r);else if(Array.isArray(e))this.encodeArray(e,i);else if(ArrayBuffer.isView(e))this.encodeBinary(e);else if(typeof e=="object")this.encodeMap(e,i);else throw new Error(`Unrecognized object: ${Object.prototype.toString.apply(e)}`)}encodeBinary(e){let i=e.byteLength;if(i<256)this.writeU8(196),this.writeU8(i);else if(i<65536)this.writeU8(197),this.writeU16(i);else if(i<4294967296)this.writeU8(198),this.writeU32(i);else throw new Error(`Too large binary: ${i}`);let r=(0,Cd.ensureUint8Array)(e);this.writeU8a(r)}encodeArray(e,i){let r=e.length;if(r<16)this.writeU8(144+r);else if(r<65536)this.writeU8(220),this.writeU16(r);else if(r<4294967296)this.writeU8(221),this.writeU32(r);else throw new Error(`Too large array: ${r}`);for(let n of e)this.doEncode(n,i+1)}countWithoutUndefined(e,i){let r=0;for(let n of i)e[n]!==void 0&&r++;return r}encodeMap(e,i){let r=Object.keys(e);this.sortKeys&&r.sort();let n=this.ignoreUndefined?this.countWithoutUndefined(e,r):r.length;if(n<16)this.writeU8(128+n);else if(n<65536)this.writeU8(222),this.writeU16(n);else if(n<4294967296)this.writeU8(223),this.writeU32(n);else throw new Error(`Too large map object: ${n}`);for(let o of r){let s=e[o];this.ignoreUndefined&&s===void 0||(this.encodeString(o),this.doEncode(s,i+1))}}encodeExtension(e){if(typeof e.data=="function"){let r=e.data(this.pos+6),n=r.length;if(n>=4294967296)throw new Error(`Too large extension object: ${n}`);this.writeU8(201),this.writeU32(n),this.writeI8(e.type),this.writeU8a(r);return}let i=e.data.length;if(i===1)this.writeU8(212);else if(i===2)this.writeU8(213);else if(i===4)this.writeU8(214);else if(i===8)this.writeU8(215);else if(i===16)this.writeU8(216);else if(i<256)this.writeU8(199),this.writeU8(i);else if(i<65536)this.writeU8(200),this.writeU16(i);else if(i<4294967296)this.writeU8(201),this.writeU32(i);else throw new Error(`Too large extension object: ${i}`);this.writeI8(e.type),this.writeU8a(e.data)}writeU8(e){this.ensureBufferSizeToWrite(1),this.view.setUint8(this.pos,e),this.pos++}writeU8a(e){let i=e.length;this.ensureBufferSizeToWrite(i),this.bytes.set(e,this.pos),this.pos+=i}writeI8(e){this.ensureBufferSizeToWrite(1),this.view.setInt8(this.pos,e),this.pos++}writeU16(e){this.ensureBufferSizeToWrite(2),this.view.setUint16(this.pos,e),this.pos+=2}writeI16(e){this.ensureBufferSizeToWrite(2),this.view.setInt16(this.pos,e),this.pos+=2}writeU32(e){this.ensureBufferSizeToWrite(4),this.view.setUint32(this.pos,e),this.pos+=4}writeI32(e){this.ensureBufferSizeToWrite(4),this.view.setInt32(this.pos,e),this.pos+=4}writeF32(e){this.ensureBufferSizeToWrite(4),this.view.setFloat32(this.pos,e),this.pos+=4}writeF64(e){this.ensureBufferSizeToWrite(8),this.view.setFloat64(this.pos,e),this.pos+=8}writeU64(e){this.ensureBufferSizeToWrite(8),(0,Hr.setUint64)(this.view,this.pos,e),this.pos+=8}writeI64(e){this.ensureBufferSizeToWrite(8),(0,Hr.setInt64)(this.view,this.pos,e),this.pos+=8}writeBigUint64(e){this.ensureBufferSizeToWrite(8),this.view.setBigUint64(this.pos,e),this.pos+=8}writeBigInt64(e){this.ensureBufferSizeToWrite(8),this.view.setBigInt64(this.pos,e),this.pos+=8}};K.Encoder=li});var Gr=_(di=>{"use strict";Object.defineProperty(di,"__esModule",{value:!0});di.encode=Pd;var kd=ui();function Pd(t,e){return new kd.Encoder(e).encodeSharedRef(t)}});var Qr=_(ci=>{"use strict";Object.defineProperty(ci,"__esModule",{value:!0});ci.prettyByte=qd;function qd(t){return`${t<0?"-":""}0x${Math.abs(t).toString(16).padStart(2,"0")}`}});var Wr=_(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.CachedKeyDecoder=void 0;var Vd=ht(),Md=16,Dd=16,pi=class{hit=0;miss=0;caches;maxKeyLength;maxLengthPerKey;constructor(e=Md,i=Dd){this.maxKeyLength=e,this.maxLengthPerKey=i,this.caches=[];for(let r=0;r<this.maxKeyLength;r++)this.caches.push([])}canBeCached(e){return e>0&&e<=this.maxKeyLength}find(e,i,r){let n=this.caches[r-1];e:for(let o of n){let s=o.bytes;for(let l=0;l<r;l++)if(s[l]!==e[i+l])continue e;return o.str}return null}store(e,i){let r=this.caches[e.length-1],n={bytes:e,str:i};r.length>=this.maxLengthPerKey?r[Math.random()*r.length|0]=n:r.push(n)}decode(e,i,r){let n=this.find(e,i,r);if(n!=null)return this.hit++,n;this.miss++;let o=(0,Vd.utf8DecodeJs)(e,i,r),s=Uint8Array.prototype.slice.call(e,i,i+r);return this.store(s,o),o}};It.CachedKeyDecoder=pi});var Et=_(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.Decoder=void 0;var mi=Qr(),jd=Tt(),pe=wt(),Od=ht(),Yr=ai(),Fd=Wr(),Y=vt(),fi="array",Ke="map_key",Jr="map_value",Rd=t=>{if(typeof t=="string"||typeof t=="number")return t;throw new Y.DecodeError("The type of key must be string or number but "+typeof t)},gi=class{stack=[];stackHeadPosition=-1;get length(){return this.stackHeadPosition+1}top(){return this.stack[this.stackHeadPosition]}pushArrayState(e){let i=this.getUninitializedStateFromPool();i.type=fi,i.position=0,i.size=e,i.array=new Array(e)}pushMapState(e){let i=this.getUninitializedStateFromPool();i.type=Ke,i.readCount=0,i.size=e,i.map={}}getUninitializedStateFromPool(){if(this.stackHeadPosition++,this.stackHeadPosition===this.stack.length){let e={type:void 0,size:0,array:void 0,position:0,readCount:0,map:void 0,key:null};this.stack.push(e)}return this.stack[this.stackHeadPosition]}release(e){if(this.stack[this.stackHeadPosition]!==e)throw new Error("Invalid stack state. Released state is not on top of the stack.");if(e.type===fi){let r=e;r.size=0,r.array=void 0,r.position=0,r.type=void 0}if(e.type===Ke||e.type===Jr){let r=e;r.size=0,r.map=void 0,r.readCount=0,r.type=void 0}this.stackHeadPosition--}reset(){this.stack.length=0,this.stackHeadPosition=-1}},Be=-1,yi=new DataView(new ArrayBuffer(0)),Ud=new Uint8Array(yi.buffer);try{yi.getInt8(0)}catch(t){if(!(t instanceof RangeError))throw new Error("This module is not supported in the current JavaScript engine because DataView does not throw RangeError on out-of-bounds access")}var Zr=new RangeError("Insufficient data"),Ld=new Fd.CachedKeyDecoder,hi=class t{extensionCodec;context;useBigInt64;rawStrings;maxStrLength;maxBinLength;maxArrayLength;maxMapLength;maxExtLength;keyDecoder;mapKeyConverter;totalPos=0;pos=0;view=yi;bytes=Ud;headByte=Be;stack=new gi;entered=!1;constructor(e){this.extensionCodec=e?.extensionCodec??jd.ExtensionCodec.defaultCodec,this.context=e?.context,this.useBigInt64=e?.useBigInt64??!1,this.rawStrings=e?.rawStrings??!1,this.maxStrLength=e?.maxStrLength??pe.UINT32_MAX,this.maxBinLength=e?.maxBinLength??pe.UINT32_MAX,this.maxArrayLength=e?.maxArrayLength??pe.UINT32_MAX,this.maxMapLength=e?.maxMapLength??pe.UINT32_MAX,this.maxExtLength=e?.maxExtLength??pe.UINT32_MAX,this.keyDecoder=e?.keyDecoder!==void 0?e.keyDecoder:Ld,this.mapKeyConverter=e?.mapKeyConverter??Rd}clone(){return new t({extensionCodec:this.extensionCodec,context:this.context,useBigInt64:this.useBigInt64,rawStrings:this.rawStrings,maxStrLength:this.maxStrLength,maxBinLength:this.maxBinLength,maxArrayLength:this.maxArrayLength,maxMapLength:this.maxMapLength,maxExtLength:this.maxExtLength,keyDecoder:this.keyDecoder})}reinitializeState(){this.totalPos=0,this.headByte=Be,this.stack.reset()}setBuffer(e){let i=(0,Yr.ensureUint8Array)(e);this.bytes=i,this.view=new DataView(i.buffer,i.byteOffset,i.byteLength),this.pos=0}appendBuffer(e){if(this.headByte===Be&&!this.hasRemaining(1))this.setBuffer(e);else{let i=this.bytes.subarray(this.pos),r=(0,Yr.ensureUint8Array)(e),n=new Uint8Array(i.length+r.length);n.set(i),n.set(r,i.length),this.setBuffer(n)}}hasRemaining(e){return this.view.byteLength-this.pos>=e}createExtraByteError(e){let{view:i,pos:r}=this;return new RangeError(`Extra ${i.byteLength-r} of ${i.byteLength} byte(s) found at buffer[${e}]`)}decode(e){if(this.entered)return this.clone().decode(e);try{this.entered=!0,this.reinitializeState(),this.setBuffer(e);let i=this.doDecodeSync();if(this.hasRemaining(1))throw this.createExtraByteError(this.pos);return i}finally{this.entered=!1}}*decodeMulti(e){if(this.entered){yield*this.clone().decodeMulti(e);return}try{for(this.entered=!0,this.reinitializeState(),this.setBuffer(e);this.hasRemaining(1);)yield this.doDecodeSync()}finally{this.entered=!1}}async decodeAsync(e){if(this.entered)return this.clone().decodeAsync(e);try{this.entered=!0;let i=!1,r;for await(let l of e){if(i)throw this.entered=!1,this.createExtraByteError(this.totalPos);this.appendBuffer(l);try{r=this.doDecodeSync(),i=!0}catch(u){if(!(u instanceof RangeError))throw u}this.totalPos+=this.pos}if(i){if(this.hasRemaining(1))throw this.createExtraByteError(this.totalPos);return r}let{headByte:n,pos:o,totalPos:s}=this;throw new RangeError(`Insufficient data in parsing ${(0,mi.prettyByte)(n)} at ${s} (${o} in the current buffer)`)}finally{this.entered=!1}}decodeArrayStream(e){return this.decodeMultiAsync(e,!0)}decodeStream(e){return this.decodeMultiAsync(e,!1)}async*decodeMultiAsync(e,i){if(this.entered){yield*this.clone().decodeMultiAsync(e,i);return}try{this.entered=!0;let r=i,n=-1;for await(let o of e){if(i&&n===0)throw this.createExtraByteError(this.totalPos);this.appendBuffer(o),r&&(n=this.readArraySize(),r=!1,this.complete());try{for(;yield this.doDecodeSync(),--n!==0;);}catch(s){if(!(s instanceof RangeError))throw s}this.totalPos+=this.pos}}finally{this.entered=!1}}doDecodeSync(){e:for(;;){let e=this.readHeadByte(),i;if(e>=224)i=e-256;else if(e<192)if(e<128)i=e;else if(e<144){let n=e-128;if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(e<160){let n=e-144;if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else{let n=e-160;i=this.decodeString(n,0)}else if(e===192)i=null;else if(e===194)i=!1;else if(e===195)i=!0;else if(e===202)i=this.readF32();else if(e===203)i=this.readF64();else if(e===204)i=this.readU8();else if(e===205)i=this.readU16();else if(e===206)i=this.readU32();else if(e===207)this.useBigInt64?i=this.readU64AsBigInt():i=this.readU64();else if(e===208)i=this.readI8();else if(e===209)i=this.readI16();else if(e===210)i=this.readI32();else if(e===211)this.useBigInt64?i=this.readI64AsBigInt():i=this.readI64();else if(e===217){let n=this.lookU8();i=this.decodeString(n,1)}else if(e===218){let n=this.lookU16();i=this.decodeString(n,2)}else if(e===219){let n=this.lookU32();i=this.decodeString(n,4)}else if(e===220){let n=this.readU16();if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else if(e===221){let n=this.readU32();if(n!==0){this.pushArrayState(n),this.complete();continue e}else i=[]}else if(e===222){let n=this.readU16();if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(e===223){let n=this.readU32();if(n!==0){this.pushMapState(n),this.complete();continue e}else i={}}else if(e===196){let n=this.lookU8();i=this.decodeBinary(n,1)}else if(e===197){let n=this.lookU16();i=this.decodeBinary(n,2)}else if(e===198){let n=this.lookU32();i=this.decodeBinary(n,4)}else if(e===212)i=this.decodeExtension(1,0);else if(e===213)i=this.decodeExtension(2,0);else if(e===214)i=this.decodeExtension(4,0);else if(e===215)i=this.decodeExtension(8,0);else if(e===216)i=this.decodeExtension(16,0);else if(e===199){let n=this.lookU8();i=this.decodeExtension(n,1)}else if(e===200){let n=this.lookU16();i=this.decodeExtension(n,2)}else if(e===201){let n=this.lookU32();i=this.decodeExtension(n,4)}else throw new Y.DecodeError(`Unrecognized type byte: ${(0,mi.prettyByte)(e)}`);this.complete();let r=this.stack;for(;r.length>0;){let n=r.top();if(n.type===fi)if(n.array[n.position]=i,n.position++,n.position===n.size)i=n.array,r.release(n);else continue e;else if(n.type===Ke){if(i==="__proto__")throw new Y.DecodeError("The key __proto__ is not allowed");n.key=this.mapKeyConverter(i),n.type=Jr;continue e}else if(n.map[n.key]=i,n.readCount++,n.readCount===n.size)i=n.map,r.release(n);else{n.key=null,n.type=Ke;continue e}}return i}}readHeadByte(){return this.headByte===Be&&(this.headByte=this.readU8()),this.headByte}complete(){this.headByte=Be}readArraySize(){let e=this.readHeadByte();switch(e){case 220:return this.readU16();case 221:return this.readU32();default:{if(e<160)return e-144;throw new Y.DecodeError(`Unrecognized array type byte: ${(0,mi.prettyByte)(e)}`)}}}pushMapState(e){if(e>this.maxMapLength)throw new Y.DecodeError(`Max length exceeded: map length (${e}) > maxMapLengthLength (${this.maxMapLength})`);this.stack.pushMapState(e)}pushArrayState(e){if(e>this.maxArrayLength)throw new Y.DecodeError(`Max length exceeded: array length (${e}) > maxArrayLength (${this.maxArrayLength})`);this.stack.pushArrayState(e)}decodeString(e,i){return!this.rawStrings||this.stateIsMapKey()?this.decodeUtf8String(e,i):this.decodeBinary(e,i)}decodeUtf8String(e,i){if(e>this.max